Toby Chui 2 недель назад
Родитель
Сommit
64c566585e

+ 78 - 0
src/web/Blocky/README.md

@@ -0,0 +1,78 @@
+# Blocky
+
+An original voxel sandbox game for the ArozOS desktop: generated worlds with
+grassland, forest, desert and ocean biomes, survival (health, hunger,
+crafting, smelting) and creative modes, day / night, rain and thunderstorms.
+There are no creatures. All textures and sounds are generated in code and
+three.js is vendored in `lib/three/`, so the app loads nothing from outside
+its folder.
+
+## Files
+
+| File | What it does |
+|---|---|
+| `init.agi` | Registers the module (group `Games`, float window). |
+| `backend/worlds.agi` | World storage in `user:/.appdata/Blocky/worlds/<id>/`. |
+| `js/main.js` | Boot, start screen with the live world preview, world list, settings, pause / death screens. |
+| `js/game.js` | One running world: ticks, input to actions, weather, day cycle, saving. |
+| `js/world.js` | Chunks, light propagation, block updates (water, falling sand, plants, leaf decay, furnaces), raycast, save encoding. |
+| `js/worldgen.js` | Deterministic terrain, biomes, caves, ores, trees, plants. |
+| `js/mesher.js` | Section meshing (smooth light + ambient occlusion) and item models. |
+| `js/render.js` | three.js scene, terrain shader, sky, clouds, rain, lightning, selection, particles, held item. |
+| `js/blocks.js` | Block / item registry, mining rules, shaped recipes and the grid matcher, smelting. |
+| `js/player.js`, `js/physics.js` | Movement, collisions, survival stats. |
+| `js/ui.js`, `js/icons.js` | HUD, inventory / workbench / furnace / chest / creative screens, icon sheet. |
+| `js/chat.js`, `js/commands.js` | Chat line and slash commands. |
+| `js/textures.js` | Procedural pixel art for every tile, crack overlays and isometric icons. |
+| `js/audio.js` | Web Audio synthesised sounds. |
+| `js/storage.js` | AGI backend client with an IndexedDB fallback when run standalone. |
+
+## Engine notes
+
+- Chunks are 16 x 128 x 16, indexed `(x << 11) | (z << 7) | y`, and meshed as
+  eight 16-high sections. A chunk is lit once its 8 neighbours are generated
+  and meshed once its 8 neighbours are lit, so streaming generates
+  `renderDistance + 2` chunks out.
+- Light is sky + block light (4 bits each). Changes use the removal / refill
+  flood; sky light at level 15 travels straight down without loss.
+- All tiles live in one `DataArrayTexture` so mipmaps never bleed between
+  tiles; the terrain shader is GLSL3 (`render.js`).
+- Trees can cross chunk borders because column height and biome come from 2D
+  noise alone: every chunk re-derives its neighbours' trees and stamps the
+  part inside itself.
+- Random tick changes such as grass spreading or reeds growing do not mark a
+  chunk as modified (`world.quiet`), so untouched chunks never enter the save.
+
+## Crafting
+
+The inventory has a 2 x 2 grid, a workbench a 3 x 3 grid. Recipes are shaped
+(mirroring allowed) or shapeless; `matchRecipe` in `blocks.js` normalises the
+grid to the bounding box of its items. A recipe whose pattern fits in 2 x 2
+(`small`) also works in the inventory. The recipe book beside the grid lays a
+recipe out from the inventory (shift click for as many as possible).
+
+## Saves
+
+A save is `JSON.stringify({encoding, data})` where `data` is the deflated
+world state: player, inventory, time, spawn, dropped items, tile entities and
+run-length encoded block / meta arrays of modified chunks. The backend splits
+it into 3 MB parts (`data.<generation>.<index>`) and writes `meta.json` last,
+so an interrupted save keeps the previous generation readable. Weather is not
+restored: every session starts with clear skies.
+
+## Commands
+
+T opens the chat line, / opens it with a slash. Commands other than `/help`
+and `/seed` need the world's cheats option (also switchable in the pause
+menu): `/give`, `/tp` (`~` relative, y optional), `/time`, `/weather`,
+`/gamemode`, `/difficulty`, `/setblock`, `/clear`, `/heal`, `/kill`,
+`/spawnpoint`.
+
+## Testing standalone
+
+Serve `src/web` statically (the `webroot-static` launch config) and open
+`/Blocky/index.html`; worlds then go to IndexedDB. The Browser pane cannot
+hold a pointer lock, so scripted tests fake it with
+`Object.defineProperty(blocky.input, "locked", { get: () => true })` and push
+key codes into `blocky.input.keys` / `pressed` and buttons into
+`blocky.input.buttons` / `clicked`. `window.blocky` is the app object.

+ 192 - 0
src/web/Blocky/backend/worlds.agi

@@ -0,0 +1,192 @@
+/*
+    Blocky - world storage backend
+
+    Worlds are kept per user in user:/.appdata/Blocky/worlds/<id>/:
+        meta.json           - name, seed, mode, difficulty, generation, part count
+        data.<gen>.<index>  - the compressed world payload, split in parts so a
+                              single POST never gets near the form size limit
+
+    A save writes every part of a new generation first and the meta file last,
+    then removes the parts of older generations; an interrupted save therefore
+    leaves the previous generation readable.
+
+    POST parameters:
+        action  - list | meta | loadpart | savepart | savemeta | delete
+        id      - world id ([A-Za-z0-9_-], up to 48 characters)
+        gen     - generation number (savepart / loadpart)
+        index   - part index (savepart / loadpart)
+        data    - part content (savepart)
+        meta    - JSON meta object (savemeta)
+*/
+
+var WORLDS = "user:/.appdata/Blocky/worlds/";
+
+function respond(obj) {
+    sendJSONResp(JSON.stringify(obj));
+}
+
+function fail(msg) {
+    respond({ ok: false, error: msg });
+}
+
+function validId(s) {
+    return typeof s === "string" && /^[A-Za-z0-9_-]{1,48}$/.test(s);
+}
+
+//Non negative integer given as a plain decimal string, or -1
+function toInt(s, max) {
+    if (typeof s === "undefined" || !/^[0-9]{1,9}$/.test(String(s))) {
+        return -1;
+    }
+    var n = parseInt(s, 10);
+    return n <= max ? n : -1;
+}
+
+function ensureDir(p) {
+    if (!filelib.fileExists(p)) {
+        filelib.mkdir(p);
+    }
+}
+
+function listDir(p) {
+    if (!filelib.fileExists(p)) {
+        return [];
+    }
+    var entries = filelib.readdir(p, "default");
+    return entries ? entries : [];
+}
+
+function main() {
+    if (!requirelib("filelib")) {
+        fail("filelib unavailable");
+        return;
+    }
+    if (typeof action === "undefined") {
+        fail("action is required");
+        return;
+    }
+
+    if (action === "list") {
+        var worlds = [];
+        var dirs = listDir(WORLDS);
+        for (var i = 0; i < dirs.length; i++) {
+            if (!dirs[i].IsDir || !validId(dirs[i].Filename)) {
+                continue;
+            }
+            var mp = WORLDS + dirs[i].Filename + "/meta.json";
+            if (!filelib.fileExists(mp)) {
+                continue;
+            }
+            try {
+                var m = JSON.parse(filelib.readFile(mp));
+                m.id = dirs[i].Filename;
+                worlds.push(m);
+            } catch (e) {
+                //Skip unreadable worlds
+            }
+        }
+        respond({ ok: true, worlds: worlds });
+        return;
+    }
+
+    if (typeof id === "undefined" || !validId(id)) {
+        fail("invalid world id");
+        return;
+    }
+    var dir = WORLDS + id + "/";
+
+    if (action === "meta") {
+        if (!filelib.fileExists(dir + "meta.json")) {
+            fail("world not found");
+            return;
+        }
+        respond({ ok: true, meta: JSON.parse(filelib.readFile(dir + "meta.json")) });
+        return;
+    }
+
+    if (action === "loadpart") {
+        var lg = toInt(gen, 999999999), li = toInt(index, 999);
+        if (lg < 0 || li < 0) {
+            fail("invalid part");
+            return;
+        }
+        var lp = dir + "data." + lg + "." + li;
+        if (!filelib.fileExists(lp)) {
+            fail("part not found");
+            return;
+        }
+        respond({ ok: true, data: filelib.readFile(lp) });
+        return;
+    }
+
+    if (action === "savepart") {
+        var sg = toInt(gen, 999999999), si = toInt(index, 999);
+        if (sg < 0 || si < 0 || typeof data === "undefined") {
+            fail("invalid part");
+            return;
+        }
+        ensureDir(dir);
+        if (!filelib.writeFile(dir + "data." + sg + "." + si, data)) {
+            fail("unable to write world data");
+            return;
+        }
+        respond({ ok: true });
+        return;
+    }
+
+    if (action === "savemeta") {
+        var parsed;
+        try {
+            parsed = JSON.parse(meta);
+        } catch (e) {
+            fail("meta must be valid JSON");
+            return;
+        }
+        var mg = toInt(String(parsed.gen), 999999999), mparts = toInt(String(parsed.parts), 999);
+        if (mg < 0 || mparts < 1) {
+            fail("invalid meta");
+            return;
+        }
+        //Every part of this generation must be on disk before it becomes current
+        for (var k = 0; k < mparts; k++) {
+            if (!filelib.fileExists(dir + "data." + mg + "." + k)) {
+                fail("missing part " + k);
+                return;
+            }
+        }
+        parsed.id = id;
+        if (!filelib.writeFile(dir + "meta.json", JSON.stringify(parsed))) {
+            fail("unable to write meta");
+            return;
+        }
+        //Remove parts that belong to other generations
+        var files = listDir(dir);
+        for (var f = 0; f < files.length; f++) {
+            var name = files[f].Filename;
+            var mm = /^data\.([0-9]+)\.([0-9]+)$/.exec(name);
+            if (mm && (parseInt(mm[1], 10) !== mg || parseInt(mm[2], 10) >= mparts)) {
+                filelib.deleteFile(dir + name);
+            }
+        }
+        respond({ ok: true });
+        return;
+    }
+
+    if (action === "delete") {
+        var all = listDir(dir);
+        for (var d = 0; d < all.length; d++) {
+            if (!all[d].IsDir) {
+                filelib.deleteFile(dir + all[d].Filename);
+            }
+        }
+        if (filelib.fileExists(dir)) {
+            filelib.deleteFile(dir);
+        }
+        respond({ ok: true });
+        return;
+    }
+
+    fail("unknown action");
+}
+
+main();

+ 1230 - 0
src/web/Blocky/css/style.css

@@ -0,0 +1,1230 @@
+/*
+    Blocky - style.css
+*/
+
+:root {
+    --panel: rgba(24, 26, 31, 0.92);
+    --panel-edge: #0b0c0e;
+    --panel-hi: rgba(255, 255, 255, 0.08);
+    --text: #eef0f2;
+    --muted: #a7adb6;
+    --accent: #7cc35a;
+    --accent-dark: #3f7a2a;
+    --slot: #15171b;
+    --slot-edge: #3a3e46;
+    --danger: #c0443a;
+    --font: "Segoe UI", system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif;
+}
+
+* {
+    box-sizing: border-box;
+}
+
+html,
+body {
+    margin: 0;
+    height: 100%;
+    overflow: hidden;
+    background: #1b1d22;
+    color: var(--text);
+    font-family: var(--font);
+    user-select: none;
+    -webkit-user-select: none;
+    -webkit-tap-highlight-color: transparent;
+}
+
+#view {
+    position: fixed;
+    inset: 0;
+    width: 100%;
+    height: 100%;
+    display: block;
+    image-rendering: pixelated;
+    touch-action: none;
+}
+
+.hidden {
+    display: none !important;
+}
+
+/* ---------------- buttons & boxes ---------------- */
+
+.btn {
+    font: 600 15px var(--font);
+    color: var(--text);
+    background: linear-gradient(#6c7079, #4f535b);
+    border: 2px solid #111215;
+    box-shadow: inset 2px 2px 0 rgba(255, 255, 255, 0.22), inset -2px -2px 0 rgba(0, 0, 0, 0.35);
+    text-shadow: 1px 1px 0 #1a1a1a;
+    padding: 9px 16px;
+    min-height: 40px;
+    cursor: pointer;
+    border-radius: 2px;
+}
+
+.btn:hover:not(:disabled) {
+    background: linear-gradient(#7aa063, #55783f);
+}
+
+.btn:active:not(:disabled) {
+    box-shadow: inset -2px -2px 0 rgba(255, 255, 255, 0.15), inset 2px 2px 0 rgba(0, 0, 0, 0.35);
+}
+
+.btn:disabled {
+    opacity: 0.45;
+    cursor: default;
+}
+
+.btn.on {
+    background: linear-gradient(#78b356, #4b7f33);
+}
+
+.btn.danger:hover {
+    background: linear-gradient(#d65a4f, #9e3229);
+}
+
+.btn.wide {
+    width: 320px;
+    max-width: 100%;
+    display: block;
+    margin: 6px auto;
+}
+
+.box {
+    background: var(--panel);
+    border: 2px solid var(--panel-edge);
+    box-shadow: inset 0 0 0 1px var(--panel-hi), 0 12px 40px rgba(0, 0, 0, 0.5);
+    padding: 18px 22px;
+    max-width: min(640px, calc(100vw - 32px));
+    max-height: calc(100vh - 32px);
+    overflow: auto;
+}
+
+.box.center {
+    text-align: center;
+}
+
+.box h1,
+.box h2 {
+    margin: 0 0 12px;
+    text-shadow: 2px 2px 0 #000;
+}
+
+.box p {
+    color: var(--muted);
+    line-height: 1.5;
+}
+
+.row {
+    display: flex;
+    gap: 8px;
+    margin-top: 10px;
+    flex-wrap: wrap;
+}
+
+.row .btn {
+    flex: 1 1 180px;
+}
+
+.field {
+    display: block;
+    margin: 10px 0;
+    text-align: left;
+    font-weight: 600;
+}
+
+.field small,
+.field input {
+    display: block;
+    font-weight: 400;
+}
+
+.field small {
+    color: var(--muted);
+    margin-top: 4px;
+}
+
+.field input[type=text] {
+    width: 100%;
+    margin-top: 6px;
+    padding: 9px 10px;
+    font: 15px var(--font);
+    color: var(--text);
+    background: #0e0f12;
+    border: 2px solid #3a3e46;
+    outline: none;
+}
+
+.field input[type=text]:focus {
+    border-color: var(--accent);
+}
+
+.toggle {
+    display: flex;
+    gap: 4px;
+    margin-top: 6px;
+    flex-wrap: wrap;
+}
+
+.toggle .btn {
+    flex: 1 1 0;
+    min-width: 80px;
+    padding: 7px 8px;
+}
+
+.check {
+    display: flex;
+    align-items: center;
+    gap: 8px;
+    margin: 8px 0;
+    color: var(--text);
+    text-align: left;
+    cursor: pointer;
+}
+
+.check input {
+    width: 18px;
+    height: 18px;
+    accent-color: var(--accent);
+}
+
+.overlay {
+    position: fixed;
+    inset: 0;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    background: rgba(0, 0, 0, 0.5);
+    z-index: 40;
+    padding: 16px;
+}
+
+.overlay.death {
+    background: rgba(120, 10, 10, 0.45);
+}
+
+.overlay.death h1 {
+    font-size: 40px;
+    color: #ffdcdc;
+}
+
+.clickable {
+    cursor: pointer;
+}
+
+/* ---------------- start menu ---------------- */
+
+#menu {
+    position: fixed;
+    inset: 0;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    padding: 4vh 16px 16px;
+    z-index: 30;
+    background: radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 40%, rgba(0, 0, 0, 0.45));
+    overflow-y: auto;
+}
+
+#logo {
+    width: min(560px, 90vw);
+    height: auto;
+    image-rendering: pixelated;
+    filter: drop-shadow(0 6px 10px rgba(0, 0, 0, 0.55));
+}
+
+.tagline {
+    color: #ffe680;
+    font-weight: 700;
+    text-shadow: 2px 2px 0 #3b2d00;
+    margin: 4px 0 24px;
+    transform: rotate(-2deg);
+    animation: pulse 1.8s ease-in-out infinite;
+}
+
+@keyframes pulse {
+    50% {
+        transform: rotate(-2deg) scale(1.06);
+    }
+}
+
+.page {
+    width: 100%;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+}
+
+.page .box {
+    width: 560px;
+}
+
+.worldlist {
+    max-height: 42vh;
+    min-height: 120px;
+    overflow-y: auto;
+    background: rgba(0, 0, 0, 0.35);
+    border: 2px solid #0b0c0e;
+    padding: 4px;
+}
+
+.world {
+    padding: 10px 12px;
+    border: 2px solid transparent;
+    cursor: pointer;
+    display: flex;
+    justify-content: space-between;
+    gap: 12px;
+}
+
+.world:hover {
+    background: rgba(255, 255, 255, 0.06);
+}
+
+.world.sel {
+    border-color: #d8d8d8;
+    background: rgba(255, 255, 255, 0.08);
+}
+
+.world b {
+    display: block;
+    font-size: 16px;
+}
+
+.world span {
+    color: var(--muted);
+    font-size: 13px;
+}
+
+.world .wmeta {
+    text-align: right;
+    flex-shrink: 0;
+}
+
+.empty {
+    color: var(--muted);
+    text-align: center;
+    padding: 36px 12px;
+}
+
+.footer {
+    margin-top: auto;
+    padding-top: 16px;
+    color: rgba(255, 255, 255, 0.75);
+    font-size: 12px;
+    text-shadow: 1px 1px 0 #000;
+}
+
+.settings-grid {
+    display: grid;
+    grid-template-columns: 1fr 1fr;
+    gap: 6px 22px;
+}
+
+.settings-grid label:not(.check) {
+    display: flex;
+    flex-direction: column;
+    font-weight: 600;
+    font-size: 14px;
+}
+
+.settings-grid label b {
+    position: absolute;
+    right: 0;
+}
+
+.settings-grid label:not(.check) {
+    position: relative;
+}
+
+.settings-grid input[type=range] {
+    margin-top: 6px;
+    accent-color: var(--accent);
+}
+
+.helpgrid {
+    display: grid;
+    gap: 8px;
+    font-size: 14px;
+}
+
+.helpgrid b {
+    color: #ffe680;
+}
+
+.progress {
+    width: 360px;
+    max-width: 100%;
+    height: 14px;
+    background: #0d0e10;
+    border: 2px solid #3a3e46;
+    margin: 6px auto;
+}
+
+.progress i {
+    display: block;
+    height: 100%;
+    width: 0;
+    background: linear-gradient(#8fd66a, #4f8f34);
+    transition: width 0.15s;
+}
+
+/* Pause menu: two columns of buttons so it fits short, wide windows */
+.overlay.dim {
+    background: rgba(8, 9, 12, 0.62);
+}
+
+.menugrid {
+    display: grid;
+    grid-template-columns: repeat(2, minmax(0, 290px));
+    gap: 8px 14px;
+    width: min(600px, 100%);
+    max-height: 100%;
+    overflow: auto;
+}
+
+.menugrid h2 {
+    text-align: center;
+    margin: 0 0 6px;
+    text-shadow: 2px 2px 0 #000;
+}
+
+.menugrid .span2 {
+    grid-column: 1 / -1;
+}
+
+.menugrid .btn {
+    width: 100%;
+}
+
+.menugrid .gap {
+    height: 4px;
+}
+
+.cmdlist {
+    display: grid;
+    gap: 6px;
+    margin-top: 8px;
+}
+
+.cmdlist div {
+    display: grid;
+    grid-template-columns: minmax(0, 1fr);
+    padding: 6px 8px;
+    background: rgba(0, 0, 0, 0.3);
+}
+
+.cmdlist code,
+.box code {
+    font: 13px Consolas, "Courier New", monospace;
+    color: #ffe680;
+}
+
+.cmdlist span {
+    color: var(--muted);
+    font-size: 13px;
+    margin-top: 2px;
+}
+
+/* Chat line and log */
+#chat {
+    position: fixed;
+    left: 8px;
+    bottom: 104px;
+    width: min(560px, calc(100vw - 16px));
+    z-index: 15;
+    pointer-events: none;
+}
+
+#chat.open {
+    pointer-events: auto;
+}
+
+#chatLog .line {
+    font: 14px/1.35 var(--font);
+    color: #fff;
+    text-shadow: 1px 1px 0 #000;
+    background: rgba(0, 0, 0, 0.42);
+    padding: 1px 8px;
+    white-space: pre-wrap;
+    word-break: break-word;
+    transition: opacity 1.5s;
+}
+
+#chatLog .line.error {
+    color: #ff9a8f;
+}
+
+#chatLog .line.ok {
+    color: #d6f5c4;
+}
+
+#chatLog .line.hint {
+    color: #c9cfd8;
+    font-size: 12px;
+}
+
+#chatLog .line.fading {
+    opacity: 0;
+}
+
+#chatInput {
+    width: 100%;
+    margin-top: 4px;
+    padding: 7px 9px;
+    font: 15px var(--font);
+    color: #fff;
+    background: rgba(0, 0, 0, 0.7);
+    border: 2px solid rgba(255, 255, 255, 0.35);
+    outline: none;
+}
+
+@media (max-width: 560px) {
+    .menugrid {
+        grid-template-columns: minmax(0, 1fr);
+    }
+}
+
+/* ---------------- HUD ---------------- */
+
+#hud {
+    position: fixed;
+    inset: 0;
+    pointer-events: none;
+    z-index: 10;
+}
+
+#hud.bare>*:not(#underwater):not(#hurt),
+body.screen-open #bottom,
+body.screen-open #crosshair {
+    visibility: hidden;
+}
+
+#crosshair {
+    position: absolute;
+    left: 50%;
+    top: 50%;
+    width: 22px;
+    height: 22px;
+    margin: -11px 0 0 -11px;
+    mix-blend-mode: difference;
+}
+
+#crosshair::before,
+#crosshair::after {
+    content: "";
+    position: absolute;
+    background: #fff;
+}
+
+#crosshair::before {
+    left: 10px;
+    top: 0;
+    width: 2px;
+    height: 22px;
+}
+
+#crosshair::after {
+    top: 10px;
+    left: 0;
+    height: 2px;
+    width: 22px;
+}
+
+#underwater {
+    position: absolute;
+    inset: 0;
+    background: rgba(20, 60, 160, 0.28);
+    opacity: 0;
+    transition: opacity 0.2s;
+}
+
+#underwater.on {
+    opacity: 1;
+}
+
+#hurt {
+    position: absolute;
+    inset: 0;
+    box-shadow: inset 0 0 120px rgba(200, 0, 0, 0.7);
+    opacity: 0;
+    transition: opacity 0.25s;
+}
+
+#hurt.on {
+    opacity: 1;
+    transition: none;
+}
+
+#debug {
+    position: absolute;
+    left: 6px;
+    top: 6px;
+    margin: 0;
+    font: 13px/1.35 Consolas, "Courier New", monospace;
+    color: #fff;
+    background: rgba(0, 0, 0, 0.45);
+    padding: 6px 8px;
+    white-space: pre;
+}
+
+#saving {
+    position: absolute;
+    right: 10px;
+    top: 10px;
+    font-size: 13px;
+    color: #fff;
+    background: rgba(0, 0, 0, 0.5);
+    padding: 4px 10px;
+}
+
+#message {
+    position: absolute;
+    left: 50%;
+    top: 22%;
+    transform: translateX(-50%);
+    font-weight: 700;
+    font-size: 18px;
+    text-shadow: 2px 2px 0 #000;
+    opacity: 0;
+    white-space: nowrap;
+}
+
+#message.fade,
+#itemName.fade {
+    animation: fadeout 2.6s forwards;
+}
+
+@keyframes fadeout {
+    0%,
+    70% {
+        opacity: 1;
+    }
+
+    100% {
+        opacity: 0;
+    }
+}
+
+#bottom {
+    position: absolute;
+    left: 50%;
+    bottom: 8px;
+    transform: translateX(-50%);
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+}
+
+#itemName {
+    font-weight: 700;
+    text-shadow: 2px 2px 0 #000;
+    min-height: 22px;
+    margin-bottom: 4px;
+    opacity: 0;
+}
+
+#statusbars {
+    width: 100%;
+    padding: 0 2px 4px;
+}
+
+.barrow {
+    display: flex;
+    justify-content: space-between;
+    align-items: flex-end;
+}
+
+.barright {
+    display: flex;
+    flex-direction: column;
+    align-items: flex-end;
+}
+
+.iconrow {
+    display: flex;
+    gap: 1px;
+}
+
+#foodbar,
+#airbar {
+    flex-direction: row-reverse;
+}
+
+.iconrow span {
+    width: 18px;
+    height: 16px;
+    background-size: 100% 100%;
+    background-repeat: no-repeat;
+}
+
+#hearts.blink span {
+    filter: brightness(1.8);
+}
+
+#foodbar.starving span:nth-child(odd) {
+    animation: shake 0.5s infinite;
+}
+
+@keyframes shake {
+    50% {
+        transform: translateY(-1px);
+    }
+}
+
+#hotbar {
+    display: flex;
+    background: rgba(10, 10, 12, 0.55);
+    border: 2px solid rgba(0, 0, 0, 0.75);
+    pointer-events: auto;
+}
+
+#hotbar .slot {
+    border: 2px solid rgba(255, 255, 255, 0.12);
+    background: rgba(0, 0, 0, 0.18);
+    margin: 0;
+}
+
+#hotbar .slot.sel {
+    border-color: #f2f2f2;
+    box-shadow: 0 0 0 2px #000, inset 0 0 0 1px #000;
+    z-index: 1;
+}
+
+/* ---------------- slots & screens ---------------- */
+
+.slot {
+    position: relative;
+    width: 44px;
+    height: 44px;
+    background: var(--slot);
+    border: 2px solid var(--slot-edge);
+    box-shadow: inset 2px 2px 0 rgba(0, 0, 0, 0.5);
+    flex: 0 0 auto;
+}
+
+.slot .ic,
+.pal .ic,
+.recipe>.ic,
+#cursorStack .ic {
+    position: absolute;
+    left: 2px;
+    top: 2px;
+    width: 36px;
+    height: 36px;
+    background-repeat: no-repeat;
+}
+
+.slot .cnt,
+#cursorStack .cnt {
+    position: absolute;
+    right: 2px;
+    bottom: 0;
+    font: 700 13px var(--font);
+    color: #fff;
+    text-shadow: 1px 1px 0 #000, -1px 0 0 #000, 0 -1px 0 #000;
+    pointer-events: none;
+}
+
+.slot .dura {
+    position: absolute;
+    left: 4px;
+    right: 4px;
+    bottom: 3px;
+    height: 3px;
+    background: #000;
+    display: none;
+}
+
+.slot .dura i {
+    display: block;
+    height: 100%;
+}
+
+#screen {
+    position: fixed;
+    inset: 0;
+    z-index: 20;
+    background: rgba(0, 0, 0, 0.45);
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    padding: 12px;
+}
+
+.screenhint {
+    color: rgba(255, 255, 255, 0.6);
+    font-size: 12px;
+    margin-top: 8px;
+}
+
+#screenPanel {
+    display: flex;
+    gap: 18px;
+    background: var(--panel);
+    border: 2px solid var(--panel-edge);
+    box-shadow: inset 0 0 0 1px var(--panel-hi), 0 14px 50px rgba(0, 0, 0, 0.55);
+    padding: 14px 16px 16px;
+    max-height: calc(100vh - 40px);
+    max-width: calc(100vw - 24px);
+    overflow: auto;
+}
+
+#screenPanel h3 {
+    margin: 4px 0 8px;
+    font-size: 15px;
+    display: flex;
+    justify-content: space-between;
+    align-items: center;
+    gap: 12px;
+}
+
+.slots {
+    display: grid;
+    grid-template-columns: repeat(9, 44px);
+    gap: 2px;
+}
+
+.slots.hotrow {
+    margin-top: 8px;
+}
+
+.slot:hover {
+    border-color: #9aa1ab;
+}
+
+.slot.big {
+    width: 56px;
+    height: 56px;
+}
+
+.slot.big .ic {
+    left: 8px;
+    top: 8px;
+}
+
+.slot.trash {
+    background: #2a1314;
+    border-color: #6b2c2a;
+}
+
+.slot.trash::before {
+    content: "";
+    position: absolute;
+    inset: 9px 11px 7px;
+    border: 2px solid #c27b75;
+    border-top-width: 4px;
+    border-radius: 0 0 3px 3px;
+}
+
+.trashrow {
+    display: flex;
+    justify-content: flex-end;
+    align-items: center;
+    gap: 10px;
+    margin-top: 8px;
+    color: var(--muted);
+    font-size: 12px;
+}
+
+.scr-col.book {
+    width: 270px;
+    display: flex;
+    flex-direction: column;
+}
+
+.craftrow {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    gap: 18px;
+    padding: 4px 0 14px;
+}
+
+.cgrid {
+    display: grid;
+    gap: 2px;
+}
+
+.cgrid.s2 {
+    grid-template-columns: repeat(2, 44px);
+}
+
+.cgrid.s3 {
+    grid-template-columns: repeat(3, 44px);
+}
+
+.slot.result {
+    border-color: #6c7480;
+}
+
+.craftrow .arrow.ready i {
+    width: 100%;
+}
+
+.bookbtn {
+    font: 600 12px var(--font);
+    color: var(--muted);
+    background: #22252b;
+    border: 2px solid #0b0c0e;
+    padding: 4px 10px;
+    cursor: pointer;
+}
+
+.bookbtn.on {
+    color: #fff;
+    background: #3c5f2c;
+}
+
+.pattern {
+    display: grid;
+    gap: 1px;
+    margin-top: 3px;
+}
+
+.pattern b,
+.loose b {
+    width: 18px;
+    height: 18px;
+    background: rgba(0, 0, 0, 0.45);
+    position: relative;
+    display: inline-block;
+}
+
+.pattern .ic,
+.loose .ic {
+    position: absolute;
+    left: 1px;
+    top: 1px;
+    width: 16px;
+    height: 16px;
+}
+
+.loose {
+    display: flex;
+    gap: 2px;
+    align-items: center;
+    margin-top: 3px;
+}
+
+.loose span {
+    color: var(--muted);
+    font-size: 11px;
+    margin-left: 4px;
+}
+
+.onlycan {
+    font-weight: 400;
+    font-size: 12px;
+    color: var(--muted);
+    display: flex;
+    align-items: center;
+    gap: 4px;
+}
+
+.recipes {
+    flex: 1;
+    overflow-y: auto;
+    max-height: 340px;
+    min-height: 200px;
+    background: rgba(0, 0, 0, 0.3);
+    border: 2px solid #0b0c0e;
+    padding: 3px;
+}
+
+.recipe {
+    position: relative;
+    display: flex;
+    align-items: center;
+    gap: 8px;
+    padding: 4px 6px 4px 48px;
+    min-height: 46px;
+    cursor: pointer;
+    opacity: 0.45;
+    border: 1px solid transparent;
+}
+
+.recipe>.ic {
+    left: 6px;
+    top: 5px;
+}
+
+.recipe.can {
+    opacity: 1;
+}
+
+.recipe:hover {
+    background: rgba(255, 255, 255, 0.07);
+    border-color: rgba(255, 255, 255, 0.15);
+}
+
+.recipe.can:hover {
+    background: rgba(124, 195, 90, 0.18);
+}
+
+.rinfo b {
+    font-size: 14px;
+}
+
+.ings {
+    display: flex;
+    gap: 8px;
+    flex-wrap: wrap;
+    margin-top: 2px;
+}
+
+.ing {
+    display: inline-flex;
+    align-items: center;
+    gap: 2px;
+    font-size: 12px;
+    color: #cfe8c2;
+}
+
+.ing.miss {
+    color: #e39b93;
+}
+
+.ing .ic {
+    width: 18px;
+    height: 18px;
+    display: inline-block;
+}
+
+.hint {
+    color: var(--muted);
+    font-size: 12px;
+    margin: 8px 0 0;
+}
+
+.tabs {
+    display: flex;
+    gap: 4px;
+    margin-bottom: 6px;
+}
+
+.tab {
+    font: 600 13px var(--font);
+    color: var(--muted);
+    background: #22252b;
+    border: 2px solid #0b0c0e;
+    padding: 6px 12px;
+    cursor: pointer;
+}
+
+.tab.on {
+    color: #fff;
+    background: #3c5f2c;
+}
+
+.palette {
+    display: grid;
+    grid-template-columns: repeat(9, 44px);
+    gap: 2px;
+    max-height: 190px;
+    overflow-y: auto;
+    padding: 2px;
+    background: rgba(0, 0, 0, 0.3);
+    border: 2px solid #0b0c0e;
+}
+
+.pal {
+    position: relative;
+    width: 44px;
+    height: 44px;
+    background: #1b1e23;
+    border: 2px solid #2e323a;
+    cursor: pointer;
+}
+
+.pal:hover {
+    border-color: #9aa1ab;
+}
+
+.furnace {
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    gap: 22px;
+    padding: 10px 0 16px;
+}
+
+.fcol {
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    gap: 6px;
+}
+
+.flame {
+    width: 18px;
+    height: 20px;
+    background: #2a2c31;
+    position: relative;
+    clip-path: polygon(50% 0, 85% 45%, 100% 80%, 75% 100%, 25% 100%, 0 80%, 15% 45%);
+}
+
+.flame i {
+    position: absolute;
+    left: 0;
+    right: 0;
+    bottom: 0;
+    background: linear-gradient(#ffe36b, #ff7a1a);
+}
+
+.arrow {
+    width: 60px;
+    height: 18px;
+    background: #2a2c31;
+    position: relative;
+    clip-path: polygon(0 30%, 70% 30%, 70% 0, 100% 50%, 70% 100%, 70% 70%, 0 70%);
+}
+
+.arrow i {
+    position: absolute;
+    left: 0;
+    top: 0;
+    bottom: 0;
+    background: #eaeaea;
+}
+
+#cursorStack {
+    position: fixed;
+    left: 0;
+    top: 0;
+    width: 40px;
+    height: 40px;
+    pointer-events: none;
+    z-index: 60;
+}
+
+#tooltip {
+    position: fixed;
+    left: 0;
+    top: 0;
+    z-index: 61;
+    pointer-events: none;
+    background: rgba(16, 6, 24, 0.94);
+    border: 2px solid #3a1b6b;
+    color: #fff;
+    padding: 4px 8px;
+    font-size: 13px;
+    white-space: nowrap;
+}
+
+/* ---------------- touch ---------------- */
+
+#touch {
+    position: fixed;
+    inset: 0;
+    z-index: 11;
+    pointer-events: none;
+}
+
+#stick {
+    position: absolute;
+    left: 24px;
+    bottom: 110px;
+    width: 130px;
+    height: 130px;
+    border-radius: 50%;
+    background: rgba(255, 255, 255, 0.12);
+    border: 2px solid rgba(255, 255, 255, 0.3);
+    pointer-events: auto;
+    touch-action: none;
+}
+
+#stickKnob {
+    position: absolute;
+    left: 40px;
+    top: 40px;
+    width: 46px;
+    height: 46px;
+    border-radius: 50%;
+    background: rgba(255, 255, 255, 0.45);
+}
+
+#lookpad {
+    position: absolute;
+    left: 40%;
+    right: 0;
+    top: 0;
+    bottom: 90px;
+    pointer-events: auto;
+    touch-action: none;
+}
+
+.tbtns {
+    position: absolute;
+    right: 16px;
+    bottom: 110px;
+    display: grid;
+    grid-template-columns: 70px 70px;
+    gap: 8px;
+    pointer-events: auto;
+}
+
+.tbtns button {
+    height: 52px;
+    font: 700 13px var(--font);
+    color: #fff;
+    background: rgba(0, 0, 0, 0.35);
+    border: 2px solid rgba(255, 255, 255, 0.35);
+    border-radius: 8px;
+    touch-action: none;
+}
+
+.tbtns button.on {
+    background: rgba(124, 195, 90, 0.5);
+}
+
+@media (max-height: 680px) {
+    #logo {
+        width: min(400px, 80vw);
+    }
+
+    .tagline {
+        margin: 0 0 12px;
+    }
+
+    #menu {
+        padding-top: 2vh;
+    }
+}
+
+@media (max-width: 760px) {
+    .slot,
+    .pal {
+        width: 34px;
+        height: 34px;
+    }
+
+    .slot .ic,
+    .pal .ic {
+        transform: scale(0.75);
+        transform-origin: 0 0;
+    }
+
+    .slots,
+    .palette {
+        grid-template-columns: repeat(9, 34px);
+    }
+
+    #screenPanel {
+        flex-direction: column;
+    }
+
+    .scr-col.book {
+        width: auto;
+    }
+
+    .settings-grid {
+        grid-template-columns: 1fr;
+    }
+
+    .iconrow span {
+        width: 13px;
+        height: 12px;
+    }
+}

+ 22 - 0
src/web/Blocky/img/module_icon.svg

@@ -0,0 +1,22 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" shape-rendering="crispEdges">
+    <defs>
+        <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
+            <stop offset="0" stop-color="#5d9cf0"/>
+            <stop offset="1" stop-color="#9cc8ff"/>
+        </linearGradient>
+    </defs>
+    <rect x="2" y="2" width="60" height="60" rx="12" fill="url(#sky)"/>
+    <!-- grass block, top face -->
+    <path d="M32 12 L52 22 L32 32 L12 22 Z" fill="#6fb34c"/>
+    <path d="M22 17 h4 v2 h-4z M36 15 h4 v2 h-4z M30 23 h4 v2 h-4z M42 21 h4 v2 h-4z M18 22 h4 v2 h-4z" fill="#86c95f"/>
+    <!-- left face: dirt with grass fringe -->
+    <path d="M12 22 L32 32 L32 54 L12 44 Z" fill="#8a6141"/>
+    <path d="M12 22 L32 32 L32 37 L28 35 L28 38 L24 36 L24 33 L20 31 L20 34 L16 32 L16 29 L12 27 Z" fill="#5f9e3f"/>
+    <path d="M16 38 h3 v3 h-3z M24 43 h3 v3 h-3z M19 46 h2 v2 h-2z" fill="#6e4b31"/>
+    <!-- right face -->
+    <path d="M52 22 L52 44 L32 54 L32 32 Z" fill="#6d4c33"/>
+    <path d="M52 22 L32 32 L32 37 L36 35 L36 38 L40 36 L40 33 L44 31 L44 34 L48 32 L48 29 L52 27 Z" fill="#4c8233"/>
+    <path d="M44 40 h3 v3 h-3z M37 45 h2 v3 h-2z" fill="#563926"/>
+    <path d="M32 12 L52 22 L32 32 L12 22 Z M12 22 L32 32 L32 54 L12 44 Z M52 22 L52 44 L32 54 L32 32 Z"
+          fill="none" stroke="#1f2a16" stroke-width="1.4" stroke-linejoin="round"/>
+</svg>

+ 253 - 0
src/web/Blocky/index.html

@@ -0,0 +1,253 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
+    <meta name="theme-color" content="#1b1d22">
+    <title>Blocky</title>
+    <link rel="icon" href="img/module_icon.svg">
+    <script src="../script/jquery.min.js"></script>
+    <script src="../script/ao_module.js"></script>
+    <link rel="stylesheet" href="css/style.css">
+    <script type="importmap">
+    {
+        "imports": {
+            "three": "./lib/three/three.module.min.js"
+        }
+    }
+    </script>
+</head>
+
+<body>
+    <canvas id="view"></canvas>
+
+    <!-- ================= In-game HUD ================= -->
+    <div id="hud" class="hidden">
+        <div id="underwater"></div>
+        <div id="hurt"></div>
+        <div id="crosshair"></div>
+        <pre id="debug" class="hidden"></pre>
+        <div id="message"></div>
+        <div id="saving" class="hidden">Saving...</div>
+        <div id="bottom">
+            <div id="itemName"></div>
+            <div id="statusbars">
+                <div class="barrow">
+                    <div id="hearts" class="iconrow"></div>
+                    <div class="barright">
+                        <div id="airbar" class="iconrow hidden"></div>
+                        <div id="foodbar" class="iconrow"></div>
+                    </div>
+                </div>
+            </div>
+            <div id="hotbar"></div>
+        </div>
+    </div>
+
+    <!-- ================= Chat / commands ================= -->
+    <div id="chat">
+        <div id="chatLog"></div>
+        <input id="chatInput" class="hidden" type="text" maxlength="200" autocomplete="off" spellcheck="false" placeholder="Type a message or a /command (Tab completes)">
+    </div>
+
+    <!-- ================= Inventory / container screens ================= -->
+    <div id="screen" class="hidden">
+        <div id="screenPanel" class="panel"></div>
+        <div class="screenhint">E or Esc to close</div>
+    </div>
+    <div id="cursorStack" class="hidden"></div>
+    <div id="tooltip" class="hidden"></div>
+
+    <!-- ================= Start screen ================= -->
+    <div id="menu">
+        <canvas id="logo" width="760" height="190"></canvas>
+        <div class="tagline" id="tagline">Build anything. Survive the night.</div>
+
+        <div class="page" id="pageMain">
+            <button class="btn wide" id="btnPlay">Play</button>
+            <button class="btn wide" id="btnSettings">Settings</button>
+            <button class="btn wide" id="btnHelp">How to Play</button>
+            <button class="btn wide" id="btnQuit">Quit</button>
+        </div>
+
+        <div class="page hidden" id="pageWorlds">
+            <div class="box">
+                <h2>Select World</h2>
+                <div id="worldList" class="worldlist"></div>
+                <div class="row">
+                    <button class="btn" id="btnPlayWorld" disabled>Play Selected World</button>
+                    <button class="btn" id="btnNewWorld">Create New World</button>
+                </div>
+                <div class="row">
+                    <button class="btn" id="btnDeleteWorld" disabled>Delete</button>
+                    <button class="btn" id="btnWorldsBack">Back</button>
+                </div>
+            </div>
+        </div>
+
+        <div class="page hidden" id="pageCreate">
+            <div class="box">
+                <h2>Create New World</h2>
+                <label class="field">World name
+                    <input type="text" id="newName" maxlength="40" value="New World">
+                </label>
+                <label class="field">Seed <small>(leave empty for a random one)</small>
+                    <input type="text" id="newSeed" maxlength="40" placeholder="Random">
+                </label>
+                <div class="field">Game mode
+                    <div class="toggle" id="newMode">
+                        <button class="btn on" data-mode="survival">Survival</button>
+                        <button class="btn" data-mode="creative">Creative</button>
+                    </div>
+                    <small id="modeHint">Gather resources, craft tools and keep yourself fed.</small>
+                </div>
+                <div class="field">Difficulty
+                    <div class="toggle" id="newDiff">
+                        <button class="btn" data-diff="0">Peaceful</button>
+                        <button class="btn" data-diff="1">Easy</button>
+                        <button class="btn on" data-diff="2">Normal</button>
+                        <button class="btn" data-diff="3">Hard</button>
+                    </div>
+                    <small id="diffHint"></small>
+                </div>
+                <label class="check"><input type="checkbox" id="newCheats" checked> Allow cheats (commands such as /give and /tp, game mode, time and weather)</label>
+                <div class="row">
+                    <button class="btn" id="btnCreate">Create World</button>
+                    <button class="btn" id="btnCreateCancel">Cancel</button>
+                </div>
+            </div>
+        </div>
+
+        <div class="footer"><span id="storageNote">Checking storage...</span></div>
+    </div>
+
+    <!-- ================= Overlays ================= -->
+    <div id="loading" class="overlay hidden">
+        <div class="box center">
+            <h2 id="loadTitle">Generating terrain</h2>
+            <div class="progress"><i id="loadBar"></i></div>
+            <p id="loadText">Preparing the world...</p>
+        </div>
+    </div>
+
+    <div id="resume" class="overlay hidden">
+        <div class="box center clickable">
+            <h2>Click to play</h2>
+            <p>Move with W A S D, look with the mouse. Press Esc to pause.</p>
+        </div>
+    </div>
+
+    <div id="pause" class="overlay dim hidden">
+        <div class="menugrid">
+            <h2 class="span2">Game Paused</h2>
+            <button class="btn span2" id="btnResume">Back to Game</button>
+            <button class="btn" id="btnDiff" title="How fast hunger drains">Difficulty: Normal</button>
+            <button class="btn" id="btnCheats" title="Lets you use commands and the buttons below">Cheats: On</button>
+            <button class="btn cheat" id="btnMode">Game Mode: Survival</button>
+            <button class="btn cheat" id="btnTime">Time: Day</button>
+            <button class="btn cheat" id="btnWeather">Weather: Clear</button>
+            <button class="btn" id="btnCommands">Commands...</button>
+            <button class="btn" id="btnPauseSettings">Settings...</button>
+            <button class="btn" id="btnPauseHelp">How to Play...</button>
+            <div class="gap span2"></div>
+            <button class="btn span2" id="btnSaveQuit">Save and Quit to Title</button>
+        </div>
+    </div>
+
+    <div id="cmdhelp" class="overlay hidden">
+        <div class="box">
+            <h2>Commands</h2>
+            <p>Press <b>T</b> to open the chat line, or <b>/</b> to start a command right away. <b>Tab</b> completes
+                command and item names, <b>Up</b> recalls earlier commands. Use <b>~</b> for your own position,
+                e.g. <code>/tp ~ ~20 ~</code>. Commands other than /help and /seed need cheats turned on.</p>
+            <div id="cmdlist" class="cmdlist"></div>
+            <div class="row"><button class="btn" id="btnCmdDone">Done</button></div>
+        </div>
+    </div>
+
+    <div id="death" class="overlay death hidden">
+        <div class="box center">
+            <h1>You Died</h1>
+            <p id="deathText"></p>
+            <button class="btn wide" id="btnRespawn">Respawn</button>
+            <button class="btn wide" id="btnDeathTitle">Save and Quit to Title</button>
+        </div>
+    </div>
+
+    <div id="settings" class="overlay hidden">
+        <div class="box">
+            <h2>Settings</h2>
+            <div class="settings-grid">
+                <label>Render distance <b id="valRender"></b><input type="range" id="setRender" min="2" max="12" step="1"></label>
+                <label>Field of view <b id="valFov"></b><input type="range" id="setFov" min="50" max="110" step="1"></label>
+                <label>Mouse sensitivity <b id="valSens"></b><input type="range" id="setSens" min="0.2" max="3" step="0.05"></label>
+                <label>Brightness <b id="valBright"></b><input type="range" id="setBright" min="0" max="1" step="0.05"></label>
+                <label>Volume <b id="valVolume"></b><input type="range" id="setVolume" min="0" max="1" step="0.05"></label>
+                <label>Render scale <b id="valScale"></b><input type="range" id="setScale" min="0.5" max="1" step="0.25"></label>
+                <label class="check"><input type="checkbox" id="setLeaves"> Fancy leaves</label>
+                <label class="check"><input type="checkbox" id="setClouds"> Clouds</label>
+                <label class="check"><input type="checkbox" id="setBob"> View bobbing</label>
+                <label class="check"><input type="checkbox" id="setInvert"> Invert mouse</label>
+                <label class="check"><input type="checkbox" id="setFps"> Show FPS</label>
+            </div>
+            <div class="row"><button class="btn" id="btnSettingsDone">Done</button></div>
+        </div>
+    </div>
+
+    <div id="help" class="overlay hidden">
+        <div class="box">
+            <h2>How to Play</h2>
+            <div class="helpgrid">
+                <div><b>W A S D</b> move, <b>Space</b> jump, <b>Shift</b> sneak, <b>Ctrl</b> or double tap <b>W</b> to sprint</div>
+                <div><b>Left mouse</b> mine a block, <b>Right mouse</b> place a block, use a workbench / furnace / chest, or eat</div>
+                <div><b>1 - 9</b> or the <b>mouse wheel</b> pick a hotbar slot</div>
+                <div><b>E</b> inventory and 2 x 2 crafting, <b>Q</b> drop an item (Ctrl+Q the whole stack)</div>
+                <div><b>T</b> chat, <b>/</b> type a command such as <b>/give</b> or <b>/tp</b></div>
+                <div><b>Creative:</b> double tap <b>Space</b> to fly, Space / Shift to rise and sink</div>
+                <div><b>F3</b> debug info, <b>F1</b> hide the interface, <b>Esc</b> pause</div>
+            </div>
+            <p>Start by punching a tree for logs, turn them into planks on the 2 x 2 grid in your inventory (E), and
+                build a workbench from four planks: it gives you a 3 x 3 grid. The recipe book next to the grid shows
+                every pattern and lays it out for you. A wooden pickaxe
+                mines stone; stone tools mine iron, iron tools mine gold and crystal. Smelt ores in a furnace.
+                Keep your food bar up: apples drop from leaves, seeds from tall grass grow into wheat for bread,
+                and two mushrooms with a bowl make stew. Harder difficulties make you hungry faster.</p>
+            <div class="row"><button class="btn" id="btnHelpDone">Got it</button></div>
+        </div>
+    </div>
+
+    <div id="confirm" class="overlay hidden">
+        <div class="box center">
+            <h2 id="confirmTitle">Are you sure?</h2>
+            <p id="confirmText"></p>
+            <div class="row">
+                <button class="btn danger" id="btnConfirmYes">Delete</button>
+                <button class="btn" id="btnConfirmNo">Cancel</button>
+            </div>
+        </div>
+    </div>
+
+    <!-- ================= Touch controls ================= -->
+    <div id="touch" class="hidden">
+        <div id="stick"><div id="stickKnob"></div></div>
+        <div id="lookpad"></div>
+        <div class="tbtns">
+            <button id="tJump">Jump</button>
+            <button id="tSneak">Sneak</button>
+            <button id="tInv">Items</button>
+            <button id="tPause">Pause</button>
+        </div>
+    </div>
+
+    <div id="error" class="overlay hidden">
+        <div class="box center">
+            <h2>Blocky could not start</h2>
+            <p id="errorText"></p>
+        </div>
+    </div>
+
+    <script type="module" src="js/main.js"></script>
+</body>
+
+</html>

+ 25 - 0
src/web/Blocky/init.agi

@@ -0,0 +1,25 @@
+/*
+    Blocky
+
+    A voxel sandbox game: explore generated grassland, desert, ocean and
+    forest biomes, mine and place blocks, craft at a workbench, smelt in a
+    furnace and keep yourself fed in survival, or build freely in creative.
+    Everything (textures, sounds, three.js) ships inside this folder and
+    worlds are saved to the user's appdata folder by backend/worlds.agi.
+*/
+
+var moduleLaunchInfo = {
+    Name: "Blocky",
+    Desc: "A voxel sandbox game with survival and creative modes",
+    Group: "Games",
+    IconPath: "Blocky/img/module_icon.svg",
+    Version: "1.0",
+    StartDir: "Blocky/index.html",
+    SupportFW: true,
+    LaunchFWDir: "Blocky/index.html",
+    SupportEmb: false,
+    InitFWSize: [1200, 760],
+    SupportedExt: []
+};
+
+registerModule(JSON.stringify(moduleLaunchInfo));

+ 215 - 0
src/web/Blocky/js/audio.js

@@ -0,0 +1,215 @@
+/*
+    Blocky - audio.js
+
+    All sounds are synthesised with the Web Audio API from filtered noise
+    and simple oscillators, so the game ships no audio files.
+*/
+
+const MATERIAL = {
+    stone: { type: "bandpass", freq: 2200, q: 1.1, dur: 0.11, gain: 0.55 },
+    wood: { type: "bandpass", freq: 850, q: 2.5, dur: 0.12, gain: 0.7, thump: 170 },
+    gravel: { type: "lowpass", freq: 1300, q: 0.7, dur: 0.15, gain: 0.7, crunch: true },
+    grass: { type: "highpass", freq: 1800, q: 0.6, dur: 0.12, gain: 0.35 },
+    sand: { type: "highpass", freq: 2800, q: 0.5, dur: 0.16, gain: 0.32 },
+    glass: { type: "bandpass", freq: 3200, q: 4, dur: 0.1, gain: 0.45, ping: true },
+    metal: { type: "bandpass", freq: 2600, q: 7, dur: 0.14, gain: 0.45, ping: true },
+    cloth: { type: "lowpass", freq: 900, q: 0.7, dur: 0.12, gain: 0.4 },
+    water: { type: "lowpass", freq: 900, q: 0.7, dur: 0.25, gain: 0.4 }
+};
+
+export class Sound {
+    constructor() {
+        this.ctx = null;
+        this.volume = 0.8;
+        this.rainGain = null;
+    }
+
+    //Must be called from a user gesture before anything plays
+    ensure() {
+        if (this.ctx) {
+            if (this.ctx.state === "suspended") {
+                this.ctx.resume();
+            }
+            return;
+        }
+        const AC = window.AudioContext || window.webkitAudioContext;
+        if (!AC) {
+            return;
+        }
+        this.ctx = new AC();
+        this.master = this.ctx.createGain();
+        this.master.gain.value = this.volume;
+        this.master.connect(this.ctx.destination);
+        const len = this.ctx.sampleRate * 2;
+        this.noise = this.ctx.createBuffer(1, len, this.ctx.sampleRate);
+        const d = this.noise.getChannelData(0);
+        for (let i = 0; i < len; i++) {
+            d[i] = Math.random() * 2 - 1;
+        }
+        //Brown noise for thunder
+        this.brown = this.ctx.createBuffer(1, len, this.ctx.sampleRate);
+        const b = this.brown.getChannelData(0);
+        let last = 0;
+        for (let i = 0; i < len; i++) {
+            last = (last + 0.02 * (Math.random() * 2 - 1)) / 1.02;
+            b[i] = last * 3.5;
+        }
+        this.startRain();
+    }
+
+    setVolume(v) {
+        this.volume = v;
+        if (this.master) {
+            this.master.gain.value = v;
+        }
+    }
+
+    noiseBurst(filterType, freq, q, dur, gain, when = 0, buffer = null) {
+        const ctx = this.ctx;
+        const t = ctx.currentTime + when;
+        const src = ctx.createBufferSource();
+        src.buffer = buffer || this.noise;
+        src.loop = true;
+        const f = ctx.createBiquadFilter();
+        f.type = filterType;
+        f.frequency.value = freq;
+        f.Q.value = q;
+        const g = ctx.createGain();
+        g.gain.setValueAtTime(0.0001, t);
+        g.gain.exponentialRampToValueAtTime(gain, t + 0.008);
+        g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
+        src.connect(f).connect(g).connect(this.master);
+        src.start(t, Math.random() * 1.5);
+        src.stop(t + dur + 0.05);
+        return f;
+    }
+
+    tone(freq, dur, gain, type = "sine", when = 0, endFreq = null) {
+        const ctx = this.ctx;
+        const t = ctx.currentTime + when;
+        const o = ctx.createOscillator();
+        o.type = type;
+        o.frequency.setValueAtTime(freq, t);
+        if (endFreq) {
+            o.frequency.exponentialRampToValueAtTime(endFreq, t + dur);
+        }
+        const g = ctx.createGain();
+        g.gain.setValueAtTime(0.0001, t);
+        g.gain.exponentialRampToValueAtTime(gain, t + 0.01);
+        g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
+        o.connect(g).connect(this.master);
+        o.start(t);
+        o.stop(t + dur + 0.05);
+    }
+
+    //kind: dig, break, place, step
+    block(kind, material) {
+        if (!this.ctx) {
+            return;
+        }
+        const m = MATERIAL[material] || MATERIAL.stone;
+        const pitch = 0.85 + Math.random() * 0.3;
+        let gain = m.gain, dur = m.dur;
+        if (kind === "step") {
+            gain *= 0.32;
+            dur *= 0.8;
+        } else if (kind === "dig") {
+            gain *= 0.45;
+            dur *= 0.7;
+        } else if (kind === "break") {
+            gain *= 1.1;
+            dur *= 1.6;
+        }
+        this.noiseBurst(m.type, m.freq * pitch, m.q, dur, gain);
+        if (m.crunch && kind !== "step") {
+            this.noiseBurst("bandpass", 600 * pitch, 2, dur * 0.6, gain * 0.6, 0.04);
+        }
+        if (m.thump) {
+            this.tone(m.thump * pitch, dur, gain * 0.5, "sine");
+        }
+        if (m.ping && kind === "break") {
+            for (let i = 0; i < 4; i++) {
+                this.tone(2000 + Math.random() * 2500, 0.18, 0.08, "sine", i * 0.03);
+            }
+        }
+    }
+
+    play(name, opts = {}) {
+        if (!this.ctx) {
+            return;
+        }
+        switch (name) {
+            case "pop":
+                this.tone(700 + Math.random() * 400, 0.07, 0.12, "sine", 0, 1300 + Math.random() * 300);
+                break;
+            case "click":
+                this.tone(1100, 0.03, 0.1, "square");
+                break;
+            case "hurt":
+                this.tone(240, 0.18, 0.35, "triangle", 0, 110);
+                this.noiseBurst("lowpass", 500, 0.7, 0.12, 0.4);
+                break;
+            case "eat":
+                this.noiseBurst("bandpass", 1300 + Math.random() * 600, 1.5, 0.08, 0.45);
+                this.noiseBurst("bandpass", 900, 1.2, 0.06, 0.3, 0.05);
+                break;
+            case "burp":
+                this.tone(160, 0.22, 0.3, "sawtooth", 0, 90);
+                break;
+            case "splash": {
+                const f = this.noiseBurst("lowpass", 2400, 0.6, 0.45, 0.5);
+                f.frequency.exponentialRampToValueAtTime(300, this.ctx.currentTime + 0.4);
+                break;
+            }
+            case "toolBreak":
+                this.tone(900, 0.2, 0.2, "square", 0, 300);
+                this.noiseBurst("highpass", 3000, 0.5, 0.2, 0.3);
+                break;
+            case "thunder": {
+                const dist = opts.distance || 0;
+                const near = Math.max(0.15, 1 - dist / 80);
+                const delay = Math.min(3, dist / 40);
+                if (dist < 24) {
+                    this.noiseBurst("highpass", 1500, 0.4, 0.25, 0.6 * near, delay);
+                }
+                const len = 3 + Math.random() * 2;
+                const f = this.noiseBurst("lowpass", 260 + near * 300, 0.5, len, 1.2 * near, delay, this.brown);
+                f.frequency.exponentialRampToValueAtTime(90, this.ctx.currentTime + delay + len);
+                this.noiseBurst("lowpass", 160, 0.5, len * 0.8, 0.9 * near, delay + 0.4 + Math.random() * 0.5, this.brown);
+                break;
+            }
+            case "fizz":
+                this.noiseBurst("highpass", 4000, 0.5, 0.3, 0.2);
+                break;
+            default:
+                break;
+        }
+    }
+
+    startRain() {
+        const ctx = this.ctx;
+        const src = ctx.createBufferSource();
+        src.buffer = this.noise;
+        src.loop = true;
+        const hp = ctx.createBiquadFilter();
+        hp.type = "highpass";
+        hp.frequency.value = 500;
+        this.rainLp = ctx.createBiquadFilter();
+        this.rainLp.type = "lowpass";
+        this.rainLp.frequency.value = 6000;
+        this.rainGain = ctx.createGain();
+        this.rainGain.gain.value = 0;
+        src.connect(hp).connect(this.rainLp).connect(this.rainGain).connect(this.master);
+        src.start();
+    }
+
+    //level 0-1, muffled when the player is under a roof
+    setRain(level, muffled) {
+        if (!this.rainGain) {
+            return;
+        }
+        const t = this.ctx.currentTime;
+        this.rainGain.gain.setTargetAtTime(level * 0.22, t, 0.4);
+        this.rainLp.frequency.setTargetAtTime(muffled ? 900 : 6000, t, 0.4);
+    }
+}

+ 536 - 0
src/web/Blocky/js/blocks.js

@@ -0,0 +1,536 @@
+/*
+    Blocky - blocks.js
+
+    Block, item, recipe and smelting registry.
+
+    Ids 0-255 are blocks (a block's inventory item shares its id), ids 256
+    and up are plain items. Faces are indexed 0:+x 1:-x 2:+y 3:-y 4:+z 5:-z
+    everywhere in the engine.
+*/
+
+import { TOOL_MATERIALS, TOOL_KINDS } from "./textures.js";
+
+export const B = {
+    AIR: 0, STONE: 1, GRASS: 2, DIRT: 3, COBBLE: 4, PLANKS: 5, SAPLING: 6, BEDROCK: 7,
+    WATER: 8, SAND: 9, GRAVEL: 10, LOG: 11, LEAVES: 12, GLASS: 13, SANDSTONE: 14,
+    COAL_ORE: 15, IRON_ORE: 16, GOLD_ORE: 17, CRYSTAL_ORE: 18, CLAY: 19, BRICKS: 20,
+    STONE_BRICKS: 21, TORCH: 22, WORKBENCH: 23, FURNACE: 24, FURNACE_LIT: 25, CHEST: 26,
+    TALL_GRASS: 27, FLOWER_YELLOW: 28, FLOWER_RED: 29, MUSHROOM_BROWN: 30, MUSHROOM_RED: 31,
+    CACTUS: 32, REEDS: 33, FARMLAND: 34, WHEAT: 35, DEAD_BUSH: 36, LADDER: 37,
+    STONE_SLAB: 38, PLANK_SLAB: 39, COBBLE_SLAB: 40, SANDSTONE_SLAB: 41,
+    IRON_BLOCK: 42, GOLD_BLOCK: 43, CRYSTAL_BLOCK: 44, LAMP: 45, MOSSY_COBBLE: 46
+};
+
+export const I = {
+    STICK: 256, COAL: 257, IRON_INGOT: 258, GOLD_INGOT: 259, CRYSTAL: 260, FLINT: 261,
+    CLAY_BALL: 262, BRICK: 263, SEEDS: 264, WHEAT: 265, BREAD: 266, APPLE: 267,
+    BOWL: 268, STEW: 269, BUCKET: 270, WATER_BUCKET: 271
+};
+
+//Tool ids: 280 + material * 4 + kind (kinds: pickaxe, axe, shovel, hoe)
+export const TOOL_BASE = 280;
+export function toolId(matIndex, kindIndex) {
+    return TOOL_BASE + matIndex * 4 + kindIndex;
+}
+
+export const BLOCKS = [];
+export const ITEMS = [];
+
+const DEFAULTS = {
+    shape: "cube",      //cube, cross, crop, torch, slab, cactus, liquid, farmland, ladder, none
+    solid: true,        //has collision
+    opaque: true,       //full cube that hides neighbour faces
+    lightOpacity: 15,
+    light: 0,
+    hardness: 1,
+    tool: null,         //pickaxe, axe, shovel
+    tier: 0,            //minimum tool tier for drops (0: hand works)
+    sound: "stone",
+    replaceable: false,
+    tint: null,         //grass or foliage (vertex tinted faces)
+    gravity: false,
+    support: null,      //what the block needs below / behind it to stay
+    noItem: false,
+    targetable: true,
+    orient: false,      //front face follows meta
+    tex: null
+};
+
+function def(id, name, props) {
+    const b = Object.assign({}, DEFAULTS, props, { id, name });
+    if (typeof b.tex === "string") {
+        b.tex = { all: b.tex };
+    }
+    BLOCKS[id] = b;
+    return b;
+}
+
+const NONSOLID_PLANT = {
+    shape: "cross", solid: false, opaque: false, lightOpacity: 0, hardness: 0,
+    sound: "grass", support: "soil"
+};
+
+def(B.AIR, "Air", { shape: "none", solid: false, opaque: false, lightOpacity: 0, hardness: 0, replaceable: true, noItem: true, targetable: false });
+def(B.STONE, "Stone", { tex: "stone", hardness: 1.5, tool: "pickaxe", tier: 1, drops: () => [[B.COBBLE, 1]] });
+def(B.GRASS, "Grass Block", { tex: { top: "grass_top", bottom: "dirt", side: "grass_side" }, hardness: 0.6, tool: "shovel", sound: "grass", tint: "grass", drops: () => [[B.DIRT, 1]] });
+def(B.DIRT, "Dirt", { tex: "dirt", hardness: 0.5, tool: "shovel", sound: "gravel" });
+def(B.COBBLE, "Cobblestone", { tex: "cobblestone", hardness: 2, tool: "pickaxe", tier: 1 });
+def(B.MOSSY_COBBLE, "Mossy Cobblestone", { tex: "mossy", hardness: 2, tool: "pickaxe", tier: 1 });
+def(B.PLANKS, "Planks", { tex: "planks", hardness: 2, tool: "axe", sound: "wood" });
+def(B.SAPLING, "Sapling", Object.assign({}, NONSOLID_PLANT, { tex: "sapling" }));
+def(B.BEDROCK, "Bedrock", { tex: "bedrock", hardness: -1, noItem: true });
+def(B.WATER, "Water", { tex: "water", shape: "liquid", solid: false, opaque: false, lightOpacity: 1, hardness: -1, replaceable: true, noItem: true, targetable: false, sound: "water" });
+def(B.SAND, "Sand", { tex: "sand", hardness: 0.5, tool: "shovel", sound: "sand", gravity: true });
+def(B.GRAVEL, "Gravel", { tex: "gravel", hardness: 0.6, tool: "shovel", sound: "gravel", gravity: true, drops: (m, rng) => [[rng() < 0.12 ? I.FLINT : B.GRAVEL, 1]] });
+def(B.LOG, "Log", { tex: { top: "log_top", bottom: "log_top", side: "log_side" }, hardness: 2, tool: "axe", sound: "wood" });
+def(B.LEAVES, "Leaves", {
+    tex: "leaves", opaque: false, lightOpacity: 1, hardness: 0.2, sound: "grass", tint: "foliage", cutout: true,
+    drops: (m, rng) => {
+        const out = [];
+        if (rng() < 0.06) {
+            out.push([B.SAPLING, 1]);
+        }
+        if (rng() < 0.025) {
+            out.push([I.APPLE, 1]);
+        }
+        return out;
+    }
+});
+def(B.GLASS, "Glass", { tex: "glass", opaque: false, lightOpacity: 0, hardness: 0.3, sound: "glass", cutout: true, drops: () => [] });
+def(B.SANDSTONE, "Sandstone", { tex: { top: "sandstone_top", bottom: "sandstone_bottom", side: "sandstone_side" }, hardness: 0.8, tool: "pickaxe", tier: 1 });
+def(B.COAL_ORE, "Coal Ore", { tex: "coal_ore", hardness: 3, tool: "pickaxe", tier: 1, drops: () => [[I.COAL, 1]] });
+def(B.IRON_ORE, "Iron Ore", { tex: "iron_ore", hardness: 3, tool: "pickaxe", tier: 2 });
+def(B.GOLD_ORE, "Gold Ore", { tex: "gold_ore", hardness: 3, tool: "pickaxe", tier: 3 });
+def(B.CRYSTAL_ORE, "Crystal Ore", { tex: "crystal_ore", hardness: 3, tool: "pickaxe", tier: 3, drops: () => [[I.CRYSTAL, 1]] });
+def(B.CLAY, "Clay", { tex: "clay", hardness: 0.6, tool: "shovel", sound: "gravel", drops: () => [[I.CLAY_BALL, 4]] });
+def(B.BRICKS, "Bricks", { tex: "bricks", hardness: 2, tool: "pickaxe", tier: 1 });
+def(B.STONE_BRICKS, "Stone Bricks", { tex: "stone_bricks", hardness: 1.5, tool: "pickaxe", tier: 1 });
+def(B.TORCH, "Torch", { tex: "torch", shape: "torch", solid: false, opaque: false, lightOpacity: 0, light: 14, hardness: 0, sound: "wood", support: "torch" });
+def(B.WORKBENCH, "Workbench", { tex: { top: "workbench_top", bottom: "planks", side: "workbench_side", front: "workbench_front" }, hardness: 2.5, tool: "axe", sound: "wood", interact: "workbench" });
+def(B.FURNACE, "Furnace", { tex: { top: "furnace_top", bottom: "furnace_top", side: "furnace_side", front: "furnace_front" }, hardness: 3.5, tool: "pickaxe", tier: 1, orient: true, interact: "furnace" });
+def(B.FURNACE_LIT, "Lit Furnace", { tex: { top: "furnace_top", bottom: "furnace_top", side: "furnace_side", front: "furnace_front_lit" }, hardness: 3.5, tool: "pickaxe", tier: 1, orient: true, light: 13, noItem: true, interact: "furnace", drops: () => [[B.FURNACE, 1]] });
+def(B.CHEST, "Chest", { tex: { top: "chest_top", bottom: "chest_top", side: "chest_side", front: "chest_front" }, hardness: 2.5, tool: "axe", sound: "wood", orient: true, interact: "chest" });
+def(B.TALL_GRASS, "Tall Grass", Object.assign({}, NONSOLID_PLANT, { tex: "tall_grass", tint: "grass", replaceable: true, drops: (m, rng) => (rng() < 0.125 ? [[I.SEEDS, 1]] : []) }));
+def(B.FLOWER_YELLOW, "Yellow Flower", Object.assign({}, NONSOLID_PLANT, { tex: "flower_yellow" }));
+def(B.FLOWER_RED, "Red Flower", Object.assign({}, NONSOLID_PLANT, { tex: "flower_red" }));
+def(B.MUSHROOM_BROWN, "Brown Mushroom", Object.assign({}, NONSOLID_PLANT, { tex: "mushroom_brown", support: "solid", light: 1 }));
+def(B.MUSHROOM_RED, "Red Mushroom", Object.assign({}, NONSOLID_PLANT, { tex: "mushroom_red", support: "solid" }));
+def(B.CACTUS, "Cactus", { tex: { top: "cactus_top", bottom: "cactus_bottom", side: "cactus_side" }, shape: "cactus", opaque: false, lightOpacity: 0, hardness: 0.4, sound: "cloth", support: "cactus" });
+def(B.REEDS, "Reeds", Object.assign({}, NONSOLID_PLANT, { tex: "reeds", support: "reeds" }));
+def(B.FARMLAND, "Farmland", { tex: { top: "farmland_dry", bottom: "dirt", side: "dirt" }, shape: "farmland", opaque: false, lightOpacity: 0, hardness: 0.6, tool: "shovel", sound: "gravel", noItem: true, drops: () => [[B.DIRT, 1]] });
+def(B.WHEAT, "Wheat", Object.assign({}, NONSOLID_PLANT, {
+    tex: "wheat_0", shape: "crop", support: "farmland", noItem: true,
+    drops: (m, rng) => (m >= 7 ? [[I.WHEAT, 1], [I.SEEDS, 1 + Math.floor(rng() * 3)]] : [[I.SEEDS, 1]])
+}));
+def(B.DEAD_BUSH, "Dead Bush", Object.assign({}, NONSOLID_PLANT, { tex: "dead_bush", support: "sand", replaceable: true, drops: (m, rng) => (rng() < 0.5 ? [[I.STICK, 1 + Math.floor(rng() * 2)]] : []) }));
+def(B.LADDER, "Ladder", { tex: "ladder", shape: "ladder", solid: false, opaque: false, lightOpacity: 0, hardness: 0.4, tool: "axe", sound: "wood", support: "wall", cutout: true });
+def(B.STONE_SLAB, "Stone Slab", { tex: { top: "slab_top", bottom: "slab_top", side: "slab_side" }, shape: "slab", opaque: false, lightOpacity: 0, hardness: 2, tool: "pickaxe", tier: 1 });
+def(B.PLANK_SLAB, "Plank Slab", { tex: "planks", shape: "slab", opaque: false, lightOpacity: 0, hardness: 2, tool: "axe", sound: "wood" });
+def(B.COBBLE_SLAB, "Cobblestone Slab", { tex: "cobblestone", shape: "slab", opaque: false, lightOpacity: 0, hardness: 2, tool: "pickaxe", tier: 1 });
+def(B.SANDSTONE_SLAB, "Sandstone Slab", { tex: { top: "sandstone_top", bottom: "sandstone_bottom", side: "sandstone_side" }, shape: "slab", opaque: false, lightOpacity: 0, hardness: 0.8, tool: "pickaxe", tier: 1 });
+def(B.IRON_BLOCK, "Block of Iron", { tex: "iron_block", hardness: 5, tool: "pickaxe", tier: 2, sound: "metal" });
+def(B.GOLD_BLOCK, "Block of Gold", { tex: "gold_block", hardness: 3, tool: "pickaxe", tier: 3, sound: "metal" });
+def(B.CRYSTAL_BLOCK, "Block of Crystal", { tex: "crystal_block", hardness: 5, tool: "pickaxe", tier: 3, sound: "metal" });
+def(B.LAMP, "Lamp", { tex: "lamp", hardness: 0.3, light: 15, sound: "glass" });
+
+//Fill the gaps so every id lookup returns something sane
+for (let i = 0; i < 256; i++) {
+    if (!BLOCKS[i]) {
+        BLOCKS[i] = Object.assign({}, DEFAULTS, { id: i, name: "Unknown", tex: { all: "stone" }, noItem: true });
+    }
+}
+
+/* ---------- Fast lookup tables used by the mesher and lighting ---------- */
+
+export const OPAQUE = new Uint8Array(256);      //full occluding cube
+export const SOLID = new Uint8Array(256);       //collides with entities
+export const LIGHT_OPACITY = new Uint8Array(256);
+export const LIGHT_EMIT = new Uint8Array(256);
+export const SHAPE = new Array(256);
+export const RAIN_BLOCKING = new Uint8Array(256);
+
+for (let i = 0; i < 256; i++) {
+    const b = BLOCKS[i];
+    OPAQUE[i] = b.opaque ? 1 : 0;
+    SOLID[i] = b.solid ? 1 : 0;
+    LIGHT_OPACITY[i] = b.lightOpacity;
+    LIGHT_EMIT[i] = b.light;
+    SHAPE[i] = b.shape;
+    RAIN_BLOCKING[i] = (b.solid || i === B.WATER || i === B.LEAVES) ? 1 : 0;
+}
+
+//A slab with meta 2 is a double slab: a full opaque cube
+export function isOpaqueAt(id, meta) {
+    return OPAQUE[id] === 1 || (SHAPE[id] === "slab" && meta === 2);
+}
+
+/* ---------- Texture layer resolution ---------- */
+
+//faceLayers[id] = Int16Array(6) resolved after the atlas is built
+export const faceLayers = [];
+let tileLayer = null;
+
+export function resolveBlockTextures(layerOf) {
+    tileLayer = layerOf;
+    for (let i = 0; i < 256; i++) {
+        const t = BLOCKS[i].tex || { all: "stone" };
+        const get = (name) => (layerOf.has(name) ? layerOf.get(name) : 0);
+        const side = get(t.side || t.all);
+        const top = get(t.top || t.all);
+        const bottom = get(t.bottom || t.all);
+        const arr = new Int16Array(7);
+        arr[0] = side; arr[1] = side; arr[2] = top; arr[3] = bottom; arr[4] = side; arr[5] = side;
+        arr[6] = t.front ? get(t.front) : side;
+        faceLayers[i] = arr;
+    }
+}
+
+export function layerOfTile(name) {
+    return tileLayer.get(name);
+}
+
+//Texture layer of a block face, taking meta into account
+export function blockFaceLayer(id, face, meta) {
+    const fl = faceLayers[id];
+    if (id === B.WHEAT) {
+        return tileLayer.get("wheat_" + Math.min(7, meta));
+    }
+    if (id === B.FARMLAND && face === 2) {
+        return tileLayer.get(meta > 0 ? "farmland_wet" : "farmland_dry");
+    }
+    if (id === B.WORKBENCH) {
+        return (face === 4 || face === 5) ? fl[6] : fl[face];
+    }
+    if (BLOCKS[id].orient) {
+        return face === meta ? fl[6] : fl[face];
+    }
+    return fl[face];
+}
+
+/* ---------- Items ---------- */
+
+const ITEM_DEFAULTS = { stack: 64, block: 0, tool: null, food: null, fuel: 0, icon: null };
+
+function item(id, name, props) {
+    ITEMS[id] = Object.assign({}, ITEM_DEFAULTS, props, { id, name });
+    return ITEMS[id];
+}
+
+const FLAT_BLOCK_ICONS = {
+    [B.SAPLING]: "sapling", [B.TORCH]: "torch", [B.TALL_GRASS]: "tall_grass",
+    [B.FLOWER_YELLOW]: "flower_yellow", [B.FLOWER_RED]: "flower_red",
+    [B.MUSHROOM_BROWN]: "mushroom_brown", [B.MUSHROOM_RED]: "mushroom_red",
+    [B.REEDS]: "reeds", [B.DEAD_BUSH]: "dead_bush", [B.LADDER]: "ladder"
+};
+
+for (let i = 1; i < 256; i++) {
+    const b = BLOCKS[i];
+    if (b.noItem || b.name === "Unknown") {
+        continue;
+    }
+    item(i, b.name, {
+        block: i,
+        icon: FLAT_BLOCK_ICONS[i] ? { flat: FLAT_BLOCK_ICONS[i], tint: b.tint } : { block: i }
+    });
+}
+
+const FUEL = 1;
+item(I.STICK, "Stick", { icon: { flat: "stick" }, fuel: 100 * FUEL });
+item(I.COAL, "Coal", { icon: { flat: "coal" }, fuel: 1600 });
+item(I.IRON_INGOT, "Iron Ingot", { icon: { flat: "iron_ingot" } });
+item(I.GOLD_INGOT, "Gold Ingot", { icon: { flat: "gold_ingot" } });
+item(I.CRYSTAL, "Crystal", { icon: { flat: "crystal" } });
+item(I.FLINT, "Flint", { icon: { flat: "flint" } });
+item(I.CLAY_BALL, "Clay Ball", { icon: { flat: "clay_ball" } });
+item(I.BRICK, "Brick", { icon: { flat: "brick" } });
+item(I.SEEDS, "Seeds", { icon: { flat: "seeds" }, plant: B.WHEAT });
+item(I.WHEAT, "Wheat", { icon: { flat: "wheat_item" } });
+item(I.BREAD, "Bread", { icon: { flat: "bread" }, food: { hunger: 5, sat: 6 } });
+item(I.APPLE, "Apple", { icon: { flat: "apple" }, food: { hunger: 4, sat: 2.4 } });
+item(I.BOWL, "Bowl", { icon: { flat: "bowl" }, fuel: 100 });
+item(I.STEW, "Mushroom Stew", { icon: { flat: "stew" }, stack: 1, food: { hunger: 6, sat: 7.2, leaves: I.BOWL } });
+item(I.BUCKET, "Bucket", { icon: { flat: "bucket" }, stack: 16 });
+item(I.WATER_BUCKET, "Water Bucket", { icon: { flat: "water_bucket" }, stack: 1 });
+
+//Fuel for blocks (ticks at 20 ticks per second; one smelt takes 200 ticks)
+ITEMS[B.LOG].fuel = 300;
+ITEMS[B.PLANKS].fuel = 300;
+ITEMS[B.PLANK_SLAB].fuel = 150;
+ITEMS[B.SAPLING].fuel = 100;
+ITEMS[B.WORKBENCH].fuel = 300;
+ITEMS[B.CHEST].fuel = 300;
+ITEMS[B.LADDER].fuel = 300;
+ITEMS[B.REEDS].block = B.REEDS;
+
+export const TOOL_STATS = [
+    { name: "Wooden", tier: 1, speed: 2, durability: 64, material: B.PLANKS },
+    { name: "Stone", tier: 2, speed: 4, durability: 140, material: B.COBBLE },
+    { name: "Iron", tier: 3, speed: 6, durability: 260, material: I.IRON_INGOT },
+    { name: "Golden", tier: 1, speed: 11, durability: 40, material: I.GOLD_INGOT },
+    { name: "Crystal", tier: 4, speed: 8, durability: 1200, material: I.CRYSTAL }
+];
+const KIND_NAMES = ["Pickaxe", "Axe", "Shovel", "Hoe"];
+
+TOOL_MATERIALS.forEach((m, mi) => {
+    TOOL_KINDS.forEach((k, ki) => {
+        const st = TOOL_STATS[mi];
+        item(toolId(mi, ki), st.name + " " + KIND_NAMES[ki], {
+            icon: { flat: m.key + "_" + k },
+            stack: 1,
+            tool: { kind: k, tier: st.tier, speed: st.speed, durability: st.durability },
+            fuel: mi === 0 ? 200 : 0
+        });
+    });
+});
+
+export function itemDef(id) {
+    return ITEMS[id] || null;
+}
+
+export function itemName(id) {
+    const it = ITEMS[id];
+    return it ? it.name : "?";
+}
+
+/* ---------- Mining ---------- */
+
+export function canHarvest(block, tool) {
+    if (block.tier === 0) {
+        return true;
+    }
+    return !!tool && tool.kind === block.tool && tool.tier >= block.tier;
+}
+
+//Seconds needed to break `block` holding `itemId` (no modifiers)
+export function breakSeconds(block, itemId) {
+    if (block.hardness < 0) {
+        return Infinity;
+    }
+    if (block.hardness === 0) {
+        return 0;
+    }
+    const it = ITEMS[itemId];
+    const tool = it && it.tool;
+    let speed = 1;
+    if (tool && tool.kind === block.tool) {
+        speed = tool.speed;
+    }
+    if (block.id === B.LEAVES && tool && tool.kind === "axe") {
+        speed = tool.speed;
+    }
+    const factor = canHarvest(block, tool) ? 1.5 : 5;
+    return block.hardness * factor / speed;
+}
+
+export function blockDrops(id, meta, rng, itemId) {
+    const b = BLOCKS[id];
+    const it = ITEMS[itemId];
+    if (!canHarvest(b, it && it.tool)) {
+        return [];
+    }
+    if (b.shape === "slab") {
+        return [[id, meta === 2 ? 2 : 1]];
+    }
+    if (b.drops) {
+        return b.drops(meta, rng);
+    }
+    if (b.noItem) {
+        return [];
+    }
+    return [[id, 1]];
+}
+
+/* ---------- Crafting ---------- */
+
+//Shaped recipes are laid out on the crafting grid as drawn (mirroring is
+//allowed); shapeless ones only need the right items anywhere on the grid.
+//A recipe whose pattern fits in 2x2 can be made in the inventory, larger
+//ones need the 3x3 grid of a workbench.
+export const RECIPES = [];
+
+function finish(r) {
+    const need = new Map();
+    if (r.shape) {
+        r.h = r.shape.length;
+        r.w = Math.max(...r.shape.map((row) => row.length));
+        r.shape = r.shape.map((row) => row.padEnd(r.w, "."));
+        for (const row of r.shape) {
+            for (const ch of row) {
+                if (ch !== ".") {
+                    need.set(r.key[ch], (need.get(r.key[ch]) || 0) + 1);
+                }
+            }
+        }
+        r.small = r.w <= 2 && r.h <= 2;
+    } else {
+        for (const id of r.items) {
+            need.set(id, (need.get(id) || 0) + 1);
+        }
+        r.small = r.items.length <= 4;
+    }
+    r.inputs = [...need.entries()];
+    RECIPES.push(r);
+}
+
+function shaped(out, count, shape, key, group = "Building") {
+    finish({ out, count, shape, key, group });
+}
+
+function shapeless(out, count, items, group = "Building") {
+    finish({ out, count, items, group });
+}
+
+shapeless(B.PLANKS, 4, [B.LOG], "Basics");
+shaped(I.STICK, 4, ["P", "P"], { P: B.PLANKS }, "Basics");
+shaped(B.WORKBENCH, 1, ["PP", "PP"], { P: B.PLANKS }, "Basics");
+shaped(B.TORCH, 4, ["C", "S"], { C: I.COAL, S: I.STICK }, "Basics");
+shaped(B.CHEST, 1, ["PPP", "P.P", "PPP"], { P: B.PLANKS }, "Basics");
+shaped(B.FURNACE, 1, ["CCC", "C.C", "CCC"], { C: B.COBBLE }, "Basics");
+
+const TOOL_SHAPES = [
+    ["MMM", ".S.", ".S."],
+    ["MM", "MS", ".S"],
+    ["M", "S", "S"],
+    ["MM", ".S", ".S"]
+];
+TOOL_STATS.forEach((st, mi) => {
+    TOOL_SHAPES.forEach((shape, ki) => {
+        shaped(toolId(mi, ki), 1, shape, { M: st.material, S: I.STICK }, "Tools");
+    });
+});
+shaped(I.BUCKET, 1, ["I.I", ".I."], { I: I.IRON_INGOT }, "Tools");
+
+shaped(I.BOWL, 4, ["P.P", ".P."], { P: B.PLANKS }, "Food");
+shaped(I.BREAD, 1, ["WWW"], { W: I.WHEAT }, "Food");
+shapeless(I.STEW, 1, [B.MUSHROOM_BROWN, B.MUSHROOM_RED, I.BOWL], "Food");
+
+shaped(B.LADDER, 3, ["S.S", "SSS", "S.S"], { S: I.STICK });
+shaped(B.SANDSTONE, 1, ["SS", "SS"], { S: B.SAND });
+shaped(B.STONE_BRICKS, 4, ["SS", "SS"], { S: B.STONE });
+shaped(B.BRICKS, 1, ["BB", "BB"], { B: I.BRICK });
+shaped(B.CLAY, 1, ["CC", "CC"], { C: I.CLAY_BALL });
+shapeless(B.MOSSY_COBBLE, 1, [B.COBBLE, B.TALL_GRASS]);
+shaped(B.STONE_SLAB, 6, ["MMM"], { M: B.STONE });
+shaped(B.PLANK_SLAB, 6, ["MMM"], { M: B.PLANKS });
+shaped(B.COBBLE_SLAB, 6, ["MMM"], { M: B.COBBLE });
+shaped(B.SANDSTONE_SLAB, 6, ["MMM"], { M: B.SANDSTONE });
+shaped(B.LAMP, 1, [".G.", "GTG", ".G."], { G: B.GLASS, T: B.TORCH });
+for (const [block, ingot] of [[B.IRON_BLOCK, I.IRON_INGOT], [B.GOLD_BLOCK, I.GOLD_INGOT], [B.CRYSTAL_BLOCK, I.CRYSTAL]]) {
+    shaped(block, 1, ["III", "III", "III"], { I: ingot });
+    shapeless(ingot, 9, [block], "Basics");
+}
+
+//Find the recipe laid out on a size x size grid of item ids (0 = empty)
+export function matchRecipe(grid, size) {
+    let minX = size, minY = size, maxX = -1, maxY = -1;
+    const present = [];
+    for (let y = 0; y < size; y++) {
+        for (let x = 0; x < size; x++) {
+            const id = grid[y * size + x];
+            if (id) {
+                present.push(id);
+                minX = Math.min(minX, x);
+                maxX = Math.max(maxX, x);
+                minY = Math.min(minY, y);
+                maxY = Math.max(maxY, y);
+            }
+        }
+    }
+    if (!present.length) {
+        return null;
+    }
+    const w = maxX - minX + 1, h = maxY - minY + 1;
+    const sorted = present.slice().sort((a, b) => a - b).join(",");
+    for (const r of RECIPES) {
+        if (r.items) {
+            if (r.items.length === present.length && r.items.slice().sort((a, b) => a - b).join(",") === sorted) {
+                return r;
+            }
+            continue;
+        }
+        if (r.w !== w || r.h !== h) {
+            continue;
+        }
+        for (const mirror of [false, true]) {
+            let ok = true;
+            for (let y = 0; y < h && ok; y++) {
+                for (let x = 0; x < w; x++) {
+                    const ch = r.shape[y][mirror ? w - 1 - x : x];
+                    const want = ch === "." ? 0 : r.key[ch];
+                    if (grid[(minY + y) * size + minX + x] !== want) {
+                        ok = false;
+                        break;
+                    }
+                }
+            }
+            if (ok) {
+                return r;
+            }
+        }
+    }
+    return null;
+}
+
+//Grid cells (row major, for the given grid size) a recipe occupies
+export function recipeLayout(r, size) {
+    const cells = new Array(size * size).fill(0);
+    if (r.items) {
+        r.items.forEach((id, i) => {
+            cells[i] = id;
+        });
+        return cells;
+    }
+    for (let y = 0; y < r.h; y++) {
+        for (let x = 0; x < r.w; x++) {
+            const ch = r.shape[y][x];
+            cells[y * size + x] = ch === "." ? 0 : r.key[ch];
+        }
+    }
+    return cells;
+}
+
+/* ---------- Smelting ---------- */
+
+export const SMELT_TICKS = 200;
+
+export const SMELTING = new Map([
+    [B.IRON_ORE, I.IRON_INGOT],
+    [B.GOLD_ORE, I.GOLD_INGOT],
+    [B.CRYSTAL_ORE, I.CRYSTAL],
+    [B.COAL_ORE, I.COAL],
+    [B.SAND, B.GLASS],
+    [B.COBBLE, B.STONE],
+    [I.CLAY_BALL, I.BRICK],
+    [B.LOG, I.COAL],
+    [B.CACTUS, B.SAND]
+]);
+
+export function fuelTicks(id) {
+    const it = ITEMS[id];
+    return it ? it.fuel : 0;
+}
+
+//Everything a creative player can pick from, grouped for the palette tabs
+export function creativeGroups() {
+    const building = [B.STONE, B.COBBLE, B.MOSSY_COBBLE, B.STONE_BRICKS, B.BRICKS, B.DIRT, B.GRASS, B.SAND, B.SANDSTONE,
+        B.GRAVEL, B.CLAY, B.LOG, B.PLANKS, B.LEAVES, B.GLASS, B.LAMP, B.STONE_SLAB, B.PLANK_SLAB,
+        B.COBBLE_SLAB, B.SANDSTONE_SLAB, B.IRON_BLOCK, B.GOLD_BLOCK, B.CRYSTAL_BLOCK, B.COAL_ORE, B.IRON_ORE,
+        B.GOLD_ORE, B.CRYSTAL_ORE, B.LADDER, B.TORCH, B.WORKBENCH, B.FURNACE, B.CHEST];
+    const nature = [B.SAPLING, B.TALL_GRASS, B.FLOWER_YELLOW, B.FLOWER_RED, B.MUSHROOM_BROWN, B.MUSHROOM_RED,
+        B.CACTUS, B.REEDS, B.DEAD_BUSH, I.SEEDS];
+    const tools = [];
+    for (let mi = 0; mi < 5; mi++) {
+        for (let ki = 0; ki < 4; ki++) {
+            tools.push(toolId(mi, ki));
+        }
+    }
+    tools.push(I.BUCKET, I.WATER_BUCKET);
+    const items = [I.STICK, I.COAL, I.IRON_INGOT, I.GOLD_INGOT, I.CRYSTAL, I.FLINT, I.CLAY_BALL, I.BRICK,
+        I.WHEAT, I.BOWL, I.APPLE, I.BREAD, I.STEW];
+    return [
+        { name: "Building", ids: building },
+        { name: "Nature", ids: nature },
+        { name: "Tools", ids: tools },
+        { name: "Items", ids: items }
+    ];
+}

+ 127 - 0
src/web/Blocky/js/chat.js

@@ -0,0 +1,127 @@
+/*
+    Blocky - chat.js
+
+    The chat line: T opens it, / opens it with a slash already typed. Enter
+    runs the line (commands.js), Esc closes it, Up / Down walk through
+    earlier lines and Tab completes command and item names. Recent output
+    stays on screen for a few seconds after the line closes.
+*/
+
+import { runCommand, complete } from "./commands.js";
+import { escapeHtml } from "./util.js";
+
+const SHOW_SECONDS = 10;
+
+export class Chat {
+    constructor(app) {
+        this.app = app;
+        this.open = false;
+        this.lines = [];
+        this.history = [];
+        this.histPos = -1;
+        this.logEl = document.getElementById("chatLog");
+        this.inputEl = document.getElementById("chatInput");
+        this.inputEl.addEventListener("keydown", (e) => this.onKey(e));
+        setInterval(() => this.render(), 1000);
+    }
+
+    show(prefix) {
+        if (this.open) {
+            return;
+        }
+        this.open = true;
+        this.histPos = -1;
+        this.inputEl.value = prefix;
+        this.inputEl.classList.remove("hidden");
+        document.getElementById("chat").classList.add("open");
+        this.app.input.unlock();
+        this.inputEl.focus();
+        this.render();
+    }
+
+    close(resume) {
+        if (!this.open) {
+            return;
+        }
+        this.open = false;
+        this.inputEl.blur();
+        this.inputEl.classList.add("hidden");
+        document.getElementById("chat").classList.remove("open");
+        this.render();
+        if (resume) {
+            this.app.resumePlay();
+        }
+    }
+
+    add(text, kind = "ok") {
+        this.lines.push({ text, kind, t: performance.now() });
+        if (this.lines.length > 100) {
+            this.lines.shift();
+        }
+        this.render();
+    }
+
+    clear() {
+        this.lines = [];
+        this.close(false);
+        this.render();
+    }
+
+    onKey(e) {
+        e.stopPropagation();
+        if (e.key === "Enter") {
+            e.preventDefault();
+            const line = this.inputEl.value;
+            if (line.trim()) {
+                this.history.push(line);
+                if (this.history.length > 50) {
+                    this.history.shift();
+                }
+                const game = this.app.game;
+                if (game) {
+                    for (const m of runCommand(game, line)) {
+                        this.add(m.text, m.kind);
+                    }
+                }
+            }
+            this.close(true);
+        } else if (e.key === "Escape") {
+            e.preventDefault();
+            this.close(true);
+        } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
+            e.preventDefault();
+            if (!this.history.length) {
+                return;
+            }
+            if (e.key === "ArrowUp") {
+                this.histPos = this.histPos < 0 ? this.history.length - 1 : Math.max(0, this.histPos - 1);
+            } else if (this.histPos >= 0) {
+                this.histPos++;
+                if (this.histPos >= this.history.length) {
+                    this.histPos = -1;
+                    this.inputEl.value = "";
+                    return;
+                }
+            }
+            if (this.histPos >= 0) {
+                this.inputEl.value = this.history[this.histPos];
+            }
+        } else if (e.key === "Tab") {
+            e.preventDefault();
+            const r = complete(this.inputEl.value);
+            this.inputEl.value = r.line;
+            if (r.options.length > 1) {
+                this.add(r.options.slice(0, 24).join("  ") + (r.options.length > 24 ? "  ..." : ""), "hint");
+            }
+        }
+    }
+
+    render() {
+        const now = performance.now();
+        const visible = this.open ? this.lines.slice(-14) : this.lines.filter((l) => now - l.t < SHOW_SECONDS * 1000).slice(-8);
+        this.logEl.innerHTML = visible.map((l) => {
+            const fading = !this.open && now - l.t > (SHOW_SECONDS - 2) * 1000;
+            return `<div class="line ${l.kind}${fading ? " fading" : ""}">${escapeHtml(l.text)}</div>`;
+        }).join("");
+    }
+}

+ 449 - 0
src/web/Blocky/js/commands.js

@@ -0,0 +1,449 @@
+/*
+    Blocky - commands.js
+
+    Slash commands typed into the chat line (T, or / to start with a
+    slash). Everything that changes the world or the player needs the
+    world's "Allow cheats" option; /help and /seed always work.
+
+    Coordinates accept ~ for "where I am" and ~n for an offset, so
+    "/tp ~ ~10 ~" lifts you ten blocks.
+*/
+
+import { ITEMS, BLOCKS, B, itemName } from "./blocks.js";
+import { DIFFICULTY } from "./player.js";
+import { maxStack } from "./inventory.js";
+import { WORLD_H } from "./world.js";
+
+class CommandError extends Error {}
+
+const fail = (msg) => {
+    throw new CommandError(msg);
+};
+
+/* ---------------- item names ---------------- */
+
+const keyOf = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
+let itemKeys = null;
+
+const ALIASES = {
+    crafting_table: B.WORKBENCH,
+    table: B.WORKBENCH,
+    cobble: B.COBBLE,
+    wood: B.LOG,
+    sugar_cane: B.REEDS,
+    iron_block: B.IRON_BLOCK,
+    gold_block: B.GOLD_BLOCK,
+    crystal_block: B.CRYSTAL_BLOCK,
+    mossy_cobble: B.MOSSY_COBBLE,
+    double_stone_slab: B.STONE_SLAB
+};
+
+function names() {
+    if (!itemKeys) {
+        itemKeys = new Map();
+        ITEMS.forEach((it, id) => {
+            if (it) {
+                itemKeys.set(keyOf(it.name), id);
+            }
+        });
+        for (const [k, id] of Object.entries(ALIASES)) {
+            if (!itemKeys.has(k)) {
+                itemKeys.set(k, id);
+            }
+        }
+    }
+    return itemKeys;
+}
+
+//Item id from a name, an alias, a unique prefix or a number
+export function findItem(text) {
+    const t = keyOf(text);
+    if (/^\d+$/.test(t)) {
+        return ITEMS[Number(t)] ? Number(t) : null;
+    }
+    const map = names();
+    if (map.has(t)) {
+        return map.get(t);
+    }
+    const hits = [...map.keys()].filter((k) => k.startsWith(t) || k.endsWith("_" + t));
+    const ids = [...new Set(hits.map((k) => map.get(k)))];
+    return ids.length === 1 ? ids[0] : null;
+}
+
+function placeableBlock(text) {
+    const t = keyOf(text);
+    if (t === "air") {
+        return B.AIR;
+    }
+    if (t === "water") {
+        return B.WATER;
+    }
+    const id = findItem(text);
+    if (id === null || id > 255 || !BLOCKS[id]) {
+        fail(`Unknown block "${text}"`);
+    }
+    return id;
+}
+
+/* ---------------- argument helpers ---------------- */
+
+function coord(token, base, center) {
+    if (token === undefined) {
+        fail("Missing coordinate");
+    }
+    if (token.startsWith("~")) {
+        const rest = token.slice(1);
+        const off = rest === "" ? 0 : Number(rest);
+        if (!Number.isFinite(off)) {
+            fail(`"${token}" is not a coordinate`);
+        }
+        return base + off;
+    }
+    const v = Number(token);
+    if (!Number.isFinite(v)) {
+        fail(`"${token}" is not a coordinate`);
+    }
+    return center && Number.isInteger(v) ? v + 0.5 : v;
+}
+
+function int(token, name, min, max) {
+    const v = Number(token);
+    if (!Number.isInteger(v) || v < min || v > max) {
+        fail(`${name} must be a whole number from ${min} to ${max}`);
+    }
+    return v;
+}
+
+const TIMES = { sunrise: 0, day: 1000, morning: 1000, noon: 6000, sunset: 12000, evening: 12000, night: 13000, midnight: 18000 };
+
+function timeLabel(ticks) {
+    const tod = ticks % 24000;
+    const h = Math.floor((tod / 1000 + 6) % 24), m = Math.floor((tod % 1000) * 0.06);
+    return `day ${Math.floor(ticks / 24000) + 1}, ${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
+}
+
+//Top of a column: loaded terrain if we have it, else the generator's guess
+function surfaceY(game, x, z) {
+    const w = game.world;
+    if (w.isLoaded(Math.floor(x), Math.floor(z))) {
+        return w.rainTop(Math.floor(x), Math.floor(z));
+    }
+    return w.gen.column(Math.floor(x), Math.floor(z)).h + 1;
+}
+
+/* ---------------- commands ---------------- */
+
+export const COMMANDS = {
+    help: {
+        usage: "/help [command]",
+        desc: "List the commands, or explain one",
+        run(game, args) {
+            if (args[0]) {
+                const c = COMMANDS[args[0].replace(/^\//, "").toLowerCase()];
+                if (!c) {
+                    fail(`There is no /${args[0]} command`);
+                }
+                return [`${c.usage} - ${c.desc}`];
+            }
+            return ["Commands: " + Object.keys(COMMANDS).map((k) => "/" + k).join(", "), "Type /help <command> for details."];
+        }
+    },
+    give: {
+        usage: "/give [player] <item> [amount]",
+        desc: "Put items in your inventory, e.g. /give iron_ingot 32",
+        cheat: true,
+        run(game, args) {
+            //"/give <player> <item>": single player ignores the name
+            if (args.length >= 2 && findItem(args[0]) === null && !/^\d+$/.test(args[1]) && findItem(args[1]) !== null) {
+                args = args.slice(1);
+            }
+            if (!args[0]) {
+                fail("Usage: /give [player] <item> [amount]");
+            }
+            const id = findItem(args[0]);
+            if (id === null) {
+                fail(`Unknown item "${args[0]}". Try names like stone, planks, iron_pickaxe`);
+            }
+            const count = args[1] === undefined ? 1 : int(args[1], "Amount", 1, 64 * 36);
+            let left = count;
+            const max = maxStack(id);
+            let leftover = 0;
+            while (left > 0) {
+                const n = Math.min(left, max);
+                leftover += game.inventory.add(id, n);
+                left -= n;
+            }
+            if (leftover > 0) {
+                game.dropStack({ id, count: leftover });
+            }
+            game.ui.hudKey = "";
+            return [`Gave ${count} ${itemName(id)}`];
+        }
+    },
+    tp: {
+        usage: "/tp [player] <x> [y] <z>  or  /tp spawn",
+        desc: "Teleport; leave out y to land on the ground. ~ means your own position",
+        cheat: true,
+        run(game, args) {
+            const p = game.player;
+            if (args[0] === "spawn") {
+                game.teleport(game.spawn.x, null, game.spawn.z);
+                return ["Teleported to the world spawn"];
+            }
+            if (args.length === 4) {
+                args = args.slice(1);
+            }
+            let x, y, z;
+            if (args.length === 3) {
+                x = coord(args[0], p.x, true);
+                y = coord(args[1], p.y, false);
+                z = coord(args[2], p.z, true);
+                if (y < -20 || y > 400) {
+                    fail("y must be between -20 and 400");
+                }
+            } else if (args.length === 2) {
+                x = coord(args[0], p.x, true);
+                z = coord(args[1], p.z, true);
+                y = null;
+            } else {
+                fail("Usage: /tp <x> <y> <z> or /tp <x> <z>");
+            }
+            if (Math.abs(x) > 1e6 || Math.abs(z) > 1e6) {
+                fail("That is too far away");
+            }
+            game.teleport(x, y, z);
+            const shown = y === null ? surfaceY(game, x, z) : y;
+            return [`Teleported to ${x.toFixed(1)}, ${Number(shown).toFixed(1)}, ${z.toFixed(1)}`];
+        }
+    },
+    time: {
+        usage: "/time set <day|noon|sunset|night|midnight|ticks>, /time add <ticks>, /time query",
+        desc: "Change the time of day (a day is 24000 ticks)",
+        cheat: true,
+        run(game, args) {
+            const sub = (args[0] || "").toLowerCase();
+            if (sub === "query" || sub === "") {
+                return ["It is " + timeLabel(game.ticks)];
+            }
+            if (sub === "add") {
+                const n = int(args[1], "Ticks", 1, 240000);
+                game.ticks += n;
+                return ["It is now " + timeLabel(game.ticks)];
+            }
+            const target = sub === "set" ? (args[1] || "").toLowerCase() : sub;
+            let t = TIMES[target];
+            if (t === undefined) {
+                t = int(target, "Time", 0, 23999);
+            }
+            game.setTime(t);
+            return ["Time set to " + timeLabel(game.ticks)];
+        }
+    },
+    weather: {
+        usage: "/weather <clear|rain|thunder> [seconds]",
+        desc: "Change the weather",
+        cheat: true,
+        run(game, args) {
+            const s = (args[0] || "").toLowerCase();
+            if (!["clear", "rain", "thunder"].includes(s)) {
+                fail("Usage: /weather <clear|rain|thunder> [seconds]");
+            }
+            game.setWeather(s);
+            if (args[1] !== undefined) {
+                game.weather.timer = int(args[1], "Seconds", 1, 100000) * 20;
+            }
+            return [`Weather set to ${s}`];
+        }
+    },
+    gamemode: {
+        usage: "/gamemode <survival|creative>",
+        desc: "Switch game mode (s, c, 0 and 1 work too)",
+        cheat: true,
+        run(game, args) {
+            const m = (args[0] || "").toLowerCase();
+            const creative = ["creative", "c", "1"].includes(m);
+            if (!creative && !["survival", "s", "0"].includes(m)) {
+                fail("Usage: /gamemode <survival|creative>");
+            }
+            game.setMode(creative);
+            return [`Game mode set to ${creative ? "Creative" : "Survival"}`];
+        }
+    },
+    difficulty: {
+        usage: "/difficulty <peaceful|easy|normal|hard>",
+        desc: "Change how fast hunger drains",
+        cheat: true,
+        run(game, args) {
+            const v = (args[0] || "").toLowerCase();
+            let d = DIFFICULTY.findIndex((x) => x.name.toLowerCase() === v || x.name[0].toLowerCase() === v);
+            if (d < 0 && /^[0-3]$/.test(v)) {
+                d = Number(v);
+            }
+            if (d < 0) {
+                fail("Usage: /difficulty <peaceful|easy|normal|hard>");
+            }
+            game.setDifficulty(d);
+            return [`Difficulty set to ${DIFFICULTY[d].name}`];
+        }
+    },
+    setblock: {
+        usage: "/setblock <x> <y> <z> <block>",
+        desc: "Place a block (air removes one)",
+        cheat: true,
+        run(game, args) {
+            const p = game.player;
+            if (args.length < 4) {
+                fail("Usage: /setblock <x> <y> <z> <block>");
+            }
+            const x = Math.floor(coord(args[0], p.x, false));
+            const y = Math.floor(coord(args[1], p.y, false));
+            const z = Math.floor(coord(args[2], p.z, false));
+            const id = placeableBlock(args[3]);
+            if (y < 0 || y >= WORLD_H) {
+                fail(`y must be between 0 and ${WORLD_H - 1}`);
+            }
+            if (!game.world.isLoaded(x, z)) {
+                fail("That position is not loaded");
+            }
+            game.world.setBlock(x, y, z, id, 0);
+            if (id === B.WATER) {
+                game.world.schedule(x, y, z, 5);
+            }
+            if (id === B.FURNACE || id === B.CHEST) {
+                game.world.createTileEntity(x, y, z, id === B.FURNACE ? "furnace" : "chest");
+            }
+            return [`Placed ${id === B.AIR ? "air" : BLOCKS[id].name} at ${x}, ${y}, ${z}`];
+        }
+    },
+    clear: {
+        usage: "/clear [item]",
+        desc: "Empty your inventory, or remove one kind of item",
+        cheat: true,
+        run(game, args) {
+            const inv = game.inventory;
+            if (args[0]) {
+                const id = findItem(args[0]);
+                if (id === null) {
+                    fail(`Unknown item "${args[0]}"`);
+                }
+                const n = inv.count(id);
+                inv.remove(id, n);
+                game.ui.hudKey = "";
+                return [`Removed ${n} ${itemName(id)}`];
+            }
+            inv.clear();
+            game.ui.hudKey = "";
+            return ["Inventory cleared"];
+        }
+    },
+    heal: {
+        usage: "/heal",
+        desc: "Fill your health and food",
+        cheat: true,
+        run(game) {
+            const p = game.player;
+            p.health = 20;
+            p.food = 20;
+            p.saturation = 5;
+            p.air = 15;
+            game.ui.hudKey = "";
+            return ["Healed"];
+        }
+    },
+    kill: {
+        usage: "/kill",
+        desc: "Die and respawn",
+        cheat: true,
+        run(game) {
+            game.player.kill("command");
+            return [];
+        }
+    },
+    spawnpoint: {
+        usage: "/spawnpoint",
+        desc: "Respawn here from now on",
+        cheat: true,
+        run(game) {
+            const p = game.player;
+            game.spawn = { x: p.x, y: p.y, z: p.z };
+            return [`Spawn point set to ${Math.floor(p.x)}, ${Math.floor(p.y)}, ${Math.floor(p.z)}`];
+        }
+    },
+    seed: {
+        usage: "/seed",
+        desc: "Show the world seed",
+        run(game) {
+            const m = game.meta;
+            return [`Seed: ${m.seed}${m.seedText && m.seedText !== String(m.seed) ? ` (from "${m.seedText}")` : ""}`];
+        }
+    }
+};
+
+//Run one chat line; returns [{ text, kind }]
+export function runCommand(game, line) {
+    const text = line.trim();
+    if (!text) {
+        return [];
+    }
+    if (!text.startsWith("/")) {
+        return [{ text: "<You> " + text, kind: "say" }];
+    }
+    const [name, ...args] = text.slice(1).split(/\s+/);
+    const cmd = COMMANDS[name.toLowerCase()];
+    if (!cmd) {
+        return [{ text: `Unknown command /${name}. Type /help for a list.`, kind: "error" }];
+    }
+    if (cmd.cheat && !game.meta.cheats) {
+        return [{ text: "Cheats are off in this world. Turn them on in the pause menu to use /" + name.toLowerCase() + ".", kind: "error" }];
+    }
+    try {
+        return cmd.run(game, args).map((t) => ({ text: t, kind: "ok" }));
+    } catch (e) {
+        if (e instanceof CommandError) {
+            return [{ text: e.message, kind: "error" }];
+        }
+        throw e;
+    }
+}
+
+//Tab completion of the last word: command names, then item names
+export function complete(line) {
+    const parts = line.split(" ");
+    const last = parts[parts.length - 1];
+    let pool;
+    if (parts.length === 1) {
+        if (!last.startsWith("/")) {
+            return { line, options: [] };
+        }
+        pool = Object.keys(COMMANDS).map((k) => "/" + k);
+    } else {
+        const cmd = parts[0].slice(1).toLowerCase();
+        if (cmd === "gamemode") {
+            pool = ["survival", "creative"];
+        } else if (cmd === "weather") {
+            pool = ["clear", "rain", "thunder"];
+        } else if (cmd === "difficulty") {
+            pool = DIFFICULTY.map((d) => d.name.toLowerCase());
+        } else if (cmd === "time") {
+            pool = parts.length === 2 ? ["set", "add", "query"] : Object.keys(TIMES);
+        } else if (cmd === "help") {
+            pool = Object.keys(COMMANDS);
+        } else {
+            pool = [...names().keys()];
+        }
+    }
+    const lower = last.toLowerCase();
+    const options = pool.filter((o) => o.startsWith(lower)).sort();
+    if (!options.length) {
+        return { line, options: [] };
+    }
+    //Longest common prefix
+    let pre = options[0];
+    for (const o of options) {
+        while (!o.startsWith(pre)) {
+            pre = pre.slice(0, -1);
+        }
+    }
+    parts[parts.length - 1] = options.length === 1 ? options[0] + " " : pre;
+    return { line: parts.join(" "), options };
+}

+ 171 - 0
src/web/Blocky/js/entities.js

@@ -0,0 +1,171 @@
+/*
+    Blocky - entities.js
+
+    Dropped items (small spinning blocks or flat sprites that the player
+    picks up) and falling blocks (sand and gravel that lost their support).
+    There are no creatures in Blocky.
+*/
+
+import { B, BLOCKS } from "./blocks.js";
+import { moveAxis } from "./physics.js";
+
+const ITEM_HALF = 0.125;
+const DESPAWN = 300;
+
+export class Entities {
+    constructor(renderer) {
+        this.renderer = renderer;
+        this.items = [];
+        this.falling = [];
+    }
+
+    clear() {
+        for (const e of this.items) {
+            this.renderer.disposeItemMesh(e.mesh);
+        }
+        for (const e of this.falling) {
+            this.renderer.disposeItemMesh(e.mesh);
+        }
+        this.items = [];
+        this.falling = [];
+    }
+
+    spawnItem(x, y, z, id, count, dmg = 0, vel = null, pickupDelay = 0.5) {
+        if (this.items.length > 300) {
+            const old = this.items.shift();
+            this.renderer.disposeItemMesh(old.mesh);
+        }
+        const mesh = this.renderer.makeItemMesh(id);
+        mesh.scale.setScalar(mesh.userData.cube ? 0.25 : 0.42);
+        this.renderer.scene.add(mesh);
+        const v = vel || [(Math.random() - 0.5) * 2.4, 2.5 + Math.random() * 1.5, (Math.random() - 0.5) * 2.4];
+        this.items.push({
+            x, y, z, vx: v[0], vy: v[1], vz: v[2], id, count, dmg, age: 0, delay: pickupDelay,
+            spin: Math.random() * Math.PI * 2, mesh
+        });
+    }
+
+    spawnFalling(x, y, z, id, meta) {
+        const mesh = this.renderer.makeItemMesh(id);
+        mesh.scale.setScalar(0.999);
+        this.renderer.scene.add(mesh);
+        this.falling.push({ x: x + 0.5, y: y, z: z + 0.5, vy: 0, id, meta, mesh, age: 0 });
+    }
+
+    update(dt, world, player, inventory, onPickup) {
+        const r = this.renderer;
+        for (let i = this.items.length - 1; i >= 0; i--) {
+            const e = this.items[i];
+            e.age += dt;
+            if (e.age > DESPAWN) {
+                r.disposeItemMesh(e.mesh);
+                this.items.splice(i, 1);
+                continue;
+            }
+            //Attraction to the player
+            const px = player.x, py = player.y + 0.8, pz = player.z;
+            const dx = px - e.x, dy = py - e.y, dz = pz - e.z;
+            const dist = Math.hypot(dx, dy, dz);
+            const canPick = e.age > e.delay && !player.dead;
+            if (canPick && dist < 1.8) {
+                const k = 10 * dt / Math.max(0.3, dist);
+                e.vx += dx * k * 3;
+                e.vy += dy * k * 3;
+                e.vz += dz * k * 3;
+                if (dist < 0.7) {
+                    const left = inventory.add(e.id, e.count, e.dmg);
+                    if (left < e.count) {
+                        onPickup(e.id, e.count - left);
+                    }
+                    if (left === 0) {
+                        r.disposeItemMesh(e.mesh);
+                        this.items.splice(i, 1);
+                        continue;
+                    }
+                    e.count = left;
+                }
+            }
+            const inWater = world.getBlock(Math.floor(e.x), Math.floor(e.y), Math.floor(e.z)) === B.WATER;
+            e.vy -= (inWater ? 4 : 18) * dt;
+            if (inWater) {
+                e.vy = Math.max(e.vy, -1.5);
+                if (world.getBlock(Math.floor(e.x), Math.floor(e.y + 0.3), Math.floor(e.z)) === B.WATER) {
+                    e.vy += 8 * dt;
+                }
+            }
+            const box = [e.x - ITEM_HALF, e.y - ITEM_HALF, e.z - ITEM_HALF, e.x + ITEM_HALF, e.y + ITEM_HALF, e.z + ITEM_HALF];
+            //Pushed out of blocks it ended up inside of
+            const inside = BLOCKS[world.getBlock(Math.floor(e.x), Math.floor(e.y), Math.floor(e.z))];
+            if (inside.solid && inside.shape === "cube") {
+                e.y += 4 * dt;
+                e.vy = 0;
+            } else {
+                const my = moveAxis(world, box, 1, e.vy * dt);
+                const onGround = e.vy < 0 && my > e.vy * dt + 1e-6;
+                if (my !== e.vy * dt) {
+                    e.vy = 0;
+                }
+                if (moveAxis(world, box, 0, e.vx * dt) !== e.vx * dt) {
+                    e.vx = 0;
+                }
+                if (moveAxis(world, box, 2, e.vz * dt) !== e.vz * dt) {
+                    e.vz = 0;
+                }
+                const fr = Math.exp(-(onGround ? 8 : 1) * dt);
+                e.vx *= fr;
+                e.vz *= fr;
+                e.x = (box[0] + box[3]) / 2;
+                e.y = (box[1] + box[4]) / 2;
+                e.z = (box[2] + box[5]) / 2;
+            }
+            e.spin += dt * 1.6;
+            const bob = Math.sin(e.age * 2.5) * 0.06 + 0.1;
+            e.mesh.position.set(e.x, e.y + bob, e.z);
+            e.mesh.rotation.y = e.spin;
+            const lx = Math.floor(e.x), ly = Math.floor(e.y), lz = Math.floor(e.z);
+            r.setMeshLight(e.mesh, world.getSky(lx, ly, lz) / 15, world.getBlockLight(lx, ly, lz) / 15);
+        }
+
+        for (let i = this.falling.length - 1; i >= 0; i--) {
+            const e = this.falling[i];
+            e.age += dt;
+            e.vy = Math.max(-40, e.vy - 30 * dt);
+            const ny = e.y + e.vy * dt;
+            const bx = Math.floor(e.x), bz = Math.floor(e.z);
+            const below = world.getBlock(bx, Math.floor(ny), bz);
+            const landed = !world.canFallInto(below) || ny <= 0 || e.age > 20;
+            if (landed) {
+                const ty = Math.floor(ny) + 1;
+                r.disposeItemMesh(e.mesh);
+                this.falling.splice(i, 1);
+                const cur = world.getBlock(bx, ty, bz);
+                if (world.canFallInto(cur) && ty < 128) {
+                    if (cur !== B.AIR && cur !== B.WATER) {
+                        world.breakNaturally(bx, ty, bz);
+                    }
+                    world.setBlock(bx, ty, bz, e.id, e.meta);
+                } else {
+                    this.spawnItem(e.x, ty + 0.5, e.z, e.id, 1);
+                }
+                continue;
+            }
+            e.y = ny;
+            e.mesh.position.set(e.x, e.y + 0.5, e.z);
+            r.setMeshLight(e.mesh, world.getSky(bx, Math.floor(e.y), bz) / 15, world.getBlockLight(bx, Math.floor(e.y), bz) / 15);
+        }
+    }
+
+    serialize() {
+        return this.items.map((e) => ({ x: e.x, y: e.y, z: e.z, id: e.id, count: e.count, dmg: e.dmg, age: e.age }));
+    }
+
+    load(list) {
+        if (!Array.isArray(list)) {
+            return;
+        }
+        for (const e of list) {
+            this.spawnItem(e.x, e.y, e.z, e.id, e.count, e.dmg || 0, [0, 0, 0], 0);
+            this.items[this.items.length - 1].age = e.age || 0;
+        }
+    }
+}

+ 1026 - 0
src/web/Blocky/js/game.js

@@ -0,0 +1,1026 @@
+/*
+    Blocky - game.js
+
+    One running world: ties together the world simulation, the player, the
+    inventory, entities, weather and the day / night cycle, and turns input
+    into actions (mining, placing, using items, eating).
+
+    Time runs at 20 ticks per second; a full day is 24000 ticks (20 real
+    minutes). Tick 0 is sunrise.
+*/
+
+import {
+    B, BLOCKS, ITEMS, I, SHAPE, SOLID, blockDrops, breakSeconds, blockFaceLayer
+} from "./blocks.js";
+import { World, WORLD_H } from "./world.js";
+import { BIOME, BIOME_NAMES } from "./worldgen.js";
+import { Player, DIFFICULTY } from "./player.js";
+import { Inventory } from "./inventory.js";
+import { Entities } from "./entities.js";
+import { selectionBox, collisionBoxes, FACE_DIR } from "./shapes.js";
+import { deflateString, mulberry32, clamp, lerp } from "./util.js";
+
+const TICK = 0.05;
+const DAY = 24000;
+const AUTOSAVE_SECONDS = 120;
+
+const DEATH_TEXT = {
+    fall: "You hit the ground too hard",
+    drown: "You drowned",
+    starve: "You starved to death",
+    cactus: "You were pricked to death by a cactus",
+    lightning: "You were struck by lightning",
+    suffocate: "You suffocated in a wall",
+    command: "You ended it with a command",
+    void: "You fell out of the world"
+};
+
+export class Game {
+    constructor(app, meta, state) {
+        this.app = app;
+        this.renderer = app.renderer;
+        this.sound = app.sound;
+        this.ui = app.ui;
+        this.input = app.input;
+        this.meta = meta;
+        this.state = state;
+        this.rng = mulberry32((Date.now() ^ meta.seed) | 0);
+        this.paused = false;
+        this.hideHud = false;
+        this.debug = false;
+        this.accum = 0;
+        this.breaking = null;
+        this.breakCooldown = 0;
+        this.useCooldown = 0;
+        this.eatT = 0;
+        this.eatSound = 0;
+        this.swing = 1;
+        this.equip = 0;
+        this.lastHeld = -1;
+        this.lastSelected = -1;
+        this.stepDist = 0;
+        this.saving = false;
+        this.saveTimer = AUTOSAVE_SECONDS;
+        this.fovNow = 75;
+        this.frameNo = 0;
+        this.fps = 0;
+        this.fpsAcc = 0;
+        this.fpsFrames = 0;
+        this.placeOnGround = false;
+        this.wasInWater = false;
+        this.pickupSoundAt = 0;
+        this.hit = null;
+    }
+
+    get settings() {
+        return this.app.settings;
+    }
+
+    get creative() {
+        return this.player.creative;
+    }
+
+    /* ---------------- setup ---------------- */
+
+    async load(progress) {
+        const meta = this.meta, state = this.state || {};
+        this.world = new World(meta.seed, {
+            onDrop: (x, y, z, id, n, dmg) => this.entities.spawnItem(x, y, z, id, n, dmg || 0),
+            onFalling: (x, y, z, id, meta2) => this.entities.spawnFalling(x, y, z, id, meta2),
+            onBlockBroken: (x, y, z, id) => this.blockParticles(x, y, z, id, 0, 10)
+        });
+        this.renderer.attachWorld(this.world);
+        this.entities = new Entities(this.renderer);
+        this.player = new Player(this.world);
+        this.inventory = new Inventory();
+        this.player.creative = meta.mode === "creative";
+        this.player.difficulty = clamp(meta.difficulty ?? 2, 0, 3);
+        this.ticks = state.ticks ?? 1000;
+        //Every session starts with clear skies for 10-20 minutes
+        this.weather = {
+            state: "clear",
+            timer: 12000 + Math.floor(this.rng() * 12000),
+            rain: 0,
+            thunder: 0,
+            strikeIn: 4,
+            flash: 0
+        };
+        this.world.load(state.world);
+        if (state.spawn) {
+            this.spawn = state.spawn;
+        } else {
+            const s = this.world.gen.findSpawn();
+            this.spawn = { x: s.x, y: s.h + 1, z: s.z };
+        }
+        if (state.player) {
+            this.player.load(state.player);
+        } else {
+            this.player.setPos(this.spawn.x, this.spawn.y, this.spawn.z);
+            this.player.yaw = Math.PI * 0.75;
+            this.placeOnGround = true;
+        }
+        this.inventory.load(state.inventory);
+        if (!state.player && this.player.creative) {
+            //A starter hotbar for creative worlds
+            [B.GRASS, B.STONE, B.PLANKS, B.LOG, B.GLASS, B.BRICKS, B.TORCH, B.LAMP, B.WORKBENCH].forEach((id, i) => {
+                this.inventory.slots[i] = { id, count: ITEMS[id].stack, dmg: 0 };
+            });
+        }
+
+        //Stream the spawn area before showing it
+        const R = this.settings.renderDistance;
+        const pcx = Math.floor(this.player.x / 16), pcz = Math.floor(this.player.z / 16);
+        const need = Math.min(R, 3);
+        await new Promise((resolve) => {
+            const step = () => {
+                const t0 = performance.now();
+                this.world.stream(pcx, pcz, R, t0 + 40);
+                this.renderer.updateMeshes(this.world, this.player.x, this.player.z, need, t0 + 60);
+                let ready = 0, total = 0;
+                for (let dx = -need; dx <= need; dx++) {
+                    for (let dz = -need; dz <= need; dz++) {
+                        total++;
+                        const c = this.world.chunkAt(pcx + dx, pcz + dz);
+                        if (c && c.meshes && !c.dirty.some((d) => d)) {
+                            ready++;
+                        }
+                    }
+                }
+                progress(ready / total);
+                if (ready >= total) {
+                    resolve();
+                } else {
+                    setTimeout(step, 0);
+                }
+            };
+            step();
+        });
+        if (this.placeOnGround) {
+            this.dropToGround();
+        }
+        this.entities.load(state.entities);
+        this.ui.hudKey = "";
+    }
+
+    //Put the player on top of the column it stands in
+    dropToGround() {
+        const x = Math.floor(this.player.x), z = Math.floor(this.player.z);
+        if (!this.world.isLoaded(x, z)) {
+            return false;
+        }
+        let y = WORLD_H - 2;
+        while (y > 1 && !SOLID[this.world.getBlock(x, y - 1, z)] && this.world.getBlock(x, y - 1, z) !== B.WATER) {
+            y--;
+        }
+        this.player.setPos(this.player.x, y, this.player.z);
+        this.placeOnGround = false;
+        return true;
+    }
+
+    dispose() {
+        this.entities.clear();
+        this.renderer.detachWorld();
+        this.renderer.setHeldItem(0);
+        this.sound.setRain(0, false);
+    }
+
+    /* ---------------- per frame ---------------- */
+
+    frame(dt, now) {
+        const p = this.player, r = this.renderer, input = this.input;
+        this.frameNo++;
+        this.fpsAcc += dt;
+        this.fpsFrames++;
+        if (this.fpsAcc >= 0.5) {
+            this.fps = Math.round(this.fpsFrames / this.fpsAcc);
+            this.fpsAcc = 0;
+            this.fpsFrames = 0;
+        }
+        this.handleKeys();
+        const pcx = Math.floor(p.x / 16), pcz = Math.floor(p.z / 16);
+        const here = this.world.chunkAt(pcx, pcz);
+        const ready = here && here.lit;
+
+        if (!this.paused) {
+            this.accum += dt;
+            let n = 0;
+            while (this.accum >= TICK && n < 5) {
+                this.tick();
+                this.accum -= TICK;
+                n++;
+            }
+            if (n === 5) {
+                this.accum = 0;
+            }
+            //Look
+            const [mx, my] = input.consumeLook();
+            if (input.locked && !this.ui.isOpen() && !p.dead) {
+                const s = 0.0022 * this.settings.sensitivity;
+                p.yaw -= mx * s;
+                p.pitch -= my * s * (this.settings.invertY ? -1 : 1);
+                p.pitch = clamp(p.pitch, -1.55, 1.55);
+            }
+            if (this.touchLook) {
+                p.yaw -= this.touchLook[0];
+                p.pitch = clamp(p.pitch - this.touchLook[1], -1.55, 1.55);
+                this.touchLook = null;
+            }
+            //Move
+            if (this.placeOnGround && ready) {
+                this.dropToGround();
+            }
+            if (ready && !this.placeOnGround) {
+                const mv = this.movementInput();
+                let rem = Math.min(dt, 0.1);
+                while (rem > 1e-4) {
+                    const s = Math.min(rem, 1 / 60);
+                    p.update(s, mv);
+                    rem -= s;
+                }
+            }
+            this.handlePlayerEvents();
+            this.updateInteraction(dt);
+            this.entities.update(dt, this.world, p, this.inventory, (id, count) => this.onPickup(id, count));
+            r.updateParticles(dt, this.world);
+            r.updateLightning(dt);
+            this.updateWeather(dt);
+            this.saveTimer -= dt;
+            if (this.saveTimer <= 0) {
+                this.saveTimer = AUTOSAVE_SECONDS;
+                this.save(true);
+            }
+        } else {
+            input.consumeLook();
+        }
+
+        //Streaming
+        const R = this.settings.renderDistance;
+        this.world.stream(pcx, pcz, R, now + 7);
+        if (this.frameNo % 60 === 0) {
+            for (const c of this.world.unloadFar(pcx, pcz, R)) {
+                r.disposeChunk(c);
+            }
+        }
+        this.pendingMeshes = r.updateMeshes(this.world, p.x, p.z, R, performance.now() + 7);
+
+        this.updateCamera(dt);
+        const env = r.applyEnvironment({
+            time: this.ticks % DAY,
+            day: Math.floor(this.ticks / DAY),
+            rain: this.weather.rain,
+            thunder: this.weather.thunder,
+            flash: this.weather.flash,
+            underwater: p.headInWater,
+            renderDistance: R
+        });
+        this.world.skyDarken = Math.round((1 - env.day) * 11 + this.weather.rain * 2);
+        this.world.raining = this.weather.rain > 0.5;
+        const exposure = r.updateRain(dt, this.weather.rain, r.camera.position, this.world);
+        this.sound.setRain(this.paused ? 0 : this.weather.rain * (0.2 + 0.8 * exposure), exposure < 0.25);
+
+        //Held item
+        const held = this.inventory.heldId();
+        if (held !== this.lastHeld || this.inventory.selected !== this.lastSelected) {
+            if (this.lastSelected !== -1) {
+                this.equip = 1;
+                this.ui.showItemName(held);
+            }
+            this.lastHeld = held;
+            this.lastSelected = this.inventory.selected;
+        }
+        this.equip = Math.max(0, this.equip - dt * 6);
+        this.swing = Math.min(1, this.swing + dt * 4);
+        r.setHeldItem(held);
+        const ex = Math.floor(p.x), ey = Math.floor(p.eyeY), ez = Math.floor(p.z);
+        const bobOn = this.settings.viewBobbing && p.onGround && !p.flying;
+        const phase = p.walkDist * Math.PI * 0.75;
+        const amp = bobOn ? Math.min(1, Math.hypot(p.vx, p.vz) / 4.3) : 0;
+        r.updateHand({
+            swing: this.swing >= 1 ? 0 : this.swing,
+            equip: this.equip,
+            bobX: Math.sin(phase) * 0.03 * amp,
+            bobY: -Math.abs(Math.cos(phase)) * 0.03 * amp,
+            eat: this.eatT > 0 ? 1 : 0,
+            eatT: this.eatT,
+            sky: this.world.getSky(ex, ey, ez) / 15,
+            blk: this.world.getBlockLight(ex, ey, ez) / 15
+        });
+        r.render(dt, !this.hideHud && !p.dead);
+
+        this.ui.updateHud(this);
+        document.getElementById("underwater").classList.toggle("on", p.headInWater);
+        document.getElementById("hurt").classList.toggle("on", p.hurtTime > 0.3);
+        this.updateDebug();
+        input.endFrame();
+    }
+
+    movementInput() {
+        const k = (c) => this.input.down(c);
+        if (this.ui.isOpen() || this.player.dead || this.paused || this.app.chat.open) {
+            return { forward: 0, strafe: 0, jump: false, sneak: false, sprint: false };
+        }
+        const t = this.input.touchMove;
+        let forward = (k("KeyW") || k("ArrowUp") ? 1 : 0) - (k("KeyS") || k("ArrowDown") ? 1 : 0) + t.forward;
+        let strafe = (k("KeyD") || k("ArrowRight") ? 1 : 0) - (k("KeyA") || k("ArrowLeft") ? 1 : 0) + t.strafe;
+        if (!k("KeyW") && !k("ArrowUp") && t.forward <= 0.7) {
+            this.sprintTap = false;
+        }
+        return {
+            forward: clamp(forward, -1, 1),
+            strafe: clamp(strafe, -1, 1),
+            jump: k("Space") || this.input.touchJump,
+            sneak: k("ShiftLeft") || k("ShiftRight") || this.input.touchSneak,
+            sprint: k("ControlLeft") || k("ControlRight") || this.sprintTap
+        };
+    }
+
+    handleKeys() {
+        const input = this.input, ui = this.ui, p = this.player;
+        for (const code of input.pressed) {
+            if (code === "KeyE") {
+                if (ui.isOpen()) {
+                    this.closeScreen();
+                } else if (!this.paused && !p.dead) {
+                    this.openScreen("inventory");
+                }
+            } else if (code === "Escape") {
+                if (ui.isOpen()) {
+                    this.closeScreen();
+                }
+            } else if ((code === "KeyT" || code === "Slash") && !ui.isOpen() && !this.paused && !p.dead) {
+                this.app.chat.show(code === "Slash" ? "/" : "");
+            } else if (code.startsWith("Digit")) {
+                const n = Number(code.slice(5)) - 1;
+                if (n >= 0 && n < 9) {
+                    if (ui.isOpen()) {
+                        ui.hotkey(n);
+                    } else {
+                        this.inventory.selected = n;
+                    }
+                }
+            } else if (code === "KeyQ" && !ui.isOpen() && !this.paused && !p.dead) {
+                this.dropHeld(input.down("ControlLeft") || input.down("ControlRight"));
+            } else if (code === "F3") {
+                this.debug = !this.debug;
+            } else if (code === "F1") {
+                this.hideHud = !this.hideHud;
+                document.getElementById("hud").classList.toggle("bare", this.hideHud);
+            }
+        }
+        if (input.doubleTaps.has("Space") && this.creative && !ui.isOpen()) {
+            p.flying = !p.flying;
+            p.vy = 0;
+        }
+        if (input.doubleTaps.has("KeyW")) {
+            this.sprintTap = true;
+        }
+        const wheel = input.consumeWheel();
+        if (wheel !== 0 && !ui.isOpen()) {
+            this.inventory.selected = (this.inventory.selected + (wheel > 0 ? 1 : -1) + 9) % 9;
+        }
+    }
+
+    /* ---------------- ticks ---------------- */
+
+    tick() {
+        this.ticks++;
+        const p = this.player;
+        this.world.tick(Math.floor(p.x / 16), Math.floor(p.z / 16));
+        p.tick();
+        const w = this.weather;
+        w.timer--;
+        if (w.timer <= 0) {
+            if (w.state === "clear") {
+                w.state = this.rng() < 0.7 ? "rain" : "thunder";
+                w.timer = 3600 + Math.floor(this.rng() * 6000);
+            } else if (w.state === "thunder" && this.rng() < 0.35) {
+                w.state = "rain";
+                w.timer = 2400 + Math.floor(this.rng() * 3600);
+            } else {
+                w.state = "clear";
+                w.timer = 6000 + Math.floor(this.rng() * 14000);
+            }
+        }
+        if (this.ui.isOpen() && this.ui.screen.kind === "furnace" && this.ticks % 2 === 0) {
+            this.ui.renderScreen(false);
+        }
+    }
+
+    updateWeather(dt) {
+        const w = this.weather;
+        const rainTarget = w.state === "clear" ? 0 : 1;
+        const thunderTarget = w.state === "thunder" ? 1 : 0;
+        const step = dt * 0.12;
+        w.rain += clamp(rainTarget - w.rain, -step, step);
+        w.thunder += clamp(thunderTarget - w.thunder, -step, step);
+        w.flash = Math.max(0, w.flash - dt * 3.5);
+        if (w.state === "thunder" && w.thunder > 0.6) {
+            w.strikeIn -= dt;
+            if (w.strikeIn <= 0) {
+                w.strikeIn = 3 + this.rng() * 14;
+                this.lightningStrike();
+            }
+        }
+    }
+
+    lightningStrike() {
+        const p = this.player;
+        const ang = this.rng() * Math.PI * 2, d = 6 + this.rng() * 70;
+        const x = Math.floor(p.x + Math.cos(ang) * d), z = Math.floor(p.z + Math.sin(ang) * d);
+        if (!this.world.isLoaded(x, z) || this.world.biomeAt(x, z) === BIOME.DESERT) {
+            return;
+        }
+        const y = this.world.rainTop(x, z);
+        this.renderer.strikeLightning(x + 0.5, y, z + 0.5);
+        this.weather.flash = 1;
+        const dist = Math.hypot(x + 0.5 - p.x, z + 0.5 - p.z, y - p.y);
+        this.sound.play("thunder", { distance: dist });
+        if (dist < 3.5) {
+            p.hurt(5, "lightning");
+        }
+    }
+
+    setWeather(state) {
+        this.weather.state = state;
+        this.weather.timer = state === "clear" ? 12000 : 6000;
+        if (state === "thunder") {
+            this.weather.strikeIn = 2;
+        }
+    }
+
+    setTime(t) {
+        this.ticks = Math.floor(this.ticks / DAY) * DAY + t + (t < this.ticks % DAY ? DAY : 0);
+    }
+
+    setMode(creative) {
+        this.player.creative = creative;
+        if (!creative) {
+            this.player.flying = false;
+        }
+        this.meta.mode = creative ? "creative" : "survival";
+        this.ui.hudKey = "";
+    }
+
+    setDifficulty(d) {
+        this.player.difficulty = d;
+        this.meta.difficulty = d;
+    }
+
+    /* ---------------- interaction ---------------- */
+
+    eyeRay() {
+        const p = this.player;
+        const cp = Math.cos(p.pitch);
+        return [p.x, p.eyeY, p.z, -Math.sin(p.yaw) * cp, Math.sin(p.pitch), -Math.cos(p.yaw) * cp];
+    }
+
+    updateInteraction(dt) {
+        const p = this.player, input = this.input, r = this.renderer;
+        this.breakCooldown = Math.max(0, this.breakCooldown - dt);
+        this.useCooldown = Math.max(0, this.useCooldown - dt);
+        const active = !this.ui.isOpen() && !p.dead && !this.paused && !this.app.chat.open && (input.locked || this.touchActive);
+        if (!active) {
+            this.breaking = null;
+            this.eatT = 0;
+            r.setSelection(null);
+            r.setCrack(null, 0);
+            this.hit = null;
+            return;
+        }
+        const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
+        const reach = this.creative ? 5.5 : 4.5;
+        const hit = this.world.raycast(ox, oy, oz, dx, dy, dz, reach, selectionBox);
+        this.hit = hit;
+        r.setSelection(this.hideHud ? null : hit);
+
+        const leftDown = input.buttons.has(0) || this.touchBreak;
+        const rightDown = input.buttons.has(2);
+        const rightClick = input.clicked.has(2) || this.touchUse;
+        this.touchUse = false;
+
+        //Mining
+        if (leftDown) {
+            if (input.clicked.has(0) || this.swing >= 1) {
+                this.swing = 0;
+            }
+            if (this.creative) {
+                if (hit && this.breakCooldown <= 0) {
+                    this.breakBlock(hit, false);
+                    this.breakCooldown = 0.22;
+                }
+                this.breaking = null;
+            } else if (!hit) {
+                this.breaking = null;
+            } else {
+                const same = this.breaking && this.breaking.x === hit.x && this.breaking.y === hit.y && this.breaking.z === hit.z && this.breaking.id === hit.id;
+                if (!same) {
+                    this.breaking = { x: hit.x, y: hit.y, z: hit.z, id: hit.id, progress: 0, sound: 0 };
+                }
+                if (this.breakCooldown <= 0) {
+                    const def = BLOCKS[hit.id];
+                    let t = breakSeconds(def, this.inventory.heldId());
+                    if (p.headInWater) {
+                        t *= 5;
+                    }
+                    if (!p.onGround && !p.inWater && !p.onLadder) {
+                        t *= 5;
+                    }
+                    const b = this.breaking;
+                    b.progress = t <= 0 ? 1 : b.progress + dt / t;
+                    b.sound -= dt;
+                    if (b.sound <= 0 && b.progress < 1) {
+                        b.sound = 0.24;
+                        this.sound.block("dig", def.sound);
+                        this.blockParticles(hit.x, hit.y, hit.z, hit.id, hit.meta, 2, hit.point);
+                    }
+                    if (b.progress >= 1) {
+                        this.breakBlock(hit, true);
+                        this.breaking = null;
+                        this.breakCooldown = 0.25;
+                    }
+                }
+            }
+        } else {
+            this.breaking = null;
+        }
+        r.setCrack(hit, this.breaking ? this.breaking.progress : 0);
+
+        //Eating
+        const held = this.inventory.held;
+        const heldDef = held && ITEMS[held.id];
+        if (rightDown && heldDef && heldDef.food && !this.creative && p.food < 20 && !(hit && BLOCKS[hit.id].interact && !p.sneaking)) {
+            this.eatT += dt;
+            this.eatSound -= dt;
+            if (this.eatSound <= 0) {
+                this.eatSound = 0.22;
+                this.sound.play("eat");
+            }
+            if (this.eatT >= 1.6) {
+                p.eat(heldDef.food);
+                this.inventory.consumeHeld(1);
+                if (heldDef.food.leaves) {
+                    const left = this.inventory.add(heldDef.food.leaves, 1);
+                    if (left) {
+                        this.dropStack({ id: heldDef.food.leaves, count: 1 });
+                    }
+                }
+                this.sound.play("burp");
+                this.eatT = 0;
+            }
+            return;
+        }
+        this.eatT = 0;
+
+        //Using / placing
+        if (rightClick || (rightDown && this.useCooldown <= 0)) {
+            if (this.useCooldown <= 0 || rightClick) {
+                this.useCooldown = 0.25;
+                this.useItem(hit);
+            }
+        }
+    }
+
+    blockParticles(x, y, z, id, meta, count, point) {
+        const tex = this.app.tex;
+        const layer = blockFaceLayer(id, 4, meta || 0);
+        const name = tex.names[layer];
+        let col = tex.avgColor.get(name) || [128, 128, 128];
+        const def = BLOCKS[id];
+        if (def.tint) {
+            col = [col[0] * 0.55, col[1] * 0.9, col[2] * 0.4];
+        }
+        const light = Math.max(this.world.getSky(x, y + 1, z) / 15 * this.renderer.shared.uDaylight.value, this.world.getBlockLight(x, y + 1, z) / 15);
+        const px = point ? point[0] : x + 0.5, py = point ? point[1] : y + 0.5, pz = point ? point[2] : z + 0.5;
+        this.renderer.spawnParticles(px, py, pz, col, count, point ? 0.08 : 0.4, point ? 2 : 3, Math.max(0.15, light));
+    }
+
+    breakBlock(hit, survival) {
+        const { x, y, z, id, meta } = hit;
+        const def = BLOCKS[id];
+        if (def.hardness < 0 && !this.creative) {
+            return;
+        }
+        if (id === B.BEDROCK && !this.creative) {
+            return;
+        }
+        this.world.setBlock(x, y, z, B.AIR, 0);
+        this.sound.block("break", def.sound);
+        this.blockParticles(x, y, z, id, meta, 18);
+        if (survival) {
+            const heldId = this.inventory.heldId();
+            for (const [did, n] of blockDrops(id, meta, this.rng, heldId)) {
+                this.entities.spawnItem(x + 0.5, y + 0.4, z + 0.5, did, n);
+            }
+            if (def.hardness > 0 && this.inventory.damageHeld(1)) {
+                this.sound.play("toolBreak");
+            }
+            this.player.exhaust(0.005);
+        }
+    }
+
+    useItem(hit) {
+        const p = this.player, inv = this.inventory, w = this.world;
+        const held = inv.held;
+        const it = held && ITEMS[held.id];
+        if (hit && BLOCKS[hit.id].interact && !p.sneaking) {
+            this.interactBlock(hit);
+            return;
+        }
+        //Buckets look for water too
+        if (held && held.id === I.BUCKET) {
+            const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
+            const wh = w.raycast(ox, oy, oz, dx, dy, dz, 4.5, (bid, m) => (bid === B.WATER && m === 0 ? [0, 0, 0, 1, 0.875, 1] : selectionBox(bid, m)));
+            if (wh && wh.id === B.WATER && wh.meta === 0) {
+                w.setBlock(wh.x, wh.y, wh.z, B.AIR, 0);
+                this.sound.play("splash");
+                this.swing = 0;
+                if (!this.creative) {
+                    inv.consumeHeld(1);
+                    if (inv.held) {
+                        if (inv.add(I.WATER_BUCKET, 1)) {
+                            this.dropStack({ id: I.WATER_BUCKET, count: 1 });
+                        }
+                    } else {
+                        inv.slots[inv.selected] = { id: I.WATER_BUCKET, count: 1, dmg: 0 };
+                    }
+                }
+            }
+            return;
+        }
+        if (!hit || !held) {
+            return;
+        }
+        if (it.tool && it.tool.kind === "hoe") {
+            if ((hit.id === B.GRASS || hit.id === B.DIRT) && hit.face !== 3 && w.getBlock(hit.x, hit.y + 1, hit.z) === B.AIR) {
+                w.setBlock(hit.x, hit.y, hit.z, B.FARMLAND, 0);
+                this.sound.block("step", "gravel");
+                this.swing = 0;
+                if (!this.creative && inv.damageHeld(1)) {
+                    this.sound.play("toolBreak");
+                }
+            }
+            return;
+        }
+        if (held.id === I.WATER_BUCKET) {
+            const t = this.placeTarget(hit);
+            if (t && (w.getBlock(t[0], t[1], t[2]) === B.AIR || BLOCKS[w.getBlock(t[0], t[1], t[2])].replaceable)) {
+                const cur = w.getBlock(t[0], t[1], t[2]);
+                if (cur !== B.AIR && cur !== B.WATER) {
+                    w.breakNaturally(t[0], t[1], t[2]);
+                }
+                w.setBlock(t[0], t[1], t[2], B.WATER, 0);
+                w.schedule(t[0], t[1], t[2], 5);
+                this.sound.play("splash");
+                this.swing = 0;
+                if (!this.creative) {
+                    inv.slots[inv.selected] = { id: I.BUCKET, count: 1, dmg: 0 };
+                }
+            }
+            return;
+        }
+        if (it.plant) {
+            if (hit.id === B.FARMLAND && hit.face === 2 && w.getBlock(hit.x, hit.y + 1, hit.z) === B.AIR) {
+                w.setBlock(hit.x, hit.y + 1, hit.z, it.plant, 0);
+                this.sound.block("place", "grass");
+                this.swing = 0;
+                if (!this.creative) {
+                    inv.consumeHeld(1);
+                }
+            }
+            return;
+        }
+        if (it.block) {
+            this.placeBlock(hit, it.block);
+        }
+    }
+
+    placeTarget(hit) {
+        const def = BLOCKS[hit.id];
+        if (def.replaceable && hit.id !== B.WATER) {
+            return [hit.x, hit.y, hit.z];
+        }
+        const d = FACE_DIR[hit.face];
+        return [hit.x + d[0], hit.y + d[1], hit.z + d[2]];
+    }
+
+    placeBlock(hit, bid) {
+        const w = this.world, p = this.player, inv = this.inventory;
+        const def = BLOCKS[bid];
+        const face = hit.face;
+        //Completing a slab into a double slab
+        if (SHAPE[bid] === "slab" && hit.id === bid && ((hit.meta === 0 && face === 2) || (hit.meta === 1 && face === 3))) {
+            this.finishPlace(hit.x, hit.y, hit.z, bid, 2);
+            return;
+        }
+        const t = this.placeTarget(hit);
+        const [x, y, z] = t;
+        if (y < 0 || y >= WORLD_H) {
+            return;
+        }
+        const cur = w.getBlock(x, y, z);
+        const curMeta = w.getMeta(x, y, z);
+        let meta = 0;
+        if (SHAPE[bid] === "slab") {
+            if (cur === bid && curMeta !== 2) {
+                this.finishPlace(x, y, z, bid, 2);
+                return;
+            }
+            meta = face === 3 ? 1 : face === 2 ? 0 : (hit.point[1] - hit.y > 0.5 ? 1 : 0);
+        }
+        if (!BLOCKS[cur].replaceable) {
+            return;
+        }
+        if (bid === B.TORCH) {
+            if (face === 3) {
+                return;
+            }
+            meta = face;
+        } else if (bid === B.LADDER) {
+            if (face === 2 || face === 3) {
+                return;
+            }
+            meta = face;
+        } else if (def.orient) {
+            const lx = -Math.sin(p.yaw), lz = -Math.cos(p.yaw);
+            if (Math.abs(lx) > Math.abs(lz)) {
+                meta = lx > 0 ? 1 : 0;
+            } else {
+                meta = lz > 0 ? 5 : 4;
+            }
+        } else if (bid === B.LEAVES) {
+            meta = 1;
+        }
+        if (def.support && !w.hasSupport(x, y, z, bid, meta)) {
+            return;
+        }
+        if (SOLID[bid]) {
+            const pb = p.box();
+            for (const b of collisionBoxes(bid, meta)) {
+                if (pb[0] < x + b[3] && pb[3] > x + b[0] && pb[1] < y + b[4] && pb[4] > y + b[1] && pb[2] < z + b[5] && pb[5] > z + b[2]) {
+                    return;
+                }
+            }
+        }
+        if (cur !== B.AIR && cur !== B.WATER) {
+            w.breakNaturally(x, y, z);
+        }
+        this.finishPlace(x, y, z, bid, meta);
+    }
+
+    finishPlace(x, y, z, bid, meta) {
+        const w = this.world;
+        if (!w.setBlock(x, y, z, bid, meta)) {
+            return;
+        }
+        if (bid === B.FURNACE) {
+            w.createTileEntity(x, y, z, "furnace");
+        } else if (bid === B.CHEST) {
+            w.createTileEntity(x, y, z, "chest");
+        }
+        this.sound.block("place", BLOCKS[bid].sound);
+        this.swing = 0;
+        if (!this.creative) {
+            this.inventory.consumeHeld(1);
+        }
+    }
+
+    interactBlock(hit) {
+        const w = this.world;
+        const kind = BLOCKS[hit.id].interact;
+        if (kind === "workbench") {
+            this.openScreen("workbench");
+        } else {
+            let te = w.getTileEntity(hit.x, hit.y, hit.z);
+            if (!te) {
+                te = w.createTileEntity(hit.x, hit.y, hit.z, kind);
+            }
+            this.openScreen(kind, te);
+        }
+    }
+
+    /* ---------------- items ---------------- */
+
+    dropHeld(whole) {
+        const inv = this.inventory;
+        const s = inv.held;
+        if (!s) {
+            return;
+        }
+        const n = whole ? s.count : 1;
+        this.dropStack({ id: s.id, count: n, dmg: s.dmg || 0 });
+        inv.consumeHeld(n);
+        this.swing = 0;
+    }
+
+    dropStack(stack) {
+        const p = this.player;
+        const [, , , dx, dy, dz] = this.eyeRay();
+        this.entities.spawnItem(p.x + dx * 0.4, p.eyeY - 0.3, p.z + dz * 0.4, stack.id, stack.count, stack.dmg || 0,
+            [dx * 5, dy * 5 + 1.5, dz * 5], 1.5);
+    }
+
+    onPickup() {
+        const now = performance.now();
+        if (now - this.pickupSoundAt > 60) {
+            this.pickupSoundAt = now;
+            this.sound.play("pop");
+        }
+        this.ui.hudKey = "";
+        if (this.ui.isOpen()) {
+            this.ui.renderScreen(false);
+        }
+    }
+
+    /* ---------------- screens ---------------- */
+
+    openScreen(kind, te = null) {
+        this.ui.open(kind, te);
+        this.input.unlock();
+    }
+
+    closeScreen() {
+        this.ui.close();
+        this.app.resumePlay();
+    }
+
+    /* ---------------- player events ---------------- */
+
+    handlePlayerEvents() {
+        const p = this.player;
+        for (const e of p.events) {
+            if (e.type === "hurt") {
+                this.sound.play("hurt");
+            } else if (e.type === "death") {
+                this.onDeath(e.cause);
+            } else if (e.type === "land" && e.fall > 1.2) {
+                const id = this.world.getBlock(Math.floor(p.x), Math.floor(p.y - 0.2), Math.floor(p.z));
+                this.sound.block("step", BLOCKS[id].sound);
+            }
+        }
+        p.events.length = 0;
+        //Footsteps
+        if (p.onGround && !p.sneaking && p.walkDist - this.stepDist > 2.1) {
+            this.stepDist = p.walkDist;
+            const id = this.world.getBlock(Math.floor(p.x), Math.floor(p.y - 0.2), Math.floor(p.z));
+            if (id !== B.AIR) {
+                this.sound.block("step", BLOCKS[id].sound);
+            }
+        } else if (p.walkDist - this.stepDist > 4) {
+            this.stepDist = p.walkDist;
+        }
+        if (p.inWater && !this.wasInWater && p.vy < -3) {
+            this.sound.play("splash");
+        }
+        this.wasInWater = p.inWater;
+    }
+
+    onDeath(cause) {
+        const p = this.player;
+        if (!this.creative) {
+            for (const s of this.inventory.slots) {
+                if (s) {
+                    this.entities.spawnItem(p.x, p.y + 1, p.z, s.id, s.count, s.dmg || 0,
+                        [(this.rng() - 0.5) * 5, 2 + this.rng() * 3, (this.rng() - 0.5) * 5], 1);
+                }
+            }
+            this.inventory.clear();
+        }
+        this.ui.close();
+        this.app.showDeath(DEATH_TEXT[cause] || "You died");
+    }
+
+    //Move the player; y null lands on the ground once the terrain is there
+    teleport(x, y, z) {
+        const p = this.player;
+        if (y === null) {
+            const fx = Math.floor(x), fz = Math.floor(z);
+            const top = this.world.isLoaded(fx, fz) ? this.world.rainTop(fx, fz) : this.world.gen.column(fx, fz).h + 1;
+            p.setPos(x, top, z);
+            this.placeOnGround = true;
+        } else {
+            p.setPos(x, y, z);
+        }
+        this.breaking = null;
+    }
+
+    respawn() {
+        const p = this.player;
+        p.respawn({ x: this.spawn.x, y: this.spawn.y, z: this.spawn.z });
+        this.placeOnGround = true;
+        this.dropToGround();
+        this.ui.hudKey = "";
+    }
+
+    /* ---------------- camera ---------------- */
+
+    updateCamera(dt) {
+        const p = this.player, cam = this.renderer.camera;
+        let bx = 0, by = 0, roll = 0;
+        if (this.settings.viewBobbing && p.onGround && !p.flying) {
+            const phase = p.walkDist * Math.PI * 0.75;
+            const amp = Math.min(1, Math.hypot(p.vx, p.vz) / 4.3);
+            bx = Math.sin(phase) * 0.035 * amp;
+            by = -Math.abs(Math.cos(phase)) * 0.06 * amp;
+            roll = Math.sin(phase) * 0.006 * amp;
+        }
+        if (p.hurtTime > 0) {
+            roll += Math.sin(p.hurtTime * 40) * 0.04 * p.hurtTime;
+        }
+        const cos = Math.cos(p.yaw), sin = Math.sin(p.yaw);
+        cam.position.set(p.x + cos * bx, p.eyeY + by, p.z - sin * bx);
+        cam.rotation.set(p.pitch, p.yaw, roll);
+        let fov = this.settings.fov;
+        if (p.sprinting) {
+            fov *= p.flying ? 1.15 : 1.1;
+        }
+        if (this.eatT > 0) {
+            fov *= 0.98;
+        }
+        this.fovNow = lerp(this.fovNow, fov, 1 - Math.exp(-10 * dt));
+        if (Math.abs(cam.fov - this.fovNow) > 0.01) {
+            cam.fov = this.fovNow;
+            cam.updateProjectionMatrix();
+        }
+    }
+
+    updateDebug() {
+        const el = document.getElementById("debug");
+        const showFps = this.settings.showFps;
+        if (!this.debug && !showFps) {
+            el.classList.add("hidden");
+            return;
+        }
+        el.classList.remove("hidden");
+        if (!this.debug) {
+            el.textContent = this.fps + " fps";
+            return;
+        }
+        const p = this.player, w = this.world;
+        const bx = Math.floor(p.x), by = Math.floor(p.y), bz = Math.floor(p.z);
+        const deg = ((-p.yaw * 180 / Math.PI) % 360 + 360) % 360;
+        const facing = ["north (-Z)", "east (+X)", "south (+Z)", "west (-X)"][Math.round(deg / 90) % 4];
+        const tod = this.ticks % DAY;
+        const hours = Math.floor((tod / 1000 + 6) % 24), mins = Math.floor((tod % 1000) * 0.06);
+        const lines = [
+            `Blocky - ${this.fps} fps`,
+            `XYZ: ${p.x.toFixed(2)} / ${p.y.toFixed(2)} / ${p.z.toFixed(2)}`,
+            `Block: ${bx} ${by} ${bz}   Chunk: ${bx >> 4} ${bz >> 4}`,
+            `Facing: ${facing}`,
+            `Biome: ${BIOME_NAMES[w.biomeAt(bx, bz)]}`,
+            `Light: sky ${w.getSky(bx, Math.floor(p.eyeY), bz)}, block ${w.getBlockLight(bx, Math.floor(p.eyeY), bz)}`,
+            `Day ${Math.floor(this.ticks / DAY) + 1}, ${String(hours).padStart(2, "0")}:${String(mins).padStart(2, "0")}`,
+            `Weather: ${this.weather.state} (rain ${this.weather.rain.toFixed(2)})`,
+            `Chunks: ${w.chunks.size} loaded, ${this.pendingMeshes || 0} sections queued`,
+            `Entities: ${this.entities.items.length} items, ${this.entities.falling.length} falling`,
+            `Mode: ${this.creative ? "Creative" : "Survival"} - ${DIFFICULTY[p.difficulty].name}`
+        ];
+        if (!this.creative) {
+            lines.push(`Food ${p.food}  Saturation ${p.saturation.toFixed(1)}  Exhaustion ${p.exhaustion.toFixed(2)}`);
+        }
+        if (this.hit) {
+            lines.push(`Looking at: ${BLOCKS[this.hit.id].name} (${this.hit.x}, ${this.hit.y}, ${this.hit.z}) meta ${this.hit.meta}`);
+        }
+        el.textContent = lines.join("\n");
+    }
+
+    /* ---------------- saving ---------------- */
+
+    snapshot() {
+        return {
+            version: 1,
+            ticks: this.ticks,
+            weather: { state: this.weather.state, timer: this.weather.timer },
+            spawn: this.spawn,
+            player: this.player.serialize(),
+            inventory: this.inventory.serialize(),
+            world: this.world.serialize(),
+            entities: this.entities.serialize()
+        };
+    }
+
+    async save(quiet) {
+        if (this.saving) {
+            return false;
+        }
+        this.saving = true;
+        const ind = document.getElementById("saving");
+        ind.classList.remove("hidden");
+        try {
+            const packed = await deflateString(JSON.stringify(this.snapshot()));
+            this.meta.lastPlayed = Date.now();
+            this.meta.mode = this.creative ? "creative" : "survival";
+            this.meta.difficulty = this.player.difficulty;
+            await this.app.storage.save(this.meta, JSON.stringify(packed));
+            if (!quiet) {
+                this.ui.toast("World saved");
+            }
+            return true;
+        } catch (e) {
+            this.ui.toast("Could not save the world: " + e.message);
+            return false;
+        } finally {
+            this.saving = false;
+            ind.classList.add("hidden");
+        }
+    }
+}

+ 70 - 0
src/web/Blocky/js/icons.js

@@ -0,0 +1,70 @@
+/*
+    Blocky - icons.js
+
+    Renders every item into one sprite sheet: blocks as small isometric
+    cubes, everything else as its flat tile. The UI shows icons as CSS
+    backgrounds cut from this sheet.
+*/
+
+import { ITEMS, BLOCKS, SHAPE, blockFaceLayer } from "./blocks.js";
+import { drawIsoIcon, drawFlatIcon, ICON, GRASS_TINT, FOLIAGE_TINT } from "./textures.js";
+
+export function buildIcons(tex) {
+    const ids = [];
+    for (let i = 0; i < ITEMS.length; i++) {
+        if (ITEMS[i]) {
+            ids.push(i);
+        }
+    }
+    const cols = 16;
+    const rows = Math.ceil(ids.length / cols);
+    const canvas = document.createElement("canvas");
+    canvas.width = cols * ICON;
+    canvas.height = rows * ICON;
+    const ctx = canvas.getContext("2d");
+    const pos = new Map();
+    const tileCanvas = (layer) => tex.canvases.get(tex.names[layer]);
+    ids.forEach((id, n) => {
+        const x = (n % cols) * ICON, y = Math.floor(n / cols) * ICON;
+        pos.set(id, [n % cols, Math.floor(n / cols)]);
+        const it = ITEMS[id];
+        if (it.icon && it.icon.flat) {
+            drawFlatIcon(ctx, x, y, tex.canvases.get(it.icon.flat), it.icon.tint === "grass" ? GRASS_TINT : null);
+            return;
+        }
+        const bid = it.block;
+        const def = BLOCKS[bid];
+        const meta = def.orient ? 4 : 0;
+        const tiles = {
+            top: tileCanvas(blockFaceLayer(bid, 2, meta)),
+            left: tileCanvas(blockFaceLayer(bid, 4, meta)),
+            right: tileCanvas(blockFaceLayer(bid, 0, meta))
+        };
+        const opts = { half: SHAPE[bid] === "slab" };
+        if (def.tint === "grass") {
+            opts.topTint = GRASS_TINT;
+        } else if (def.tint === "foliage") {
+            opts.topTint = FOLIAGE_TINT;
+            opts.sideTint = FOLIAGE_TINT;
+        }
+        drawIsoIcon(ctx, x, y, tiles, opts);
+    });
+    const icons = { pos, cols, rows };
+    //One style rule carries the sheet; elements only set size and offset
+    canvas.toBlob((blob) => {
+        const style = document.createElement("style");
+        style.textContent = `.ic{background-image:url(${URL.createObjectURL(blob)});}`;
+        document.head.appendChild(style);
+    });
+    return icons;
+}
+
+//Inline style for an .ic element of `size` pixels
+export function iconCss(icons, id, size) {
+    const p = icons.pos.get(id);
+    if (!p) {
+        return "background:none;";
+    }
+    return `background-size:${icons.cols * size}px ${icons.rows * size}px;` +
+        `background-position:${-p[0] * size}px ${-p[1] * size}px;`;
+}

+ 161 - 0
src/web/Blocky/js/input.js

@@ -0,0 +1,161 @@
+/*
+    Blocky - input.js
+
+    Keyboard and mouse state. Mouse look and buttons only count while the
+    pointer is locked to the game canvas; key presses are collected as
+    edges (pressed this frame) plus held state, with double tap detection
+    for flying and sprinting.
+*/
+
+const GAME_KEYS = new Set(["Space", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "F1", "F3", "Tab", "KeyQ", "KeyE", "Slash", "KeyT"]);
+
+export class Input {
+    constructor(canvas) {
+        this.canvas = canvas;
+        this.keys = new Set();
+        this.pressed = new Set();
+        this.doubleTaps = new Set();
+        this.buttons = new Set();
+        this.clicked = new Set();
+        this.lastTap = {};
+        this.dx = 0;
+        this.dy = 0;
+        this.wheel = 0;
+        this.active = false;
+        this.onLockChange = null;
+        //Touch controls write into these
+        this.touchMove = { forward: 0, strafe: 0 };
+        this.touchJump = false;
+        this.touchSneak = false;
+
+        window.addEventListener("keydown", (e) => {
+            if (e.target && (e.target.tagName === "INPUT" || e.target.tagName === "SELECT" || e.target.tagName === "TEXTAREA")) {
+                return;
+            }
+            if (!this.active) {
+                return;
+            }
+            if (GAME_KEYS.has(e.code) || (e.code.startsWith("Digit") && this.locked)) {
+                e.preventDefault();
+            }
+            if (!e.repeat) {
+                this.pressed.add(e.code);
+                const now = performance.now();
+                if (now - (this.lastTap[e.code] || 0) < 300) {
+                    this.doubleTaps.add(e.code);
+                    this.lastTap[e.code] = 0;
+                } else {
+                    this.lastTap[e.code] = now;
+                }
+            }
+            this.keys.add(e.code);
+        });
+        window.addEventListener("keyup", (e) => {
+            this.keys.delete(e.code);
+        });
+        window.addEventListener("blur", () => {
+            this.keys.clear();
+            this.buttons.clear();
+        });
+        document.addEventListener("mousedown", (e) => {
+            if (!this.locked) {
+                return;
+            }
+            this.buttons.add(e.button);
+            this.clicked.add(e.button);
+            e.preventDefault();
+        });
+        document.addEventListener("mouseup", (e) => {
+            this.buttons.delete(e.button);
+        });
+        document.addEventListener("contextmenu", (e) => {
+            if (this.locked || this.active) {
+                e.preventDefault();
+            }
+        });
+        document.addEventListener("mousemove", (e) => {
+            if (!this.locked) {
+                return;
+            }
+            //Ignore the occasional huge jump some browsers report on lock
+            if (Math.abs(e.movementX) > 400 || Math.abs(e.movementY) > 400) {
+                return;
+            }
+            this.dx += e.movementX;
+            this.dy += e.movementY;
+        });
+        document.addEventListener("wheel", (e) => {
+            if (this.locked) {
+                this.wheel += Math.sign(e.deltaY);
+            }
+        }, { passive: true });
+        document.addEventListener("pointerlockchange", () => {
+            if (!this.locked) {
+                this.buttons.clear();
+            }
+            if (this.onLockChange) {
+                this.onLockChange(this.locked);
+            }
+        });
+    }
+
+    get locked() {
+        return document.pointerLockElement === this.canvas;
+    }
+
+    //Returns a promise that settles once the lock was granted or refused
+    lock() {
+        return new Promise((resolve) => {
+            if (this.locked) {
+                resolve(true);
+                return;
+            }
+            try {
+                const r = this.canvas.requestPointerLock();
+                if (r && typeof r.then === "function") {
+                    r.then(() => resolve(true), () => resolve(false));
+                } else {
+                    setTimeout(() => resolve(this.locked), 150);
+                }
+            } catch (e) {
+                resolve(false);
+            }
+        });
+    }
+
+    unlock() {
+        if (this.locked) {
+            document.exitPointerLock();
+        }
+    }
+
+    down(code) {
+        return this.keys.has(code);
+    }
+
+    consumeLook() {
+        const r = [this.dx, this.dy];
+        this.dx = 0;
+        this.dy = 0;
+        return r;
+    }
+
+    consumeWheel() {
+        const w = this.wheel;
+        this.wheel = 0;
+        return w;
+    }
+
+    endFrame() {
+        this.pressed.clear();
+        this.doubleTaps.clear();
+        this.clicked.clear();
+    }
+
+    reset() {
+        this.keys.clear();
+        this.buttons.clear();
+        this.endFrame();
+        this.dx = this.dy = this.wheel = 0;
+    }
+}

+ 147 - 0
src/web/Blocky/js/inventory.js

@@ -0,0 +1,147 @@
+/*
+    Blocky - inventory.js
+
+    The player inventory: 36 slots, the first 9 are the hotbar. A stack is
+    { id, count, dmg } where dmg is the wear of a tool.
+*/
+
+import { ITEMS, RECIPES } from "./blocks.js";
+
+export function maxStack(id) {
+    const it = ITEMS[id];
+    return it ? it.stack : 64;
+}
+
+export function cloneStack(s) {
+    return s ? { id: s.id, count: s.count, dmg: s.dmg || 0 } : null;
+}
+
+export class Inventory {
+    constructor() {
+        this.slots = new Array(36).fill(null);
+        this.selected = 0;
+    }
+
+    get held() {
+        return this.slots[this.selected];
+    }
+
+    heldId() {
+        const s = this.slots[this.selected];
+        return s ? s.id : 0;
+    }
+
+    //Add items; returns how many did not fit
+    add(id, count, dmg = 0) {
+        const max = maxStack(id);
+        const order = [];
+        for (let i = 0; i < 36; i++) {
+            order.push(i);
+        }
+        if (max > 1) {
+            for (const i of order) {
+                const s = this.slots[i];
+                if (s && s.id === id && s.count < max && (s.dmg || 0) === dmg) {
+                    const n = Math.min(count, max - s.count);
+                    s.count += n;
+                    count -= n;
+                    if (count === 0) {
+                        return 0;
+                    }
+                }
+            }
+        }
+        for (const i of order) {
+            if (!this.slots[i]) {
+                const n = Math.min(count, max);
+                this.slots[i] = { id, count: n, dmg };
+                count -= n;
+                if (count === 0) {
+                    return 0;
+                }
+            }
+        }
+        return count;
+    }
+
+    count(id) {
+        let n = 0;
+        for (const s of this.slots) {
+            if (s && s.id === id) {
+                n += s.count;
+            }
+        }
+        return n;
+    }
+
+    remove(id, count) {
+        for (let i = 35; i >= 0 && count > 0; i--) {
+            const s = this.slots[i];
+            if (s && s.id === id) {
+                const n = Math.min(count, s.count);
+                s.count -= n;
+                count -= n;
+                if (s.count <= 0) {
+                    this.slots[i] = null;
+                }
+            }
+        }
+        return count === 0;
+    }
+
+    consumeHeld(n = 1) {
+        const s = this.slots[this.selected];
+        if (!s) {
+            return;
+        }
+        s.count -= n;
+        if (s.count <= 0) {
+            this.slots[this.selected] = null;
+        }
+    }
+
+    //Wear the held tool; returns true when it broke
+    damageHeld(amount = 1) {
+        const s = this.slots[this.selected];
+        const it = s && ITEMS[s.id];
+        if (!it || !it.tool) {
+            return false;
+        }
+        s.dmg = (s.dmg || 0) + amount;
+        if (s.dmg >= it.tool.durability) {
+            this.slots[this.selected] = null;
+            return true;
+        }
+        return false;
+    }
+
+    canCraft(r) {
+        return r.inputs.every(([id, n]) => this.count(id) >= n);
+    }
+
+    clear() {
+        this.slots.fill(null);
+    }
+
+    serialize() {
+        return { slots: this.slots.map(cloneStack), selected: this.selected };
+    }
+
+    load(d) {
+        this.clear();
+        if (!d || !Array.isArray(d.slots)) {
+            return;
+        }
+        d.slots.slice(0, 36).forEach((s, i) => {
+            if (s && ITEMS[s.id] && s.count > 0) {
+                this.slots[i] = { id: s.id, count: s.count, dmg: s.dmg || 0 };
+            }
+        });
+        this.selected = Math.max(0, Math.min(8, d.selected | 0));
+    }
+}
+
+//Recipes that fit a crafting grid of the given size (2 or 3)
+export function recipesFor(size) {
+    return RECIPES.filter((r) => size === 3 || r.small);
+}

+ 728 - 0
src/web/Blocky/js/main.js

@@ -0,0 +1,728 @@
+/*
+    Blocky - main.js
+
+    Boots the game: paints the textures, builds the renderer, runs the start
+    screen (with a slowly turning view of a generated world behind it), the
+    world list and world creation, settings, and hands over to a Game once a
+    world is opened.
+*/
+
+import { buildTextures, ICON } from "./textures.js";
+import { resolveBlockTextures } from "./blocks.js";
+import { buildIcons } from "./icons.js";
+import { Renderer } from "./render.js";
+import { Sound } from "./audio.js";
+import { Storage, newWorldId } from "./storage.js";
+import { UI } from "./ui.js";
+import { Input } from "./input.js";
+import { Game } from "./game.js";
+import { World } from "./world.js";
+import { DIFFICULTY } from "./player.js";
+import { setupTouch } from "./touch.js";
+import { Chat } from "./chat.js";
+import { COMMANDS } from "./commands.js";
+import { seedFromString, inflateString, escapeHtml, mulberry32 } from "./util.js";
+
+const SETTINGS_KEY = "blocky.settings";
+const DEFAULT_SETTINGS = {
+    renderDistance: 6,
+    fov: 75,
+    sensitivity: 1,
+    brightness: 0.5,
+    volume: 0.7,
+    pixelRatio: 1,
+    fancyLeaves: true,
+    clouds: true,
+    viewBobbing: true,
+    invertY: false,
+    showFps: false
+};
+const PREVIEW_SEED = 734011;
+
+const $ = (id) => document.getElementById(id);
+const show = (id, on = true) => $(id).classList.toggle("hidden", !on);
+
+const DIFF_HINTS = [
+    "No hunger, health refills on its own.",
+    "Hunger drains slowly; starving stops at half health.",
+    "Hunger drains at the usual pace; starving leaves you at half a heart.",
+    "Hunger drains fast and starving can kill you."
+];
+
+class App {
+    constructor() {
+        this.state = "menu";
+        this.game = null;
+        this.preview = null;
+        this.worlds = [];
+        this.selectedWorld = null;
+        this.newMode = "survival";
+        this.newDiff = 2;
+        this.touchMode = window.matchMedia("(pointer: coarse)").matches && !window.matchMedia("(pointer: fine)").matches;
+    }
+
+    loadSettings() {
+        let s = {};
+        try {
+            s = JSON.parse(localStorage.getItem(SETTINGS_KEY)) || {};
+        } catch (e) {
+            s = {};
+        }
+        this.settings = Object.assign({}, DEFAULT_SETTINGS, s);
+        if (this.touchMode && !s.renderDistance) {
+            this.settings.renderDistance = 4;
+        }
+    }
+
+    saveSettings() {
+        try {
+            localStorage.setItem(SETTINGS_KEY, JSON.stringify(this.settings));
+        } catch (e) {
+            //Settings simply do not persist
+        }
+    }
+
+    boot() {
+        this.loadSettings();
+        this.tex = buildTextures();
+        resolveBlockTextures(this.tex.layerOf);
+        this.icons = buildIcons(this.tex);
+        this.canvas = $("view");
+        this.renderer = new Renderer(this.canvas, this.tex);
+        this.renderer.applySettings(this.settings);
+        this.sound = new Sound();
+        this.sound.setVolume(this.settings.volume);
+        this.storage = new Storage();
+        this.input = new Input(this.canvas);
+        this.ui = new UI(this);
+        this.chat = new Chat(this);
+        this.drawLogo();
+        this.bindMenu();
+        this.bindOverlays();
+        this.bindSettings();
+        if (this.touchMode) {
+            setupTouch(this);
+        }
+        window.addEventListener("resize", () => this.renderer.resize());
+        this.input.onLockChange = (locked) => this.onLockChange(locked);
+        this.startPreview();
+        this.storage.init().then(() => {
+            $("storageNote").textContent = "Worlds are saved to " + this.storage.where + ".";
+        });
+        document.addEventListener("pointerdown", () => this.sound.ensure(), { capture: true });
+        document.addEventListener("keydown", () => this.sound.ensure(), { capture: true });
+        if (typeof ao_module_setWindowTitle === "function") {
+            try {
+                ao_module_setWindowTitle("Blocky");
+            } catch (e) {
+                //Not inside a desktop window
+            }
+        }
+        this.last = performance.now();
+        requestAnimationFrame((t) => this.loop(t));
+    }
+
+    loop(now) {
+        requestAnimationFrame((t) => this.loop(t));
+        const dt = Math.min(0.1, Math.max(0, (now - this.last) / 1000));
+        this.last = now;
+        try {
+            if (this.state === "playing" && this.game) {
+                this.game.frame(dt, now);
+            } else if (this.preview) {
+                this.previewFrame(dt, now);
+            }
+        } catch (e) {
+            console.error(e);
+            this.fatal(e);
+        }
+    }
+
+    fatal(e) {
+        if (this.failed) {
+            return;
+        }
+        this.failed = true;
+        $("errorText").textContent = String(e && e.message ? e.message : e);
+        show("error");
+    }
+
+    /* ---------------- logo ---------------- */
+
+    drawLogo() {
+        const glyphs = {
+            B: ["####.", "#...#", "#...#", "####.", "#...#", "#...#", "####."],
+            L: ["#....", "#....", "#....", "#....", "#....", "#....", "#####"],
+            O: [".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###."],
+            C: [".####", "#....", "#....", "#....", "#....", "#....", ".####"],
+            K: ["#...#", "#..#.", "#.#..", "##...", "#.#..", "#..#.", "#...#"],
+            Y: ["#...#", "#...#", ".#.#.", "..#..", "..#..", "..#..", "..#.."]
+        };
+        const c = $("logo");
+        const ctx = c.getContext("2d");
+        ctx.imageSmoothingEnabled = false;
+        const cell = 20, depth = 6;
+        const word = "BLOCKY";
+        const width = word.length * 6 * cell - cell;
+        const ox = (c.width - width) / 2, oy = 20;
+        const side = this.tex.canvases.get("grass_side");
+        const top = this.tex.canvases.get("stone");
+        const rng = mulberry32(7);
+        const cells = [];
+        [...word].forEach((ch, i) => {
+            glyphs[ch].forEach((row, y) => {
+                [...row].forEach((v, x) => {
+                    if (v === "#") {
+                        cells.push([ox + (i * 6 + x) * cell, oy + y * cell + (i % 2 ? 4 : 0), y]);
+                    }
+                });
+            });
+        });
+        //Extruded shadow first, then the faces
+        for (const [x, y] of cells) {
+            ctx.fillStyle = "#1d2a14";
+            ctx.fillRect(x + depth, y + depth, cell, cell);
+        }
+        for (const [x, y, row] of cells) {
+            const tile = row === 0 ? side : top;
+            ctx.drawImage(tile, 0, row === 0 ? 0 : Math.floor(rng() * 8), 16, 8, x, y, cell, cell);
+            ctx.fillStyle = row === 0 ? "rgba(255,255,255,0.08)" : "rgba(0,0,0," + (0.05 + row * 0.03) + ")";
+            ctx.fillRect(x, y, cell, cell);
+            ctx.fillStyle = "rgba(255,255,255,0.25)";
+            ctx.fillRect(x, y, cell, 2);
+            ctx.fillStyle = "rgba(0,0,0,0.3)";
+            ctx.fillRect(x, y + cell - 2, cell, 2);
+        }
+    }
+
+    /* ---------------- preview world ---------------- */
+
+    startPreview() {
+        if (this.preview) {
+            return;
+        }
+        const world = new World(PREVIEW_SEED);
+        const s = world.gen.findSpawn();
+        this.renderer.attachWorld(world);
+        //Start out looking at the most land
+        let yaw = 0, best = -1;
+        for (let k = 0; k < 16; k++) {
+            const a = (k / 16) * Math.PI * 2;
+            let land = 0;
+            for (let d = 12; d <= 60; d += 12) {
+                const c = world.gen.column(Math.floor(s.x - Math.sin(a) * d), Math.floor(s.z - Math.cos(a) * d));
+                land += c.h >= 62 ? 1 : 0;
+            }
+            if (land > best) {
+                best = land;
+                yaw = a;
+            }
+        }
+        this.preview = { world, x: s.x, z: s.z, y: Math.max(s.h + 14, 80), yaw: yaw + 0.5, t: 0 };
+        this.renderer.camera.fov = 70;
+        this.renderer.camera.updateProjectionMatrix();
+    }
+
+    stopPreview() {
+        if (!this.preview) {
+            return;
+        }
+        this.renderer.detachWorld();
+        this.preview = null;
+    }
+
+    previewFrame(dt, now) {
+        const pv = this.preview, r = this.renderer;
+        pv.t += dt;
+        pv.yaw -= dt * 0.035;
+        const pcx = Math.floor(pv.x / 16), pcz = Math.floor(pv.z / 16);
+        const R = Math.min(5, this.settings.renderDistance);
+        pv.world.stream(pcx, pcz, R, now + 10);
+        r.updateMeshes(pv.world, pv.x, pv.z, R, performance.now() + 8);
+        r.camera.position.set(pv.x, pv.y, pv.z);
+        r.camera.rotation.set(-0.22, pv.yaw, 0);
+        r.applyEnvironment({ time: 1200 + pv.t * 4, day: 2, rain: 0, thunder: 0, flash: 0, underwater: false, renderDistance: R });
+        r.updateRain(dt, 0, r.camera.position, pv.world);
+        r.updateParticles(dt, pv.world);
+        r.render(dt, false);
+    }
+
+    /* ---------------- menu ---------------- */
+
+    showPage(id) {
+        for (const p of ["pageMain", "pageWorlds", "pageCreate"]) {
+            show(p, p === id);
+        }
+    }
+
+    bindMenu() {
+        $("btnPlay").onclick = () => {
+            this.showPage("pageWorlds");
+            this.refreshWorlds();
+        };
+        $("btnSettings").onclick = () => this.openSettings();
+        $("btnHelp").onclick = () => show("help");
+        $("btnHelpDone").onclick = () => show("help", false);
+        const inDesktop = typeof ao_module_virtualDesktop !== "undefined" && ao_module_virtualDesktop;
+        if (!inDesktop) {
+            show("btnQuit", false);
+        }
+        $("btnQuit").onclick = () => {
+            if (typeof ao_module_close === "function") {
+                ao_module_close();
+            }
+        };
+        $("btnWorldsBack").onclick = () => this.showPage("pageMain");
+        $("btnNewWorld").onclick = () => {
+            $("newName").value = "New World";
+            $("newSeed").value = "";
+            this.showPage("pageCreate");
+            $("newName").focus();
+            $("newName").select();
+        };
+        $("btnCreateCancel").onclick = () => this.showPage("pageWorlds");
+        $("btnPlayWorld").onclick = () => {
+            if (this.selectedWorld) {
+                this.openWorld(this.selectedWorld);
+            }
+        };
+        $("btnDeleteWorld").onclick = () => {
+            const w = this.worlds.find((x) => x.id === this.selectedWorld);
+            if (!w) {
+                return;
+            }
+            this.confirm(`"${w.name}" will be lost forever. This cannot be undone.`, async () => {
+                try {
+                    await this.storage.remove(w.id);
+                } catch (e) {
+                    alert("Could not delete the world: " + e.message);
+                }
+                this.selectedWorld = null;
+                this.refreshWorlds();
+            });
+        };
+        $("newMode").addEventListener("click", (e) => {
+            const b = e.target.closest("[data-mode]");
+            if (!b) {
+                return;
+            }
+            this.newMode = b.dataset.mode;
+            this.markToggle("newMode", "mode", this.newMode);
+            $("modeHint").textContent = this.newMode === "creative"
+                ? "Unlimited blocks, instant mining and flight. No hunger or damage."
+                : "Gather resources, craft tools and keep yourself fed.";
+        });
+        $("newDiff").addEventListener("click", (e) => {
+            const b = e.target.closest("[data-diff]");
+            if (!b) {
+                return;
+            }
+            this.newDiff = Number(b.dataset.diff);
+            this.markToggle("newDiff", "diff", String(this.newDiff));
+            $("diffHint").textContent = DIFF_HINTS[this.newDiff];
+        });
+        $("diffHint").textContent = DIFF_HINTS[this.newDiff];
+        $("btnCreate").onclick = () => this.createWorld();
+        $("newName").addEventListener("keydown", (e) => {
+            if (e.key === "Enter") {
+                this.createWorld();
+            }
+        });
+    }
+
+    markToggle(groupId, attr, value) {
+        $(groupId).querySelectorAll("[data-" + attr + "]").forEach((b) => {
+            b.classList.toggle("on", b.dataset[attr] === value);
+        });
+    }
+
+    confirm(text, onYes) {
+        $("confirmText").textContent = text;
+        show("confirm");
+        $("btnConfirmYes").onclick = () => {
+            show("confirm", false);
+            onYes();
+        };
+        $("btnConfirmNo").onclick = () => show("confirm", false);
+    }
+
+    async refreshWorlds() {
+        const list = $("worldList");
+        list.innerHTML = "<div class=\"empty\">Loading worlds...</div>";
+        try {
+            await (this.storage.ready || (this.storage.ready = this.storage.init()));
+            this.worlds = await this.storage.list();
+        } catch (e) {
+            list.innerHTML = `<div class="empty">Could not read your worlds: ${escapeHtml(e.message)}</div>`;
+            return;
+        }
+        if (!this.worlds.length) {
+            list.innerHTML = "<div class=\"empty\">No worlds yet. Create one to start playing.</div>";
+        } else {
+            list.innerHTML = this.worlds.map((w) => {
+                const when = w.lastPlayed ? new Date(w.lastPlayed).toLocaleString() : "never";
+                const mode = w.mode === "creative" ? "Creative" : "Survival";
+                const diff = (DIFFICULTY[w.difficulty] || DIFFICULTY[2]).name;
+                const size = w.size ? (w.size / 1024 < 1024 ? Math.ceil(w.size / 1024) + " KB" : (w.size / 1048576).toFixed(1) + " MB") : "";
+                return `<div class="world ${w.id === this.selectedWorld ? "sel" : ""}" data-id="${escapeHtml(w.id)}">
+                    <div><b>${escapeHtml(w.name || "World")}</b><span>${mode}, ${diff}${w.cheats ? ", cheats" : ""}</span></div>
+                    <div class="wmeta"><span>${escapeHtml(when)}</span><br><span>${size}</span></div></div>`;
+            }).join("");
+        }
+        list.querySelectorAll(".world").forEach((el) => {
+            el.onclick = () => {
+                this.selectedWorld = el.dataset.id;
+                list.querySelectorAll(".world").forEach((x) => x.classList.toggle("sel", x === el));
+                this.updateWorldButtons();
+            };
+            el.ondblclick = () => this.openWorld(el.dataset.id);
+        });
+        if (!this.worlds.find((w) => w.id === this.selectedWorld)) {
+            this.selectedWorld = null;
+        }
+        this.updateWorldButtons();
+    }
+
+    updateWorldButtons() {
+        $("btnPlayWorld").disabled = !this.selectedWorld;
+        $("btnDeleteWorld").disabled = !this.selectedWorld;
+    }
+
+    async createWorld() {
+        const name = $("newName").value.trim() || "New World";
+        const seedText = $("newSeed").value.trim();
+        const meta = {
+            id: newWorldId(name),
+            name,
+            seed: seedFromString(seedText),
+            seedText,
+            mode: this.newMode,
+            difficulty: this.newDiff,
+            cheats: $("newCheats").checked,
+            created: Date.now(),
+            lastPlayed: Date.now(),
+            gen: 0,
+            version: 1
+        };
+        await this.startGame(meta, null);
+    }
+
+    async openWorld(id) {
+        this.showLoading("Loading world", "Reading save data...");
+        let meta, state;
+        try {
+            const res = await this.storage.load(id);
+            meta = res.meta;
+            const packed = JSON.parse(res.payload);
+            state = JSON.parse(await inflateString(packed.encoding, packed.data));
+        } catch (e) {
+            show("loading", false);
+            alert("Could not open the world: " + e.message);
+            return;
+        }
+        await this.startGame(meta, state);
+    }
+
+    showLoading(title, text) {
+        $("loadTitle").textContent = title;
+        $("loadText").textContent = text;
+        $("loadBar").style.width = "0%";
+        show("loading");
+    }
+
+    async startGame(meta, state) {
+        this.sound.ensure();
+        this.showLoading(state ? "Loading world" : "Generating terrain", "Building the area around you...");
+        show("menu", false);
+        this.stopPreview();
+        this.state = "loading";
+        const game = new Game(this, meta, state);
+        this.game = game;
+        game.touchActive = this.touchMode;
+        try {
+            await game.load((f) => {
+                $("loadBar").style.width = Math.round(f * 100) + "%";
+            });
+        } catch (e) {
+            console.error(e);
+            this.fatal(e);
+            return;
+        }
+        if (!state) {
+            //Write the new world straight away so it shows up in the list
+            await game.save(true);
+        }
+        show("loading", false);
+        show("hud");
+        this.state = "playing";
+        this.input.active = true;
+        this.input.reset();
+        if (typeof ao_module_setWindowTitle === "function") {
+            try {
+                ao_module_setWindowTitle("Blocky - " + meta.name);
+            } catch (e) {
+                //Not inside a desktop window
+            }
+        }
+        if (this.touchMode) {
+            show("touch");
+        } else {
+            show("resume");
+        }
+    }
+
+    async quitToTitle() {
+        const game = this.game;
+        if (!game) {
+            return;
+        }
+        show("pause", false);
+        show("death", false);
+        this.showLoading("Saving world", "Writing your world to " + this.storage.where + "...");
+        $("loadBar").style.width = "100%";
+        if (game.player.dead) {
+            game.respawn();
+        }
+        await game.save(true);
+        game.dispose();
+        this.game = null;
+        this.state = "menu";
+        this.input.active = false;
+        this.input.unlock();
+        show("hud", false);
+        show("touch", false);
+        show("resume", false);
+        show("loading", false);
+        show("menu");
+        this.ui.close();
+        this.chat.clear();
+        this.startPreview();
+        this.showPage("pageWorlds");
+        this.refreshWorlds();
+        if (typeof ao_module_setWindowTitle === "function") {
+            try {
+                ao_module_setWindowTitle("Blocky");
+            } catch (e) {
+                //Not inside a desktop window
+            }
+        }
+    }
+
+    /* ---------------- in-game overlays ---------------- */
+
+    bindOverlays() {
+        $("resume").addEventListener("click", () => this.resumePlay());
+        $("btnResume").onclick = () => this.resumePlay();
+        $("btnPauseSettings").onclick = () => this.openSettings();
+        $("btnSaveQuit").onclick = () => this.quitToTitle();
+        $("btnRespawn").onclick = () => {
+            this.game.respawn();
+            show("death", false);
+            this.resumePlay();
+        };
+        $("btnDeathTitle").onclick = () => this.quitToTitle();
+        $("btnDiff").onclick = () => {
+            this.game.setDifficulty((this.game.player.difficulty + 1) % 4);
+            this.refreshPause();
+        };
+        $("btnCheats").onclick = () => {
+            this.game.meta.cheats = !this.game.meta.cheats;
+            this.refreshPause();
+        };
+        $("btnMode").onclick = () => {
+            this.game.setMode(!this.game.creative);
+            this.refreshPause();
+        };
+        $("btnTime").onclick = () => {
+            //Jump ahead to the next of sunrise, noon, sunset and midnight
+            const tod = this.game.ticks % 24000;
+            const next = [0, 6000, 12000, 18000].find((t) => t > tod + 100);
+            this.game.setTime(next === undefined ? 0 : next);
+            this.refreshPause();
+        };
+        $("btnWeather").onclick = () => {
+            const order = ["clear", "rain", "thunder"];
+            const g = this.game;
+            g.setWeather(order[(order.indexOf(g.weather.state) + 1) % 3]);
+            this.refreshPause();
+        };
+        $("btnCommands").onclick = () => this.showCommands();
+        $("btnCmdDone").onclick = () => show("cmdhelp", false);
+        $("btnPauseHelp").onclick = () => show("help");
+        window.addEventListener("keydown", (e) => {
+            if (this.state !== "playing") {
+                return;
+            }
+            //Esc first closes whatever sits on top of the pause menu
+            if (e.code === "Escape" && this.game && this.game.paused) {
+                for (const id of ["settings", "cmdhelp", "help"]) {
+                    if (!$(id).classList.contains("hidden")) {
+                        show(id, false);
+                        this.pausedAt = performance.now();
+                        return;
+                    }
+                }
+            }
+            //The Esc that released the pointer lock must not also resume
+            if (e.code === "Escape" && this.game && this.game.paused && performance.now() - this.pausedAt > 400) {
+                e.preventDefault();
+                this.resumePlay();
+            }
+        });
+        window.addEventListener("beforeunload", () => {
+            if (this.game && this.state === "playing") {
+                this.game.save(true);
+            }
+        });
+    }
+
+    onLockChange(locked) {
+        if (this.state !== "playing" || !this.game) {
+            return;
+        }
+        if (locked) {
+            show("resume", false);
+            return;
+        }
+        const g = this.game;
+        if (!this.ui.isOpen() && !g.player.dead && !g.paused && !this.chat.open) {
+            this.pause();
+        }
+    }
+
+    pause() {
+        const g = this.game;
+        g.paused = true;
+        this.pausedAt = performance.now();
+        this.input.active = true;
+        show("resume", false);
+        this.refreshPause();
+        show("pause");
+        g.save(true);
+    }
+
+    refreshPause() {
+        const g = this.game;
+        const tod = g.ticks % 24000;
+        const phase = tod < 1000 || tod >= 23000 ? "Sunrise" : tod < 5000 ? "Morning" : tod < 7000 ? "Noon"
+            : tod < 11000 ? "Afternoon" : tod < 13500 ? "Sunset" : tod < 16500 || tod >= 19500 ? "Night" : "Midnight";
+        const cap = (t) => t[0].toUpperCase() + t.slice(1);
+        $("btnDiff").textContent = "Difficulty: " + DIFFICULTY[g.player.difficulty].name;
+        $("btnCheats").textContent = "Cheats: " + (g.meta.cheats ? "On" : "Off");
+        $("btnMode").textContent = "Game Mode: " + (g.creative ? "Creative" : "Survival");
+        $("btnTime").textContent = "Time: " + phase;
+        $("btnWeather").textContent = "Weather: " + cap(g.weather.state);
+        document.querySelectorAll("#pause .cheat").forEach((b) => {
+            b.disabled = !g.meta.cheats;
+            b.title = g.meta.cheats ? "" : "Turn cheats on first";
+        });
+    }
+
+    showCommands() {
+        $("cmdlist").innerHTML = Object.values(COMMANDS).map((c) =>
+            `<div><code>${escapeHtml(c.usage)}</code><span>${escapeHtml(c.desc)}${c.cheat ? "" : " (always allowed)"}</span></div>`).join("");
+        show("cmdhelp");
+    }
+
+    async resumePlay() {
+        const g = this.game;
+        if (!g || this.state !== "playing") {
+            return;
+        }
+        for (const id of ["pause", "settings", "cmdhelp", "help"]) {
+            show(id, false);
+        }
+        g.paused = false;
+        this.input.active = true;
+        this.input.reset();
+        if (this.touchMode) {
+            show("resume", false);
+            return;
+        }
+        const ok = await this.input.lock();
+        if (!ok && !this.ui.isOpen() && this.game === g) {
+            show("resume");
+        } else {
+            show("resume", false);
+        }
+    }
+
+    showDeath(text) {
+        $("deathText").textContent = text;
+        this.input.unlock();
+        show("pause", false);
+        show("death");
+    }
+
+    /* ---------------- settings ---------------- */
+
+    bindSettings() {
+        const s = () => this.settings;
+        const ranges = [
+            ["setRender", "renderDistance", (v) => v + " chunks"],
+            ["setFov", "fov", (v) => v + "\u00b0"],
+            ["setSens", "sensitivity", (v) => Math.round(v * 100) + "%"],
+            ["setBright", "brightness", (v) => (v < 0.2 ? "Moody" : v > 0.8 ? "Bright" : Math.round(v * 100) + "%")],
+            ["setVolume", "volume", (v) => Math.round(v * 100) + "%"],
+            ["setScale", "pixelRatio", (v) => Math.round(v * 100) + "%"]
+        ];
+        const checks = [
+            ["setLeaves", "fancyLeaves"], ["setClouds", "clouds"], ["setBob", "viewBobbing"],
+            ["setInvert", "invertY"], ["setFps", "showFps"]
+        ];
+        this.syncSettingsForm = () => {
+            for (const [id, key, fmt] of ranges) {
+                $(id).value = s()[key];
+                $("val" + id.slice(3)).textContent = fmt(Number(s()[key]));
+            }
+            for (const [id, key] of checks) {
+                $(id).checked = !!s()[key];
+            }
+        };
+        for (const [id, key, fmt] of ranges) {
+            $(id).addEventListener("input", () => {
+                const v = Number($(id).value);
+                s()[key] = v;
+                $("val" + id.slice(3)).textContent = fmt(v);
+                this.applySettings(key);
+            });
+        }
+        for (const [id, key] of checks) {
+            $(id).addEventListener("change", () => {
+                s()[key] = $(id).checked;
+                this.applySettings(key);
+            });
+        }
+        $("btnSettingsDone").onclick = () => {
+            show("settings", false);
+            this.saveSettings();
+        };
+    }
+
+    openSettings() {
+        this.syncSettingsForm();
+        show("settings");
+    }
+
+    applySettings(key) {
+        const st = this.settings;
+        this.renderer.applySettings(st);
+        this.sound.setVolume(st.volume);
+        if (key === "fancyLeaves") {
+            const w = this.game ? this.game.world : this.preview && this.preview.world;
+            if (w) {
+                this.renderer.remeshAll(w);
+            }
+        }
+        this.saveSettings();
+    }
+}
+
+const app = new App();
+window.blocky = app;
+try {
+    app.boot();
+} catch (e) {
+    console.error(e);
+    app.fatal(e);
+}

+ 525 - 0
src/web/Blocky/js/mesher.js

@@ -0,0 +1,525 @@
+/*
+    Blocky - mesher.js
+
+    Builds the geometry of one 16x16x16 chunk section. The section and a one
+    block border (taken from the neighbouring chunks) are copied into padded
+    arrays first, so the inner loop never has to look up a chunk.
+
+    Cube faces get smooth lighting and ambient occlusion: every corner
+    averages the light of the four voxels in front of it and darkens with
+    the solid blocks around it. Everything else (plants, crops, torches,
+    slabs, cactus, farmland, ladders, water) is built from boxes and planes
+    with flat light.
+
+    Vertex layout: position (3), uv (2), layer (1), light (sky, block) (2),
+    colour (tint x shade x occlusion) (3).
+*/
+
+import { B, OPAQUE, SHAPE, BLOCKS, blockFaceLayer, layerOfTile, ITEMS } from "./blocks.js";
+import { WORLD_H } from "./worldgen.js";
+import { FACE_DIR } from "./shapes.js";
+
+const P = 18;
+const P2 = P * P;
+const PAD_SIZE = P * P * P;
+const pi = (x, y, z) => ((y + 1) * P + (z + 1)) * P + (x + 1);
+
+const pBlk = new Uint8Array(PAD_SIZE);
+const pMeta = new Uint8Array(PAD_SIZE);
+const pLight = new Uint8Array(PAD_SIZE);
+const pOpq = new Uint8Array(PAD_SIZE);
+
+const FACE_VERTS = [
+    [[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]],
+    [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]],
+    [[0, 1, 1], [1, 1, 1], [1, 1, 0], [0, 1, 0]],
+    [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]],
+    [[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]],
+    [[1, 0, 0], [0, 0, 0], [0, 1, 0], [1, 1, 0]]
+];
+const FACE_AXIS = [0, 0, 1, 1, 2, 2];
+const FACE_SIGN = [1, -1, 1, -1, 1, -1];
+export const FACE_SHADE = [0.6, 0.6, 1.0, 0.5, 0.8, 0.8];
+const FACE_OFF = [1, -1, P2, -P2, P, -P];
+const AO_LEVEL = [0.5, 0.68, 0.84, 1.0];
+
+const offs = (d) => d[1] * P2 + d[2] * P + d[0];
+
+//AO_TABLE[f][v] = [front, side1, side2, corner] padded offsets
+const AO_TABLE = FACE_VERTS.map((verts, f) => {
+    const axis = FACE_AXIS[f];
+    const n = [0, 0, 0];
+    n[axis] = FACE_SIGN[f];
+    const tAxes = [0, 1, 2].filter((a) => a !== axis);
+    return verts.map((corner) => {
+        const t1 = [0, 0, 0], t2 = [0, 0, 0];
+        t1[tAxes[0]] = corner[tAxes[0]] ? 1 : -1;
+        t2[tAxes[1]] = corner[tAxes[1]] ? 1 : -1;
+        const s1 = [n[0] + t1[0], n[1] + t1[1], n[2] + t1[2]];
+        const s2 = [n[0] + t2[0], n[1] + t2[1], n[2] + t2[2]];
+        const c = [n[0] + t1[0] + t2[0], n[1] + t1[1] + t2[1], n[2] + t1[2] + t2[2]];
+        return [offs(n), offs(s1), offs(s2), offs(c)];
+    });
+});
+
+function faceUV(f, x, y, z) {
+    switch (f) {
+        case 0: return [1 - z, y];
+        case 1: return [z, y];
+        case 2: return [x, 1 - z];
+        case 3: return [x, z];
+        case 4: return [x, y];
+        default: return [1 - x, y];
+    }
+}
+
+/* ---------------- growable vertex buffer ---------------- */
+
+class GeoBuf {
+    constructor(cap = 8192) {
+        this.alloc(cap);
+    }
+    alloc(cap) {
+        const old = this.pos ? this : null;
+        this.cap = cap;
+        const pos = new Float32Array(cap * 3), uv = new Float32Array(cap * 2), layer = new Float32Array(cap);
+        const light = new Float32Array(cap * 2), color = new Float32Array(cap * 3), index = new Uint32Array(cap * 1.5);
+        if (old) {
+            pos.set(old.pos);
+            uv.set(old.uv);
+            layer.set(old.layer);
+            light.set(old.light);
+            color.set(old.color);
+            index.set(old.index);
+        }
+        this.pos = pos; this.uv = uv; this.layer = layer; this.light = light; this.color = color; this.index = index;
+    }
+    reset() {
+        this.vc = 0;
+        this.ic = 0;
+    }
+    vert(x, y, z, u, v, layer, sky, blk, r, g, b) {
+        if (this.vc >= this.cap) {
+            this.alloc(this.cap * 2);
+        }
+        const i = this.vc++;
+        this.pos[i * 3] = x; this.pos[i * 3 + 1] = y; this.pos[i * 3 + 2] = z;
+        this.uv[i * 2] = u; this.uv[i * 2 + 1] = v;
+        this.layer[i] = layer;
+        this.light[i * 2] = sky; this.light[i * 2 + 1] = blk;
+        this.color[i * 3] = r; this.color[i * 3 + 1] = g; this.color[i * 3 + 2] = b;
+        return i;
+    }
+    quad(flip) {
+        const b = this.vc - 4;
+        if (this.ic + 6 > this.index.length) {
+            this.alloc(this.cap * 2);
+        }
+        const ix = this.index;
+        if (flip) {
+            ix[this.ic++] = b + 1; ix[this.ic++] = b + 2; ix[this.ic++] = b + 3;
+            ix[this.ic++] = b + 1; ix[this.ic++] = b + 3; ix[this.ic++] = b;
+        } else {
+            ix[this.ic++] = b; ix[this.ic++] = b + 1; ix[this.ic++] = b + 2;
+            ix[this.ic++] = b; ix[this.ic++] = b + 2; ix[this.ic++] = b + 3;
+        }
+    }
+    //Same four vertices again with reversed winding (double sided planes)
+    backQuad() {
+        const b = this.vc - 4;
+        for (let k = 3; k >= 0; k--) {
+            const s = b + k;
+            this.vert(this.pos[s * 3], this.pos[s * 3 + 1], this.pos[s * 3 + 2], this.uv[s * 2], this.uv[s * 2 + 1],
+                this.layer[s], this.light[s * 2], this.light[s * 2 + 1], this.color[s * 3], this.color[s * 3 + 1], this.color[s * 3 + 2]);
+        }
+        this.quad(false);
+    }
+    take() {
+        if (this.vc === 0) {
+            return null;
+        }
+        return {
+            pos: this.pos.slice(0, this.vc * 3),
+            uv: this.uv.slice(0, this.vc * 2),
+            layer: this.layer.slice(0, this.vc),
+            light: this.light.slice(0, this.vc * 2),
+            color: this.color.slice(0, this.vc * 3),
+            index: this.index.slice(0, this.ic)
+        };
+    }
+}
+
+const solidBuf = new GeoBuf(16384);
+const waterBuf = new GeoBuf(4096);
+
+/* ---------------- padded copy ---------------- */
+
+function fillPadded(world, chunk, sy) {
+    const y0 = sy * 16;
+    const bx = chunk.cx * 16, bz = chunk.cz * 16;
+    for (let pz = -1; pz <= 16; pz++) {
+        for (let px = -1; px <= 16; px++) {
+            const inside = px >= 0 && px < 16 && pz >= 0 && pz < 16;
+            const wx = bx + px, wz = bz + pz;
+            const c = inside ? chunk : world.chunkAt(wx >> 4, wz >> 4);
+            const ok = c !== undefined && c.generated;
+            const colBase = ((wx & 15) << 11) | ((wz & 15) << 7);
+            for (let py = -1; py <= 16; py++) {
+                const y = y0 + py;
+                const p = ((py + 1) * P + (pz + 1)) * P + (px + 1);
+                if (y < 0) {
+                    pBlk[p] = B.BEDROCK; pMeta[p] = 0; pLight[p] = 0; pOpq[p] = 1;
+                    continue;
+                }
+                if (y >= WORLD_H || !ok) {
+                    pBlk[p] = 0; pMeta[p] = 0; pLight[p] = 0xf0; pOpq[p] = 0;
+                    continue;
+                }
+                const i = colBase | y;
+                const id = c.blocks[i];
+                const m = c.meta[i];
+                pBlk[p] = id;
+                pMeta[p] = m;
+                pLight[p] = c.light[i];
+                pOpq[p] = OPAQUE[id] === 1 || (SHAPE[id] === "slab" && m === 2) ? 1 : 0;
+            }
+        }
+    }
+}
+
+/* ---------------- section mesh ---------------- */
+
+export function meshSection(world, chunk, sy, opts) {
+    fillPadded(world, chunk, sy);
+    solidBuf.reset();
+    waterBuf.reset();
+    const fancy = opts.fancyLeaves;
+    const y0 = sy * 16;
+    let any = false;
+    for (let y = 0; y < 16; y++) {
+        for (let z = 0; z < 16; z++) {
+            for (let x = 0; x < 16; x++) {
+                const p = pi(x, y, z);
+                const id = pBlk[p];
+                if (id === 0) {
+                    continue;
+                }
+                any = true;
+                const meta = pMeta[p];
+                const shape = SHAPE[id];
+                const tint = BLOCKS[id].tint;
+                const col = (z * 16 + x) * 6 + (tint === "foliage" ? 3 : 0);
+                const tr = tint ? chunk.tint[col] : 1, tg = tint ? chunk.tint[col + 1] : 1, tb = tint ? chunk.tint[col + 2] : 1;
+                if (shape === "cube" || (shape === "slab" && meta === 2)) {
+                    cubeFaces(solidBuf, p, x, y, z, id, meta, fancy, tr, tg, tb, tint);
+                } else if (shape === "liquid") {
+                    liquidFaces(waterBuf, p, x, y, z, id, meta);
+                } else if (shape === "cross") {
+                    crossPlant(solidBuf, p, x, y, z, id, meta, tr, tg, tb);
+                } else if (shape === "crop") {
+                    cropPlant(solidBuf, p, x, y, z, id, meta);
+                } else if (shape === "torch") {
+                    torch(solidBuf, p, x, y, z, id, meta);
+                } else if (shape === "ladder") {
+                    ladder(solidBuf, p, x, y, z, id, meta);
+                } else if (shape === "slab") {
+                    const y1 = meta === 1 ? 1 : 0.5, ya = meta === 1 ? 0.5 : 0;
+                    boxFaces(solidBuf, p, x, y, z, id, meta, 0, ya, 0, 1, y1, 1, (f, np) => {
+                        const nid = pBlk[np];
+                        if (f === 2 && meta === 0) {
+                            return false;
+                        }
+                        if (f === 3 && meta === 1) {
+                            return false;
+                        }
+                        if (pOpq[np]) {
+                            return true;
+                        }
+                        if (SHAPE[nid] === "slab" && pMeta[np] === meta && f !== 2 && f !== 3) {
+                            return true;
+                        }
+                        if (f === 2 && SHAPE[nid] === "slab" && pMeta[np] === 0) {
+                            return true;
+                        }
+                        if (f === 3 && SHAPE[nid] === "slab" && pMeta[np] === 1) {
+                            return true;
+                        }
+                        return false;
+                    });
+                } else if (shape === "cactus") {
+                    const e = 1 / 16;
+                    boxFaces(solidBuf, p, x, y, z, id, meta, e, 0, e, 1 - e, 1, 1 - e, (f, np) => {
+                        if (f === 2 || f === 3) {
+                            return pOpq[np] === 1 || pBlk[np] === B.CACTUS;
+                        }
+                        return false;
+                    });
+                } else if (shape === "farmland") {
+                    boxFaces(solidBuf, p, x, y, z, id, meta, 0, 0, 0, 1, 15 / 16, 1, (f, np) => f !== 2 && pOpq[np] === 1);
+                }
+            }
+        }
+    }
+    if (!any) {
+        return { solid: null, water: null, empty: true };
+    }
+    return { solid: solidBuf.take(), water: waterBuf.take(), empty: false, y0 };
+}
+
+function cubeFaces(buf, p, x, y, z, id, meta, fancy, tr, tg, tb, tint) {
+    for (let f = 0; f < 6; f++) {
+        const np = p + FACE_OFF[f];
+        if (pOpq[np]) {
+            continue;
+        }
+        const nid = pBlk[np];
+        if (nid === id && (id === B.GLASS || (id === B.LEAVES && !fancy))) {
+            continue;
+        }
+        //Slabs that cover this face completely
+        if (f === 2 && SHAPE[nid] === "slab" && pMeta[np] === 0) {
+            continue;
+        }
+        if (f === 3 && SHAPE[nid] === "slab" && pMeta[np] === 1) {
+            continue;
+        }
+        const layer = blockFaceLayer(id, f, meta);
+        const tinted = tint === "foliage" || (tint === "grass" && f === 2);
+        const shade = FACE_SHADE[f];
+        const r = (tinted ? tr : 1) * shade, g = (tinted ? tg : 1) * shade, b = (tinted ? tb : 1) * shade;
+        const verts = FACE_VERTS[f];
+        const ao = AO_TABLE[f];
+        let a0 = 0, a1 = 0, a2 = 0, a3 = 0;
+        for (let v = 0; v < 4; v++) {
+            const t = ao[v];
+            const pF = p + t[0], pS1 = p + t[1], pS2 = p + t[2], pC = p + t[3];
+            const o1 = pOpq[pS1], o2 = pOpq[pS2], oc = pOpq[pC];
+            let ls = pLight[pF] >> 4, lb = pLight[pF] & 15, n = 1;
+            if (!o1) {
+                ls += pLight[pS1] >> 4; lb += pLight[pS1] & 15; n++;
+            }
+            if (!o2) {
+                ls += pLight[pS2] >> 4; lb += pLight[pS2] & 15; n++;
+            }
+            if (!(o1 && o2) && !oc) {
+                ls += pLight[pC] >> 4; lb += pLight[pC] & 15; n++;
+            }
+            const occ = (o1 && o2) ? 0 : 3 - (o1 + o2 + oc);
+            const k = AO_LEVEL[occ];
+            const vx = verts[v][0], vy = verts[v][1], vz = verts[v][2];
+            const uv = faceUV(f, vx, vy, vz);
+            buf.vert(x + vx, y + vy, z + vz, uv[0], uv[1], layer, ls / (n * 15), lb / (n * 15), r * k, g * k, b * k);
+            const bright = occ * 16 + ls + lb;
+            if (v === 0) {
+                a0 = bright;
+            } else if (v === 1) {
+                a1 = bright;
+            } else if (v === 2) {
+                a2 = bright;
+            } else {
+                a3 = bright;
+            }
+        }
+        buf.quad(a0 + a2 < a1 + a3);
+    }
+}
+
+//Axis aligned box with flat light; cull(f, neighbourPadded) skips faces
+function boxFaces(buf, p, x, y, z, id, meta, x0, y0, z0, x1, y1, z1, cull) {
+    const mins = [x0, y0, z0], maxs = [x1, y1, z1];
+    for (let f = 0; f < 6; f++) {
+        const np = p + FACE_OFF[f];
+        if (cull(f, np)) {
+            continue;
+        }
+        const axis = FACE_AXIS[f];
+        const onEdge = FACE_SIGN[f] > 0 ? maxs[axis] >= 1 : mins[axis] <= 0;
+        const lp = onEdge && !pOpq[np] ? np : p;
+        const ls = (pLight[lp] >> 4) / 15, lb = (pLight[lp] & 15) / 15;
+        const layer = blockFaceLayer(id, f, meta);
+        const s = FACE_SHADE[f];
+        for (const c of FACE_VERTS[f]) {
+            const vx = c[0] ? x1 : x0, vy = c[1] ? y1 : y0, vz = c[2] ? z1 : z0;
+            const uv = faceUV(f, vx, vy, vz);
+            buf.vert(x + vx, y + vy, z + vz, uv[0], uv[1], layer, ls, lb, s, s, s);
+        }
+        buf.quad(false);
+    }
+}
+
+function selfLight(p) {
+    return [(pLight[p] >> 4) / 15, (pLight[p] & 15) / 15];
+}
+
+function crossPlant(buf, p, x, y, z, id, meta, tr, tg, tb) {
+    const [ls, lb] = selfLight(p);
+    const layer = blockFaceLayer(id, 4, meta);
+    const a = 0.15, b = 0.85;
+    const s = 0.92;
+    const planes = [[a, a, b, b], [a, b, b, a]];
+    for (const [xa, za, xb, zb] of planes) {
+        buf.vert(x + xa, y, z + za, 0, 0, layer, ls, lb, tr * s, tg * s, tb * s);
+        buf.vert(x + xb, y, z + zb, 1, 0, layer, ls, lb, tr * s, tg * s, tb * s);
+        buf.vert(x + xb, y + 1, z + zb, 1, 1, layer, ls, lb, tr * s, tg * s, tb * s);
+        buf.vert(x + xa, y + 1, z + za, 0, 1, layer, ls, lb, tr * s, tg * s, tb * s);
+        buf.quad(false);
+        buf.backQuad();
+    }
+}
+
+function cropPlant(buf, p, x, y, z, id, meta) {
+    const [ls, lb] = selfLight(p);
+    const layer = blockFaceLayer(id, 4, meta);
+    const yb = y - 1 / 16, yt = y + 15 / 16;
+    for (const k of [0.25, 0.75]) {
+        //Plane along z at x = k
+        buf.vert(x + k, yb, z, 0, 0, layer, ls, lb, 0.9, 0.9, 0.9);
+        buf.vert(x + k, yb, z + 1, 1, 0, layer, ls, lb, 0.9, 0.9, 0.9);
+        buf.vert(x + k, yt, z + 1, 1, 1, layer, ls, lb, 0.9, 0.9, 0.9);
+        buf.vert(x + k, yt, z, 0, 1, layer, ls, lb, 0.9, 0.9, 0.9);
+        buf.quad(false);
+        buf.backQuad();
+        //Plane along x at z = k
+        buf.vert(x, yb, z + k, 0, 0, layer, ls, lb, 0.8, 0.8, 0.8);
+        buf.vert(x + 1, yb, z + k, 1, 0, layer, ls, lb, 0.8, 0.8, 0.8);
+        buf.vert(x + 1, yt, z + k, 1, 1, layer, ls, lb, 0.8, 0.8, 0.8);
+        buf.vert(x, yt, z + k, 0, 1, layer, ls, lb, 0.8, 0.8, 0.8);
+        buf.quad(false);
+        buf.backQuad();
+    }
+}
+
+function torch(buf, p, x, y, z, id, meta) {
+    const ls = (pLight[p] >> 4) / 15;
+    const layer = blockFaceLayer(id, 4, meta);
+    const x0 = 7 / 16, x1 = 9 / 16, h = 10 / 16;
+    const wall = meta !== 2 && meta !== 3 && FACE_DIR[meta];
+    const tf = (vx, vy, vz) => {
+        if (!wall) {
+            return [x + vx, y + vy, z + vz];
+        }
+        const lean = vy * 0.42 - 0.36;
+        return [x + vx + wall[0] * lean, y + vy + 0.2, z + vz + wall[2] * lean];
+    };
+    for (let f = 0; f < 6; f++) {
+        if (f === 3) {
+            continue;
+        }
+        const s = FACE_SHADE[f] * 0.5 + 0.5;
+        for (const c of FACE_VERTS[f]) {
+            const vx = c[0] ? x1 : x0, vy = c[1] ? h : 0, vz = c[2] ? x1 : x0;
+            const uv = faceUV(f, vx, vy, vz);
+            const q = tf(vx, vy, vz);
+            buf.vert(q[0], q[1], q[2], uv[0], uv[1], layer, ls, 1, s, s, s);
+        }
+        buf.quad(false);
+    }
+}
+
+function ladder(buf, p, x, y, z, id, meta) {
+    const [ls, lb] = selfLight(p);
+    const layer = blockFaceLayer(id, 4, meta);
+    const d = FACE_DIR[meta] || FACE_DIR[4];
+    const e = 1 / 16;
+    let pts;
+    if (d[0] !== 0) {
+        const px = d[0] > 0 ? e : 1 - e;
+        pts = [[px, 0, 0], [px, 0, 1], [px, 1, 1], [px, 1, 0]];
+    } else {
+        const pz = d[2] > 0 ? e : 1 - e;
+        pts = [[0, 0, pz], [1, 0, pz], [1, 1, pz], [0, 1, pz]];
+    }
+    const uvs = [[0, 0], [1, 0], [1, 1], [0, 1]];
+    for (let k = 0; k < 4; k++) {
+        buf.vert(x + pts[k][0], y + pts[k][1], z + pts[k][2], uvs[k][0], uvs[k][1], layer, ls, lb, 0.85, 0.85, 0.85);
+    }
+    buf.quad(false);
+    buf.backQuad();
+}
+
+export function waterHeight(meta, waterAbove) {
+    if (waterAbove) {
+        return 1;
+    }
+    if (meta === 0 || meta === 8) {
+        return 0.875;
+    }
+    return Math.max(0.125, (8 - meta) / 9);
+}
+
+function liquidFaces(buf, p, x, y, z, id, meta) {
+    const above = pBlk[p + P2] === B.WATER;
+    const h = waterHeight(meta, above);
+    const layer = blockFaceLayer(id, 2, meta);
+    for (let f = 0; f < 6; f++) {
+        const np = p + FACE_OFF[f];
+        const nid = pBlk[np];
+        if (nid === B.WATER) {
+            continue;
+        }
+        if (f !== 2 && pOpq[np]) {
+            continue;
+        }
+        if (f === 2 && pOpq[np] && h >= 1) {
+            continue;
+        }
+        const lp = pOpq[np] ? p : np;
+        const ls = (pLight[lp] >> 4) / 15, lb = (pLight[lp] & 15) / 15;
+        const s = FACE_SHADE[f];
+        for (const c of FACE_VERTS[f]) {
+            const vx = c[0], vy = c[1] ? h : 0, vz = c[2];
+            const uv = faceUV(f, vx, vy, vz);
+            buf.vert(x + vx, y + vy, z + vz, uv[0], uv[1], layer, ls, lb, s, s, s);
+        }
+        buf.quad(false);
+        buf.backQuad();
+    }
+}
+
+/* ---------------- item models ---------------- */
+
+//Geometry for held items and dropped items, centred on the origin.
+//Blocks are unit cubes (slabs half height), everything else a flat card.
+export function itemGeometry(id) {
+    const buf = new GeoBuf(64);
+    buf.reset();
+    const it = ITEMS[id];
+    const blockId = it && it.block;
+    const shape = blockId ? SHAPE[blockId] : null;
+    const cubeLike = blockId && (shape === "cube" || shape === "slab" || shape === "cactus" || shape === "farmland");
+    if (cubeLike) {
+        const def = BLOCKS[blockId];
+        const meta = def.orient ? 4 : 0;
+        const top = shape === "slab" ? 0.5 : 1;
+        const inset = shape === "cactus" ? 1 / 16 : 0;
+        const tintC = def.tint === "foliage" ? [0.48, 0.86, 0.32] : def.tint === "grass" ? [0.62, 1.0, 0.43] : null;
+        for (let f = 0; f < 6; f++) {
+            const layer = blockFaceLayer(blockId, f, meta);
+            const s = FACE_SHADE[f];
+            const tinted = tintC && (def.tint === "foliage" || f === 2);
+            const r = (tinted ? tintC[0] : 1) * s, g = (tinted ? tintC[1] : 1) * s, b = (tinted ? tintC[2] : 1) * s;
+            for (const c of FACE_VERTS[f]) {
+                const vx = c[0] ? 1 - inset : inset, vy = c[1] ? top : 0, vz = c[2] ? 1 - inset : inset;
+                const uv = faceUV(f, vx, vy, vz);
+                buf.vert(vx - 0.5, vy - 0.5, vz - 0.5, uv[0], uv[1], layer, 1, 0, r, g, b);
+            }
+            buf.quad(false);
+        }
+        return { geo: buf.take(), cube: true };
+    }
+    let tile;
+    if (it && it.icon && it.icon.flat) {
+        tile = it.icon.flat;
+    } else {
+        tile = "stone";
+    }
+    const layer = layerOfTile(tile);
+    const tint = it && it.icon && it.icon.tint === "grass" ? [0.62, 1.0, 0.43] : [1, 1, 1];
+    buf.vert(-0.5, -0.5, 0, 0, 0, layer, 1, 0, tint[0], tint[1], tint[2]);
+    buf.vert(0.5, -0.5, 0, 1, 0, layer, 1, 0, tint[0], tint[1], tint[2]);
+    buf.vert(0.5, 0.5, 0, 1, 1, layer, 1, 0, tint[0], tint[1], tint[2]);
+    buf.vert(-0.5, 0.5, 0, 0, 1, layer, 1, 0, tint[0], tint[1], tint[2]);
+    buf.quad(false);
+    buf.backQuad();
+    return { geo: buf.take(), cube: false };
+}

+ 168 - 0
src/web/Blocky/js/noise.js

@@ -0,0 +1,168 @@
+/*
+    Blocky - noise.js
+
+    Seeded 2D / 3D simplex noise (after Stefan Gustavson's public domain
+    reference) plus fractal helpers used by the terrain generator.
+*/
+
+import { mulberry32 } from "./util.js";
+
+const GRAD3 = new Float32Array([
+    1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1, 0,
+    1, 0, 1, -1, 0, 1, 1, 0, -1, -1, 0, -1,
+    0, 1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1
+]);
+
+const F2 = 0.5 * (Math.sqrt(3) - 1);
+const G2 = (3 - Math.sqrt(3)) / 6;
+const F3 = 1 / 3;
+const G3 = 1 / 6;
+
+export class Noise {
+    constructor(seed) {
+        const rng = mulberry32(seed);
+        const p = new Uint8Array(256);
+        for (let i = 0; i < 256; i++) {
+            p[i] = i;
+        }
+        for (let i = 255; i > 0; i--) {
+            const j = Math.floor(rng() * (i + 1));
+            const t = p[i];
+            p[i] = p[j];
+            p[j] = t;
+        }
+        this.perm = new Uint8Array(512);
+        this.permMod12 = new Uint8Array(512);
+        for (let i = 0; i < 512; i++) {
+            this.perm[i] = p[i & 255];
+            this.permMod12[i] = this.perm[i] % 12;
+        }
+    }
+
+    noise2(xin, yin) {
+        const perm = this.perm;
+        const pm = this.permMod12;
+        const s = (xin + yin) * F2;
+        const i = Math.floor(xin + s);
+        const j = Math.floor(yin + s);
+        const t = (i + j) * G2;
+        const x0 = xin - (i - t);
+        const y0 = yin - (j - t);
+        let i1, j1;
+        if (x0 > y0) {
+            i1 = 1; j1 = 0;
+        } else {
+            i1 = 0; j1 = 1;
+        }
+        const x1 = x0 - i1 + G2;
+        const y1 = y0 - j1 + G2;
+        const x2 = x0 - 1 + 2 * G2;
+        const y2 = y0 - 1 + 2 * G2;
+        const ii = i & 255;
+        const jj = j & 255;
+        let n0 = 0, n1 = 0, n2 = 0;
+        let t0 = 0.5 - x0 * x0 - y0 * y0;
+        if (t0 > 0) {
+            const g = pm[ii + perm[jj]] * 3;
+            t0 *= t0;
+            n0 = t0 * t0 * (GRAD3[g] * x0 + GRAD3[g + 1] * y0);
+        }
+        let t1 = 0.5 - x1 * x1 - y1 * y1;
+        if (t1 > 0) {
+            const g = pm[ii + i1 + perm[jj + j1]] * 3;
+            t1 *= t1;
+            n1 = t1 * t1 * (GRAD3[g] * x1 + GRAD3[g + 1] * y1);
+        }
+        let t2 = 0.5 - x2 * x2 - y2 * y2;
+        if (t2 > 0) {
+            const g = pm[ii + 1 + perm[jj + 1]] * 3;
+            t2 *= t2;
+            n2 = t2 * t2 * (GRAD3[g] * x2 + GRAD3[g + 1] * y2);
+        }
+        return 70 * (n0 + n1 + n2);
+    }
+
+    noise3(xin, yin, zin) {
+        const perm = this.perm;
+        const pm = this.permMod12;
+        const s = (xin + yin + zin) * F3;
+        const i = Math.floor(xin + s);
+        const j = Math.floor(yin + s);
+        const k = Math.floor(zin + s);
+        const t = (i + j + k) * G3;
+        const x0 = xin - (i - t);
+        const y0 = yin - (j - t);
+        const z0 = zin - (k - t);
+        let i1, j1, k1, i2, j2, k2;
+        if (x0 >= y0) {
+            if (y0 >= z0) {
+                i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0;
+            } else if (x0 >= z0) {
+                i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1;
+            } else {
+                i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1;
+            }
+        } else {
+            if (y0 < z0) {
+                i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1;
+            } else if (x0 < z0) {
+                i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1;
+            } else {
+                i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0;
+            }
+        }
+        const x1 = x0 - i1 + G3, y1 = y0 - j1 + G3, z1 = z0 - k1 + G3;
+        const x2 = x0 - i2 + 2 * G3, y2 = y0 - j2 + 2 * G3, z2 = z0 - k2 + 2 * G3;
+        const x3 = x0 - 1 + 3 * G3, y3 = y0 - 1 + 3 * G3, z3 = z0 - 1 + 3 * G3;
+        const ii = i & 255, jj = j & 255, kk = k & 255;
+        let n = 0;
+        let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
+        if (t0 > 0) {
+            const g = pm[ii + perm[jj + perm[kk]]] * 3;
+            t0 *= t0;
+            n += t0 * t0 * (GRAD3[g] * x0 + GRAD3[g + 1] * y0 + GRAD3[g + 2] * z0);
+        }
+        let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
+        if (t1 > 0) {
+            const g = pm[ii + i1 + perm[jj + j1 + perm[kk + k1]]] * 3;
+            t1 *= t1;
+            n += t1 * t1 * (GRAD3[g] * x1 + GRAD3[g + 1] * y1 + GRAD3[g + 2] * z1);
+        }
+        let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
+        if (t2 > 0) {
+            const g = pm[ii + i2 + perm[jj + j2 + perm[kk + k2]]] * 3;
+            t2 *= t2;
+            n += t2 * t2 * (GRAD3[g] * x2 + GRAD3[g + 1] * y2 + GRAD3[g + 2] * z2);
+        }
+        let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
+        if (t3 > 0) {
+            const g = pm[ii + 1 + perm[jj + 1 + perm[kk + 1]]] * 3;
+            t3 *= t3;
+            n += t3 * t3 * (GRAD3[g] * x3 + GRAD3[g + 1] * y3 + GRAD3[g + 2] * z3);
+        }
+        return 32 * n;
+    }
+
+    //Fractal sum normalised to roughly [-1, 1]
+    fbm2(x, y, octaves, lacunarity = 2, gain = 0.5) {
+        let amp = 1, freq = 1, sum = 0, norm = 0;
+        for (let o = 0; o < octaves; o++) {
+            sum += this.noise2(x * freq, y * freq) * amp;
+            norm += amp;
+            amp *= gain;
+            freq *= lacunarity;
+        }
+        return sum / norm;
+    }
+
+    fbm3(x, y, z, octaves, lacunarity = 2, gain = 0.5) {
+        let amp = 1, freq = 1, sum = 0, norm = 0;
+        for (let o = 0; o < octaves; o++) {
+            sum += this.noise3(x * freq, y * freq, z * freq) * amp;
+            norm += amp;
+            amp *= gain;
+            freq *= lacunarity;
+        }
+        return sum / norm;
+    }
+}

+ 94 - 0
src/web/Blocky/js/physics.js

@@ -0,0 +1,94 @@
+/*
+    Blocky - physics.js
+
+    Axis aligned box movement against the block grid, shared by the player
+    and the item / falling block entities. Unloaded chunks count as solid so
+    nothing falls out of the world while the terrain streams in.
+*/
+
+import { B } from "./blocks.js";
+import { collisionBoxes } from "./shapes.js";
+
+const FULL = [0, 0, 0, 1, 1, 1];
+
+//Collect world boxes overlapping [min, max]
+export function gatherBoxes(world, minX, minY, minZ, maxX, maxY, maxZ, out) {
+    out.length = 0;
+    const x0 = Math.floor(minX), x1 = Math.floor(maxX);
+    const y0 = Math.floor(minY) - 1, y1 = Math.floor(maxY);
+    const z0 = Math.floor(minZ), z1 = Math.floor(maxZ);
+    for (let x = x0; x <= x1; x++) {
+        for (let z = z0; z <= z1; z++) {
+            const loaded = world.isLoaded(x, z);
+            for (let y = y0; y <= y1; y++) {
+                let boxes;
+                if (!loaded && y >= 0) {
+                    boxes = [FULL];
+                } else {
+                    const id = world.getBlock(x, y, z);
+                    if (id === B.AIR) {
+                        continue;
+                    }
+                    boxes = collisionBoxes(id, world.getMeta(x, y, z));
+                }
+                for (const b of boxes) {
+                    out.push(x + b[0], y + b[1], z + b[2], x + b[3], y + b[4], z + b[5]);
+                }
+            }
+        }
+    }
+    return out;
+}
+
+const tmp = [];
+
+//Move box (array [minX,minY,minZ,maxX,maxY,maxZ], mutated) by d along axis.
+//Returns the distance actually travelled.
+export function moveAxis(world, box, axis, d) {
+    if (d === 0) {
+        return 0;
+    }
+    const lo = [box[0], box[1], box[2]], hi = [box[3], box[4], box[5]];
+    if (d < 0) {
+        lo[axis] += d;
+    } else {
+        hi[axis] += d;
+    }
+    const list = gatherBoxes(world, lo[0], lo[1], lo[2], hi[0], hi[1], hi[2], tmp);
+    const a1 = (axis + 1) % 3, a2 = (axis + 2) % 3;
+    const eps = 1e-7;
+    for (let i = 0; i < list.length; i += 6) {
+        //Overlap on the other two axes?
+        if (list[i + a1] >= box[3 + a1] - eps || list[i + 3 + a1] <= box[a1] + eps) {
+            continue;
+        }
+        if (list[i + a2] >= box[3 + a2] - eps || list[i + 3 + a2] <= box[a2] + eps) {
+            continue;
+        }
+        if (d > 0 && list[i + axis] >= box[3 + axis] - eps) {
+            const gap = list[i + axis] - box[3 + axis];
+            if (gap < d) {
+                d = Math.max(0, gap);
+            }
+        } else if (d < 0 && list[i + 3 + axis] <= box[axis] + eps) {
+            const gap = list[i + 3 + axis] - box[axis];
+            if (gap > d) {
+                d = Math.min(0, gap);
+            }
+        }
+    }
+    box[axis] += d;
+    box[3 + axis] += d;
+    return d;
+}
+
+//True when any solid box overlaps the given region
+export function regionBlocked(world, minX, minY, minZ, maxX, maxY, maxZ) {
+    const list = gatherBoxes(world, minX, minY, minZ, maxX, maxY, maxZ, tmp);
+    for (let i = 0; i < list.length; i += 6) {
+        if (list[i] < maxX && list[i + 3] > minX && list[i + 1] < maxY && list[i + 4] > minY && list[i + 2] < maxZ && list[i + 5] > minZ) {
+            return true;
+        }
+    }
+    return false;
+}

+ 462 - 0
src/web/Blocky/js/player.js

@@ -0,0 +1,462 @@
+/*
+    Blocky - player.js
+
+    Player movement and survival stats.
+
+    Movement: walking, sprinting, sneaking (which keeps you from walking off
+    edges), jumping, swimming, ladder climbing and creative flight, with a
+    0.6 block auto-step so slabs can be walked up.
+
+    Survival: 20 health points, 20 food points with a hidden saturation
+    buffer and exhaustion counter. Exhaustion comes from actions and from a
+    slow constant drain whose speed depends on the difficulty. A full food
+    bar regenerates health; an empty one starves you (how far depends on the
+    difficulty again).
+*/
+
+import { B, isOpaqueAt } from "./blocks.js";
+import { moveAxis, regionBlocked, gatherBoxes } from "./physics.js";
+import { waterHeight } from "./mesher.js";
+import { clamp } from "./util.js";
+
+export const DIFFICULTY = [
+    //drain: exhaustion per second while idle; mult: multiplier on action exhaustion
+    { name: "Peaceful", drain: 0, mult: 0, starveFloor: 20 },
+    { name: "Easy", drain: 0.012, mult: 0.75, starveFloor: 10 },
+    { name: "Normal", drain: 0.025, mult: 1.0, starveFloor: 1 },
+    { name: "Hard", drain: 0.045, mult: 1.5, starveFloor: 0 }
+];
+
+const HALF_W = 0.3, HEIGHT = 1.8, EYE = 1.62, STEP = 0.6;
+
+export class Player {
+    constructor(world) {
+        this.world = world;
+        this.x = 0; this.y = 80; this.z = 0;
+        this.vx = 0; this.vy = 0; this.vz = 0;
+        this.yaw = 0; this.pitch = 0;
+        this.onGround = false;
+        this.inWater = false;
+        this.headInWater = false;
+        this.onLadder = false;
+        this.flying = false;
+        this.sneaking = false;
+        this.sprinting = false;
+        this.horizontalHit = false;
+        this.fallDistance = 0;
+        this.walkDist = 0;
+        this.creative = false;
+        this.difficulty = 2;
+        this.health = 20;
+        this.food = 20;
+        this.saturation = 5;
+        this.exhaustion = 0;
+        this.air = 15;
+        this.regenTimer = 0;
+        this.starveTimer = 0;
+        this.drownTimer = 0;
+        this.cactusTimer = 0;
+        this.hurtTime = 0;
+        this.dead = false;
+        this.events = [];
+    }
+
+    get eyeY() {
+        return this.y + EYE - (this.sneaking && !this.flying ? 0.12 : 0);
+    }
+
+    box() {
+        return [this.x - HALF_W, this.y, this.z - HALF_W, this.x + HALF_W, this.y + HEIGHT, this.z + HALF_W];
+    }
+
+    setPos(x, y, z) {
+        this.x = x; this.y = y; this.z = z;
+        this.vx = this.vy = this.vz = 0;
+        this.fallDistance = 0;
+    }
+
+    //Does the voxel at (x, y, z) contain the given world point under water?
+    waterAt(px, py, pz) {
+        const w = this.world;
+        const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);
+        if (w.getBlock(x, y, z) !== B.WATER) {
+            return false;
+        }
+        const h = waterHeight(w.getMeta(x, y, z), w.getBlock(x, y + 1, z) === B.WATER);
+        return py - y < h + 0.02;
+    }
+
+    sense() {
+        const w = this.world;
+        this.inWater = this.waterAt(this.x, this.y + 0.25, this.z) || this.waterAt(this.x, this.y + 0.9, this.z);
+        this.headInWater = this.waterAt(this.x, this.eyeY, this.z);
+        this.onLadder = false;
+        const b = this.box();
+        for (let x = Math.floor(b[0]); x <= Math.floor(b[3]); x++) {
+            for (let z = Math.floor(b[2]); z <= Math.floor(b[5]); z++) {
+                for (let y = Math.floor(b[1]); y <= Math.floor(b[4]); y++) {
+                    if (w.getBlock(x, y, z) === B.LADDER) {
+                        this.onLadder = true;
+                    }
+                }
+            }
+        }
+    }
+
+    //input: forward, strafe (-1..1), jump, sneak, sprint (bools)
+    update(dt, input) {
+        this.sense();
+        const w = this.world;
+        if (!this.creative) {
+            this.flying = false;
+        }
+        this.sneaking = !!input.sneak && !this.flying;
+        const canSprint = this.creative || this.food > 6 || this.difficulty === 0;
+        if (input.sprint && input.forward > 0 && !this.sneaking && canSprint) {
+            this.sprinting = true;
+        }
+        if (input.forward <= 0 || this.sneaking || !canSprint || (this.horizontalHit && !this.flying)) {
+            this.sprinting = false;
+        }
+
+        //Horizontal intent
+        let fx = input.forward, sx = input.strafe;
+        const len = Math.hypot(fx, sx);
+        if (len > 1) {
+            fx /= len;
+            sx /= len;
+        }
+        const sin = Math.sin(this.yaw), cos = Math.cos(this.yaw);
+        const wx = -sin * fx + cos * sx;
+        const wz = -cos * fx - sin * sx;
+        let speed;
+        if (this.flying) {
+            speed = this.sprinting ? 21.6 : 10.9;
+        } else if (this.inWater) {
+            speed = this.sprinting ? 3.2 : 2.2;
+        } else if (this.sneaking) {
+            speed = 1.3;
+        } else {
+            speed = this.sprinting ? 5.6 : 4.3;
+        }
+        let accel;
+        if (this.flying) {
+            accel = 7;
+        } else if (this.inWater) {
+            accel = 6;
+        } else if (this.onGround) {
+            accel = 16;
+        } else {
+            accel = 2.6;
+        }
+        const k = 1 - Math.exp(-accel * dt);
+        this.vx += (wx * speed - this.vx) * k;
+        this.vz += (wz * speed - this.vz) * k;
+
+        //Vertical
+        if (this.flying) {
+            const ty = (input.jump ? 8.5 : 0) - (input.sneak ? 8.5 : 0);
+            this.vy += (ty - this.vy) * (1 - Math.exp(-10 * dt));
+        } else if (this.inWater) {
+            this.vy -= 10 * dt;
+            this.vy *= Math.exp(-2.2 * dt);
+            if (input.jump) {
+                this.vy = Math.min(this.vy + 26 * dt, 3.2);
+                if (this.horizontalHit) {
+                    this.vy = 4.5;
+                }
+            }
+            this.vy = Math.max(this.vy, -3.5);
+        } else {
+            this.vy -= 32 * dt;
+            this.vy = Math.max(this.vy, -60);
+            if (input.jump && this.onGround) {
+                this.vy = 9.0;
+                if (this.sprinting) {
+                    this.vx += -sin * 2.0;
+                    this.vz += -cos * 2.0;
+                    this.exhaust(0.2);
+                } else {
+                    this.exhaust(0.05);
+                }
+            }
+        }
+        if (this.onLadder && !this.flying) {
+            this.fallDistance = 0;
+            this.vy = Math.max(this.vy, -2.4);
+            if (this.horizontalHit || input.jump) {
+                this.vy = 2.4;
+            } else if (this.sneaking) {
+                this.vy = Math.max(this.vy, 0);
+            }
+        }
+
+        //Move and collide
+        const box = this.box();
+        const dx = this.vx * dt, dy = this.vy * dt, dz = this.vz * dt;
+        const wasGround = this.onGround;
+        const my = moveAxis(w, box, 1, dy);
+        this.onGround = dy < 0 && my > dy + 1e-6;
+        if (my !== dy) {
+            this.vy = 0;
+        }
+        let mx = dx, mz = dz;
+        //Sneaking keeps you on the block you stand on
+        if (this.sneaking && this.onGround) {
+            const below = (b, ox, oz) => regionBlocked(w, b[0] + ox, b[1] - 0.6, b[2] + oz, b[3] + ox, b[1] - 0.001, b[5] + oz);
+            if (mx !== 0 && !below(box, mx, 0)) {
+                mx = 0;
+                this.vx = 0;
+            }
+            if (mz !== 0 && !below(box, mx, mz)) {
+                mz = 0;
+                this.vz = 0;
+            }
+        }
+        const start = box.slice();
+        const rx = moveAxis(w, box, 0, mx);
+        const rz = moveAxis(w, box, 2, mz);
+        let hitX = Math.abs(rx - mx) > 1e-6, hitZ = Math.abs(rz - mz) > 1e-6;
+        //Auto step for half blocks
+        if ((hitX || hitZ) && (this.onGround || wasGround) && !this.flying) {
+            const alt = start.slice();
+            const up = moveAxis(w, alt, 1, STEP);
+            const ax = moveAxis(w, alt, 0, mx);
+            const az = moveAxis(w, alt, 2, mz);
+            moveAxis(w, alt, 1, -up);
+            if (ax * ax + az * az > rx * rx + rz * rz + 1e-6) {
+                for (let i = 0; i < 6; i++) {
+                    box[i] = alt[i];
+                }
+                hitX = Math.abs(ax - mx) > 1e-6;
+                hitZ = Math.abs(az - mz) > 1e-6;
+            }
+        }
+        if (hitX) {
+            this.vx = 0;
+        }
+        if (hitZ) {
+            this.vz = 0;
+        }
+        this.horizontalHit = hitX || hitZ;
+        const oldY = this.y;
+        this.x = (box[0] + box[3]) / 2;
+        this.y = box[1];
+        this.z = (box[2] + box[5]) / 2;
+
+        //Distance based effects
+        const moved = Math.hypot(this.x - (start[0] + start[3]) / 2, this.z - (start[2] + start[5]) / 2);
+        if (this.onGround || this.inWater) {
+            this.walkDist += moved;
+        }
+        if (!this.flying) {
+            if (this.inWater) {
+                this.exhaust(0.012 * moved);
+            } else if (this.sprinting) {
+                this.exhaust(0.1 * moved);
+            }
+        }
+
+        //Falling
+        if (this.flying || this.inWater || this.onLadder) {
+            this.fallDistance = 0;
+        } else if (this.y < oldY) {
+            this.fallDistance += oldY - this.y;
+        }
+        if (this.onGround && !wasGround) {
+            if (this.fallDistance > 3 && !this.creative) {
+                const dmg = Math.floor(this.fallDistance - 3);
+                if (dmg > 0) {
+                    this.hurt(dmg, "fall");
+                }
+            }
+            this.events.push({ type: "land", fall: this.fallDistance });
+            this.fallDistance = 0;
+        }
+        if (this.onGround) {
+            this.fallDistance = 0;
+        }
+        if (this.y < -40) {
+            this.hurt(4, "void");
+            this.vy = Math.max(this.vy, 0);
+        }
+    }
+
+    /* ---------------- survival ---------------- */
+
+    exhaust(v) {
+        if (this.creative) {
+            return;
+        }
+        this.exhaustion += v * DIFFICULTY[this.difficulty].mult;
+    }
+
+    hurt(amount, cause) {
+        if (this.creative || this.dead || amount <= 0) {
+            return;
+        }
+        if (this.hurtTime > 0 && cause !== "starve" && cause !== "drown") {
+            return;
+        }
+        this.health = Math.max(0, this.health - amount);
+        this.hurtTime = 0.5;
+        this.exhaust(0.1);
+        this.events.push({ type: "hurt", amount, cause });
+        if (this.health <= 0) {
+            this.dead = true;
+            this.events.push({ type: "death", cause });
+        }
+    }
+
+    kill(cause) {
+        if (this.dead) {
+            return;
+        }
+        this.health = 0;
+        this.dead = true;
+        this.events.push({ type: "death", cause });
+    }
+
+    eat(food) {
+        this.food = Math.min(20, this.food + food.hunger);
+        this.saturation = Math.min(this.food, this.saturation + food.sat);
+    }
+
+    //Called 20 times a second
+    tick() {
+        const dt = 0.05;
+        if (this.hurtTime > 0) {
+            this.hurtTime = Math.max(0, this.hurtTime - dt);
+        }
+        if (this.creative || this.dead) {
+            this.air = 15;
+            return;
+        }
+        const diff = DIFFICULTY[this.difficulty];
+        //Constant drain, scaled by difficulty
+        this.exhaustion += diff.drain * dt;
+        while (this.exhaustion >= 4) {
+            this.exhaustion -= 4;
+            if (this.saturation > 0) {
+                this.saturation = Math.max(0, this.saturation - 1);
+            } else {
+                this.food = Math.max(0, this.food - 1);
+            }
+        }
+        if (this.difficulty === 0) {
+            this.food = 20;
+            this.regenTimer += dt;
+            if (this.regenTimer >= 1 && this.health < 20) {
+                this.regenTimer = 0;
+                this.health = Math.min(20, this.health + 1);
+            }
+        } else if (this.food >= 18 && this.health < 20) {
+            this.regenTimer += dt;
+            if (this.regenTimer >= 4) {
+                this.regenTimer = 0;
+                this.health = Math.min(20, this.health + 1);
+                this.exhaustion += 3;
+            }
+        } else {
+            this.regenTimer = 0;
+        }
+        if (this.food <= 0) {
+            this.starveTimer += dt;
+            if (this.starveTimer >= 4) {
+                this.starveTimer = 0;
+                if (this.health > diff.starveFloor) {
+                    this.hurt(1, "starve");
+                }
+            }
+        } else {
+            this.starveTimer = 0;
+        }
+        //Breath
+        if (this.headInWater) {
+            this.air -= dt;
+            if (this.air <= -1) {
+                this.air = 0;
+                this.hurt(2, "drown");
+            }
+        } else {
+            this.air = Math.min(15, this.air + dt * 5);
+        }
+        //Cactus prickles; a block in your head (fallen sand) suffocates
+        this.cactusTimer = Math.max(0, this.cactusTimer - dt);
+        if (this.cactusTimer === 0 && this.touching(B.CACTUS)) {
+            this.cactusTimer = 0.5;
+            this.hurt(1, "cactus");
+        }
+        const hx = Math.floor(this.x), hy = Math.floor(this.eyeY), hz = Math.floor(this.z);
+        if (this.world.isLoaded(hx, hz) && isOpaqueAt(this.world.getBlock(hx, hy, hz), this.world.getMeta(hx, hy, hz))) {
+            this.suffocateTimer = (this.suffocateTimer || 0) + dt;
+            if (this.suffocateTimer >= 0.5) {
+                this.suffocateTimer = 0;
+                this.hurt(1, "suffocate");
+            }
+        } else {
+            this.suffocateTimer = 0;
+        }
+    }
+
+    touching(id) {
+        const b = this.box();
+        const e = 0.05;
+        for (let x = Math.floor(b[0] - e); x <= Math.floor(b[3] + e); x++) {
+            for (let z = Math.floor(b[2] - e); z <= Math.floor(b[5] + e); z++) {
+                for (let y = Math.floor(b[1] - e); y <= Math.floor(b[4]); y++) {
+                    if (this.world.getBlock(x, y, z) !== id) {
+                        continue;
+                    }
+                    const cx0 = x + 0.0625, cx1 = x + 0.9375, cz0 = z + 0.0625, cz1 = z + 0.9375;
+                    if (b[0] - e < cx1 && b[3] + e > cx0 && b[2] - e < cz1 && b[5] + e > cz0 && b[1] - e < y + 1 && b[4] > y) {
+                        return true;
+                    }
+                }
+            }
+        }
+        return false;
+    }
+
+    //Would a solid block at (x, y, z) intersect the player?
+    intersectsBlock(x, y, z) {
+        const b = this.box();
+        return b[0] < x + 1 && b[3] > x && b[1] < y + 1 && b[4] > y && b[2] < z + 1 && b[5] > z;
+    }
+
+    respawn(spawn) {
+        this.setPos(spawn.x, spawn.y, spawn.z);
+        this.health = 20;
+        this.food = 20;
+        this.saturation = 5;
+        this.exhaustion = 0;
+        this.air = 15;
+        this.dead = false;
+        this.hurtTime = 0;
+    }
+
+    serialize() {
+        return {
+            x: this.x, y: this.y, z: this.z, yaw: this.yaw, pitch: this.pitch,
+            health: this.health, food: this.food, saturation: this.saturation, exhaustion: this.exhaustion,
+            air: this.air, flying: this.flying
+        };
+    }
+
+    load(d) {
+        if (!d) {
+            return;
+        }
+        this.setPos(d.x, d.y, d.z);
+        this.yaw = d.yaw || 0;
+        this.pitch = clamp(d.pitch || 0, -1.55, 1.55);
+        this.health = d.health ?? 20;
+        this.food = d.food ?? 20;
+        this.saturation = d.saturation ?? 5;
+        this.exhaustion = d.exhaustion ?? 0;
+        this.air = d.air ?? 15;
+        this.flying = !!d.flying;
+    }
+}
+
+export { gatherBoxes };

+ 991 - 0
src/web/Blocky/js/render.js

@@ -0,0 +1,991 @@
+/*
+    Blocky - render.js
+
+    Everything that draws: the three.js renderer and scene, the terrain
+    shader (one texture array holds every tile so mipmaps never bleed
+    between tiles), chunk section meshes, the sky (gradient dome, sun, moon,
+    stars, clouds), rain and lightning, the block selection outline and
+    crack overlay, block particles and the first person held item.
+*/
+
+import * as THREE from "three";
+import { meshSection, itemGeometry } from "./mesher.js";
+import { layerOfTile, ITEMS, BLOCKS } from "./blocks.js";
+import { SECTIONS, WORLD_H } from "./world.js";
+import { BIOME } from "./worldgen.js";
+import { clamp, lerp, mulberry32 } from "./util.js";
+
+THREE.ColorManagement.enabled = false;
+
+const TERRAIN_VERT = `
+in float aLayer;
+in vec2 aLight;
+in vec3 aColor;
+out vec2 vUv;
+flat out float vLayer;
+out vec2 vLight;
+out vec3 vColor;
+out float vDist;
+void main() {
+    vUv = uv;
+    vLayer = aLayer;
+    vLight = aLight;
+    vColor = aColor;
+    vec4 mv = modelViewMatrix * vec4(position, 1.0);
+    vDist = length(mv.xyz);
+    gl_Position = projectionMatrix * mv;
+}`;
+
+const TERRAIN_FRAG = `
+precision highp sampler2DArray;
+uniform sampler2DArray uTex;
+uniform float uDaylight;
+uniform vec3 uFogColor;
+uniform float uFogNear;
+uniform float uFogFar;
+uniform float uTime;
+uniform float uWaterLayer;
+uniform float uAlphaTest;
+uniform float uOpacity;
+uniform float uGammaK;
+uniform vec3 uLightOverride;
+in vec2 vUv;
+flat in float vLayer;
+in vec2 vLight;
+in vec3 vColor;
+in float vDist;
+layout(location = 0) out highp vec4 outColor;
+float curve(float l) {
+    return l / (1.0 + uGammaK * (1.0 - l));
+}
+void main() {
+    vec2 uv = vUv;
+    if (abs(vLayer - uWaterLayer) < 0.5) {
+        uv += vec2(sin(uTime * 0.7 + vUv.y * 3.0) * 0.03, uTime * 0.05);
+    }
+    vec4 tex = texture(uTex, vec3(uv.x, 1.0 - uv.y, vLayer));
+    if (tex.a < uAlphaTest) {
+        discard;
+    }
+    vec2 L = uLightOverride.x > 0.5 ? uLightOverride.yz : vLight;
+    float sky = curve(L.x * uDaylight);
+    float blk = curve(L.y);
+    vec3 light = max(vec3(sky), vec3(blk) * vec3(1.0, 0.86, 0.68));
+    light = max(light, vec3(0.03));
+    vec3 col = tex.rgb * vColor * light;
+    float fog = smoothstep(uFogNear, uFogFar, vDist);
+    col = mix(col, uFogColor, fog);
+    outColor = vec4(col, tex.a * uOpacity);
+}`;
+
+const SKY_VERT = `
+varying vec3 vDir;
+void main() {
+    vDir = normalize(position);
+    vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+    gl_Position = p.xyww;
+}`;
+
+const SKY_FRAG = `
+uniform vec3 uTop;
+uniform vec3 uHorizon;
+uniform vec3 uBottom;
+uniform vec3 uSunDir;
+uniform vec3 uGlowColor;
+uniform float uGlow;
+varying vec3 vDir;
+void main() {
+    vec3 d = normalize(vDir);
+    float h = d.y;
+    vec3 col = h > 0.0 ? mix(uHorizon, uTop, smoothstep(0.0, 0.45, h)) : mix(uHorizon, uBottom, smoothstep(0.0, -0.2, h));
+    float g = max(dot(d, uSunDir), 0.0);
+    col += uGlowColor * pow(g, 5.0) * uGlow * (1.0 - smoothstep(0.0, 0.55, abs(h)));
+    gl_FragColor = vec4(col, 1.0);
+}`;
+
+const CLOUD_VERT = `
+varying vec3 vWorld;
+void main() {
+    vec4 w = modelMatrix * vec4(position, 1.0);
+    vWorld = w.xyz;
+    gl_Position = projectionMatrix * viewMatrix * w;
+}`;
+
+const CLOUD_FRAG = `
+uniform sampler2D uMap;
+uniform vec2 uOffset;
+uniform vec3 uColor;
+uniform vec3 uCam;
+uniform float uFade;
+varying vec3 vWorld;
+void main() {
+    vec2 uv = (vWorld.xz + uOffset) / 1024.0;
+    vec4 t = texture2D(uMap, uv);
+    if (t.a < 0.5) discard;
+    float d = length(vWorld.xz - uCam.xz);
+    float a = 0.82 * (1.0 - smoothstep(uFade * 0.55, uFade, d));
+    gl_FragColor = vec4(uColor, a);
+}`;
+
+const CRACK_FRAG = `
+precision highp sampler2DArray;
+uniform sampler2DArray uTex;
+uniform float uLayer;
+in vec2 vUv;
+layout(location = 0) out highp vec4 outColor;
+void main() {
+    vec4 t = texture(uTex, vec3(vUv.x, 1.0 - vUv.y, uLayer));
+    if (t.a < 0.3) discard;
+    outColor = vec4(0.0, 0.0, 0.0, 0.62);
+}`;
+
+const CRACK_VERT = `
+out vec2 vUv;
+void main() {
+    vUv = uv;
+    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+}`;
+
+function makeCanvas(w, h, draw) {
+    const c = document.createElement("canvas");
+    c.width = w;
+    c.height = h;
+    draw(c.getContext("2d"), w, h);
+    return c;
+}
+
+function sunTexture() {
+    return makeCanvas(64, 64, (ctx) => {
+        const g = ctx.createRadialGradient(32, 32, 4, 32, 32, 32);
+        g.addColorStop(0, "rgba(255,250,220,1)");
+        g.addColorStop(0.32, "rgba(255,236,150,1)");
+        g.addColorStop(0.42, "rgba(255,210,110,0.55)");
+        g.addColorStop(1, "rgba(255,180,80,0)");
+        ctx.fillStyle = g;
+        ctx.fillRect(0, 0, 64, 64);
+    });
+}
+
+function moonTexture(phase) {
+    return makeCanvas(64, 64, (ctx) => {
+        ctx.fillStyle = "rgba(235,238,250,1)";
+        ctx.beginPath();
+        ctx.arc(32, 32, 16, 0, Math.PI * 2);
+        ctx.fill();
+        ctx.fillStyle = "rgba(190,196,214,1)";
+        for (const [x, y, r] of [[26, 27, 4], [37, 35, 3], [30, 40, 2.5], [39, 25, 2]]) {
+            ctx.beginPath();
+            ctx.arc(x, y, r, 0, Math.PI * 2);
+            ctx.fill();
+        }
+        //Phase shadow
+        if (phase !== 0) {
+            ctx.globalCompositeOperation = "destination-out";
+            ctx.beginPath();
+            ctx.arc(32 + phase * 30, 32, 17, 0, Math.PI * 2);
+            ctx.fill();
+            ctx.globalCompositeOperation = "source-over";
+        }
+    });
+}
+
+function cloudTexture(seed) {
+    const rng = mulberry32(seed);
+    const N = 64;
+    const grid = (g) => {
+        const a = new Float32Array(g * g);
+        for (let i = 0; i < a.length; i++) {
+            a[i] = rng();
+        }
+        return (x, y) => {
+            const fx = x * g / N, fy = y * g / N;
+            const ix = Math.floor(fx), iy = Math.floor(fy);
+            const tx = fx - ix, ty = fy - iy;
+            const v = (i, j) => a[((iy + j) % g) * g + ((ix + i) % g)];
+            return lerp(lerp(v(0, 0), v(1, 0), tx), lerp(v(0, 1), v(1, 1), tx), ty);
+        };
+    };
+    const g1 = grid(8), g2 = grid(16);
+    return makeCanvas(N, N, (ctx) => {
+        const img = ctx.createImageData(N, N);
+        for (let y = 0; y < N; y++) {
+            for (let x = 0; x < N; x++) {
+                const v = g1(x, y) * 0.7 + g2(x, y) * 0.3;
+                const i = (y * N + x) * 4;
+                img.data[i] = img.data[i + 1] = img.data[i + 2] = 255;
+                img.data[i + 3] = v > 0.56 ? 255 : 0;
+            }
+        }
+        ctx.putImageData(img, 0, 0);
+    });
+}
+
+export class Renderer {
+    constructor(canvas, tex) {
+        this.canvas = canvas;
+        this.tex = tex;
+        this.gl = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: "high-performance" });
+        this.gl.outputColorSpace = THREE.LinearSRGBColorSpace;
+        this.gl.setClearColor(0x7fa9ff);
+        this.gl.autoClear = false;
+        this.scene = new THREE.Scene();
+        this.camera = new THREE.PerspectiveCamera(75, 1, 0.05, 1000);
+        this.camera.rotation.order = "YXZ";
+        this.handScene = new THREE.Scene();
+        this.handCamera = new THREE.PerspectiveCamera(70, 1, 0.01, 10);
+        this.settings = { fancyLeaves: true, clouds: true, renderDistance: 6, brightness: 0.5, pixelRatio: 1 };
+        this.time = 0;
+
+        //Texture array with every tile
+        const at = new THREE.DataArrayTexture(tex.layers, 16, 16, tex.count);
+        at.format = THREE.RGBAFormat;
+        at.type = THREE.UnsignedByteType;
+        at.magFilter = THREE.NearestFilter;
+        at.minFilter = THREE.NearestMipmapLinearFilter;
+        at.wrapS = THREE.RepeatWrapping;
+        at.wrapT = THREE.RepeatWrapping;
+        at.generateMipmaps = true;
+        at.needsUpdate = true;
+        this.arrayTex = at;
+
+        this.shared = {
+            uTex: { value: at },
+            uDaylight: { value: 1 },
+            uFogColor: { value: new THREE.Color(0.75, 0.85, 1) },
+            uFogNear: { value: 60 },
+            uFogFar: { value: 100 },
+            uTime: { value: 0 },
+            uWaterLayer: { value: tex.layerOf.get("water") },
+            uGammaK: { value: 1.2 }
+        };
+        this.solidMat = this.terrainMaterial({ alphaTest: 0.5 });
+        this.waterMat = this.terrainMaterial({ alphaTest: 0.0, transparent: true });
+        this.solidMat.side = THREE.FrontSide;
+
+        this.buildSky();
+        this.buildClouds();
+        this.buildRain();
+        this.buildSelection();
+        this.buildParticles();
+        this.buildHand();
+        this.lightning = [];
+        this.itemGeoCache = new Map();
+        this.world = null;
+        this.resize();
+    }
+
+    terrainMaterial(opts = {}) {
+        const m = new THREE.ShaderMaterial({
+            glslVersion: THREE.GLSL3,
+            vertexShader: TERRAIN_VERT,
+            fragmentShader: TERRAIN_FRAG,
+            uniforms: Object.assign({}, this.shared, {
+                uAlphaTest: { value: opts.alphaTest !== undefined ? opts.alphaTest : 0.5 },
+                uOpacity: { value: opts.opacity !== undefined ? opts.opacity : 1 },
+                uLightOverride: { value: new THREE.Vector3(opts.override ? 1 : 0, 1, 0) }
+            }),
+            transparent: !!opts.transparent,
+            depthWrite: !opts.transparent
+        });
+        return m;
+    }
+
+    resize() {
+        const w = this.canvas.clientWidth || window.innerWidth;
+        const h = this.canvas.clientHeight || window.innerHeight;
+        const pr = Math.min(window.devicePixelRatio || 1, 2) * (this.settings.pixelRatio || 1);
+        this.gl.setPixelRatio(pr);
+        this.gl.setSize(w, h, false);
+        this.camera.aspect = w / Math.max(1, h);
+        this.camera.updateProjectionMatrix();
+        this.handCamera.aspect = this.camera.aspect;
+        this.handCamera.updateProjectionMatrix();
+    }
+
+    applySettings(s) {
+        Object.assign(this.settings, s);
+        this.shared.uGammaK.value = lerp(2.0, 0.25, clamp(this.settings.brightness, 0, 1));
+        this.clouds.visible = this.settings.clouds !== false;
+        this.resize();
+    }
+
+    /* ---------------- sky ---------------- */
+
+    buildSky() {
+        this.skyUniforms = {
+            uTop: { value: new THREE.Color() },
+            uHorizon: { value: new THREE.Color() },
+            uBottom: { value: new THREE.Color() },
+            uSunDir: { value: new THREE.Vector3(1, 0, 0) },
+            uGlowColor: { value: new THREE.Color(1.0, 0.5, 0.25) },
+            uGlow: { value: 0 }
+        };
+        const sky = new THREE.Mesh(new THREE.SphereGeometry(400, 24, 16), new THREE.ShaderMaterial({
+            vertexShader: SKY_VERT,
+            fragmentShader: SKY_FRAG,
+            uniforms: this.skyUniforms,
+            side: THREE.BackSide,
+            depthWrite: false
+        }));
+        sky.renderOrder = -100;
+        sky.frustumCulled = false;
+        this.sky = sky;
+        this.scene.add(sky);
+
+        this.celestial = new THREE.Group();
+        this.scene.add(this.celestial);
+        //Stars
+        const rng = mulberry32(99);
+        const sp = new Float32Array(1500 * 3);
+        for (let i = 0; i < 1500; i++) {
+            const u = rng() * 2 - 1, a = rng() * Math.PI * 2;
+            const r = Math.sqrt(1 - u * u);
+            sp[i * 3] = Math.cos(a) * r * 350;
+            sp[i * 3 + 1] = u * 350;
+            sp[i * 3 + 2] = Math.sin(a) * r * 350;
+        }
+        const sg = new THREE.BufferGeometry();
+        sg.setAttribute("position", new THREE.BufferAttribute(sp, 3));
+        this.starMat = new THREE.PointsMaterial({ color: 0xffffff, size: 1.6, sizeAttenuation: false, transparent: true, depthWrite: false, fog: false });
+        this.stars = new THREE.Points(sg, this.starMat);
+        this.stars.renderOrder = -99;
+        this.stars.frustumCulled = false;
+        this.celestial.add(this.stars);
+
+        const sunMat = new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(sunTexture()), transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, fog: false });
+        this.sun = new THREE.Mesh(new THREE.PlaneGeometry(90, 90), sunMat);
+        this.sun.position.set(330, 0, 0);
+        this.sun.rotation.y = -Math.PI / 2;
+        this.sun.renderOrder = -98;
+        this.celestial.add(this.sun);
+        this.moonPhase = -1;
+        this.moonMat = new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(moonTexture(0)), transparent: true, depthWrite: false, fog: false });
+        this.moon = new THREE.Mesh(new THREE.PlaneGeometry(70, 70), this.moonMat);
+        this.moon.position.set(-330, 0, 0);
+        this.moon.rotation.y = Math.PI / 2;
+        this.moon.renderOrder = -98;
+        this.celestial.add(this.moon);
+        for (const o of [this.sun, this.moon]) {
+            o.frustumCulled = false;
+        }
+    }
+
+    buildClouds() {
+        const t = new THREE.CanvasTexture(cloudTexture(1234));
+        t.magFilter = THREE.NearestFilter;
+        t.minFilter = THREE.NearestFilter;
+        t.wrapS = t.wrapT = THREE.RepeatWrapping;
+        t.generateMipmaps = false;
+        this.cloudUniforms = {
+            uMap: { value: t },
+            uOffset: { value: new THREE.Vector2() },
+            uColor: { value: new THREE.Color(1, 1, 1) },
+            uCam: { value: new THREE.Vector3() },
+            uFade: { value: 300 }
+        };
+        const m = new THREE.ShaderMaterial({
+            vertexShader: CLOUD_VERT,
+            fragmentShader: CLOUD_FRAG,
+            uniforms: this.cloudUniforms,
+            transparent: true,
+            depthWrite: false,
+            side: THREE.DoubleSide
+        });
+        const g = new THREE.PlaneGeometry(1200, 1200);
+        g.rotateX(-Math.PI / 2);
+        this.clouds = new THREE.Mesh(g, m);
+        this.clouds.renderOrder = 10;
+        this.clouds.frustumCulled = false;
+        this.scene.add(this.clouds);
+    }
+
+    /* ---------------- rain & lightning ---------------- */
+
+    buildRain() {
+        this.rainCount = 1600;
+        this.rainPos = new Float32Array(this.rainCount * 6);
+        this.rainDrops = new Float32Array(this.rainCount * 4); //x, y, z, speed
+        this.rainDrops.fill(-9999);
+        const g = new THREE.BufferGeometry();
+        g.setAttribute("position", new THREE.BufferAttribute(this.rainPos, 3));
+        this.rainMat = new THREE.LineBasicMaterial({ color: 0xa8b8d8, transparent: true, opacity: 0.5, depthWrite: false, fog: false });
+        this.rain = new THREE.LineSegments(g, this.rainMat);
+        this.rain.frustumCulled = false;
+        this.rain.renderOrder = 20;
+        this.rain.visible = false;
+        this.scene.add(this.rain);
+        this.rainExposure = 0;
+    }
+
+    //Moves rain streaks; returns how exposed the camera is (0-1) for audio
+    updateRain(dt, strength, cam, world) {
+        if (strength <= 0.01 || !world) {
+            this.rain.visible = false;
+            this.rainExposure = 0;
+            return 0;
+        }
+        this.rain.visible = true;
+        this.rainMat.opacity = 0.5 * strength;
+        const R = 14;
+        const active = Math.floor(this.rainCount * strength);
+        let exposed = 0, sampled = 0;
+        const d = this.rainDrops, p = this.rainPos;
+        const rng = Math.random;
+        for (let i = 0; i < this.rainCount; i++) {
+            const k = i * 4;
+            if (i >= active) {
+                p.fill(0, i * 6, i * 6 + 6);
+                p[i * 6 + 1] = p[i * 6 + 4] = -9999;
+                continue;
+            }
+            d[k + 1] -= d[k + 3] * dt;
+            const x = d[k], z = d[k + 2];
+            const dx = x - cam.x, dz = z - cam.z;
+            let respawn = d[k + 1] < -100 || dx * dx + dz * dz > R * R * 1.3;
+            if (!respawn) {
+                const top = world.rainTop(Math.floor(x), Math.floor(z));
+                if (d[k + 1] < top || d[k + 1] < cam.y - 12) {
+                    respawn = true;
+                }
+            }
+            if (respawn) {
+                const a = rng() * Math.PI * 2, r = Math.sqrt(rng()) * R;
+                const nx = cam.x + Math.cos(a) * r, nz = cam.z + Math.sin(a) * r;
+                const fx = Math.floor(nx), fz = Math.floor(nz);
+                const top = world.rainTop(fx, fz);
+                const biome = world.biomeAt(fx, fz);
+                sampled++;
+                if (top < 0 || biome === BIOME.DESERT || top > cam.y + 14) {
+                    d[k] = nx; d[k + 1] = -9999; d[k + 2] = nz; d[k + 3] = 0;
+                } else {
+                    if (r < 5 && top <= cam.y + 2) {
+                        exposed++;
+                    }
+                    d[k] = nx; d[k + 2] = nz;
+                    d[k + 1] = Math.max(top, cam.y) + 4 + rng() * 14;
+                    d[k + 3] = 14 + rng() * 6;
+                }
+            }
+            const y = d[k + 1];
+            p[i * 6] = d[k]; p[i * 6 + 1] = y; p[i * 6 + 2] = d[k + 2];
+            p[i * 6 + 3] = d[k] + 0.04; p[i * 6 + 4] = y + 0.7; p[i * 6 + 5] = d[k + 2];
+        }
+        this.rain.geometry.attributes.position.needsUpdate = true;
+        if (sampled > 0) {
+            this.rainExposure = lerp(this.rainExposure, Math.min(1, exposed / Math.max(1, sampled * 0.12)), 0.1);
+        }
+        return this.rainExposure;
+    }
+
+    strikeLightning(x, y, z) {
+        const g = new THREE.Group();
+        const mat = new THREE.MeshBasicMaterial({ color: 0xe6ecff, transparent: true, opacity: 0.95, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide, fog: false });
+        const rng = Math.random;
+        let px = x, pz = z;
+        const top = y + 120;
+        let py = top;
+        const segs = [];
+        while (py > y) {
+            const ny = Math.max(y, py - (4 + rng() * 6));
+            const nx = px + (rng() - 0.5) * 4, nz = pz + (rng() - 0.5) * 4;
+            segs.push([px, py, pz, ny < y + 1 ? x : nx, ny, ny < y + 1 ? z : nz]);
+            px = ny < y + 1 ? x : nx;
+            pz = ny < y + 1 ? z : nz;
+            py = ny;
+        }
+        const w = 0.32;
+        for (const [ax, ay, az, bx, by, bz] of segs) {
+            for (const rot of [0, Math.PI / 2]) {
+                const geo = new THREE.BufferGeometry();
+                const ox = Math.cos(rot) * w, oz = Math.sin(rot) * w;
+                geo.setAttribute("position", new THREE.BufferAttribute(new Float32Array([
+                    ax - ox, ay, az - oz, ax + ox, ay, az + oz, bx + ox, by, bz + oz,
+                    ax - ox, ay, az - oz, bx + ox, by, bz + oz, bx - ox, by, bz - oz
+                ]), 3));
+                g.add(new THREE.Mesh(geo, mat));
+            }
+        }
+        g.renderOrder = 30;
+        this.scene.add(g);
+        this.lightning.push({ group: g, mat, life: 0.45 });
+    }
+
+    updateLightning(dt) {
+        for (let i = this.lightning.length - 1; i >= 0; i--) {
+            const l = this.lightning[i];
+            l.life -= dt;
+            l.mat.opacity = l.life > 0 ? (Math.random() < 0.3 ? 0.3 : 0.95) : 0;
+            if (l.life <= 0) {
+                this.scene.remove(l.group);
+                l.group.traverse((o) => o.geometry && o.geometry.dispose());
+                l.mat.dispose();
+                this.lightning.splice(i, 1);
+            }
+        }
+    }
+
+    /* ---------------- selection & cracks ---------------- */
+
+    buildSelection() {
+        const edges = new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1));
+        this.selection = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({ color: 0x000000, transparent: true, opacity: 0.55 }));
+        this.selection.visible = false;
+        this.selection.renderOrder = 15;
+        this.scene.add(this.selection);
+        this.crackUniforms = { uTex: { value: this.arrayTex }, uLayer: { value: 0 } };
+        this.crack = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.ShaderMaterial({
+            glslVersion: THREE.GLSL3,
+            vertexShader: CRACK_VERT,
+            fragmentShader: CRACK_FRAG,
+            uniforms: this.crackUniforms,
+            transparent: true,
+            depthWrite: false,
+            polygonOffset: true,
+            polygonOffsetFactor: -1,
+            polygonOffsetUnits: -4
+        }));
+        this.crack.visible = false;
+        this.crack.renderOrder = 14;
+        this.scene.add(this.crack);
+    }
+
+    setSelection(hit) {
+        if (!hit) {
+            this.selection.visible = false;
+            this.crack.visible = false;
+            return;
+        }
+        const b = hit.box;
+        const e = 0.003;
+        this.selection.visible = true;
+        this.selection.position.set(hit.x + (b[0] + b[3]) / 2, hit.y + (b[1] + b[4]) / 2, hit.z + (b[2] + b[5]) / 2);
+        this.selection.scale.set(b[3] - b[0] + e * 2, b[4] - b[1] + e * 2, b[5] - b[2] + e * 2);
+    }
+
+    setCrack(hit, progress) {
+        if (!hit || progress <= 0) {
+            this.crack.visible = false;
+            return;
+        }
+        const b = hit.box;
+        const stage = Math.min(9, Math.floor(progress * 10));
+        this.crackUniforms.uLayer.value = this.tex.layerOf.get("destroy_" + stage);
+        this.crack.visible = true;
+        this.crack.position.copy(this.selection.position);
+        this.crack.scale.set(b[3] - b[0] + 0.004, b[4] - b[1] + 0.004, b[5] - b[2] + 0.004);
+    }
+
+    /* ---------------- particles ---------------- */
+
+    buildParticles() {
+        this.pMax = 800;
+        this.pPos = new Float32Array(this.pMax * 3);
+        this.pCol = new Float32Array(this.pMax * 3);
+        this.pVel = new Float32Array(this.pMax * 3);
+        this.pLife = new Float32Array(this.pMax);
+        this.pCount = 0;
+        const g = new THREE.BufferGeometry();
+        g.setAttribute("position", new THREE.BufferAttribute(this.pPos, 3));
+        g.setAttribute("color", new THREE.BufferAttribute(this.pCol, 3));
+        this.particles = new THREE.Points(g, new THREE.PointsMaterial({ size: 0.1, vertexColors: true, sizeAttenuation: true }));
+        this.particles.frustumCulled = false;
+        this.scene.add(this.particles);
+    }
+
+    spawnParticles(x, y, z, color, count, spread = 0.45, speed = 3, brightness = 1) {
+        for (let i = 0; i < count; i++) {
+            if (this.pCount >= this.pMax) {
+                return;
+            }
+            const k = this.pCount++;
+            this.pPos[k * 3] = x + (Math.random() - 0.5) * spread * 2;
+            this.pPos[k * 3 + 1] = y + (Math.random() - 0.5) * spread * 2;
+            this.pPos[k * 3 + 2] = z + (Math.random() - 0.5) * spread * 2;
+            this.pVel[k * 3] = (Math.random() - 0.5) * speed;
+            this.pVel[k * 3 + 1] = Math.random() * speed;
+            this.pVel[k * 3 + 2] = (Math.random() - 0.5) * speed;
+            const v = (0.75 + Math.random() * 0.35) * brightness / 255;
+            this.pCol[k * 3] = color[0] * v;
+            this.pCol[k * 3 + 1] = color[1] * v;
+            this.pCol[k * 3 + 2] = color[2] * v;
+            this.pLife[k] = 0.5 + Math.random() * 0.6;
+        }
+    }
+
+    updateParticles(dt, world) {
+        let n = this.pCount;
+        for (let i = 0; i < n; i++) {
+            this.pLife[i] -= dt;
+            if (this.pLife[i] <= 0) {
+                n--;
+                this.pLife[i] = this.pLife[n];
+                for (let a = 0; a < 3; a++) {
+                    this.pPos[i * 3 + a] = this.pPos[n * 3 + a];
+                    this.pVel[i * 3 + a] = this.pVel[n * 3 + a];
+                    this.pCol[i * 3 + a] = this.pCol[n * 3 + a];
+                }
+                i--;
+                continue;
+            }
+            this.pVel[i * 3 + 1] -= 16 * dt;
+            const nx = this.pPos[i * 3] + this.pVel[i * 3] * dt;
+            const ny = this.pPos[i * 3 + 1] + this.pVel[i * 3 + 1] * dt;
+            const nz = this.pPos[i * 3 + 2] + this.pVel[i * 3 + 2] * dt;
+            if (world && BLOCKS[world.getBlock(Math.floor(nx), Math.floor(ny), Math.floor(nz))].solid) {
+                this.pVel[i * 3] *= 0.3;
+                this.pVel[i * 3 + 1] = 0;
+                this.pVel[i * 3 + 2] *= 0.3;
+            } else {
+                this.pPos[i * 3] = nx;
+                this.pPos[i * 3 + 1] = ny;
+                this.pPos[i * 3 + 2] = nz;
+            }
+        }
+        this.pCount = n;
+        const g = this.particles.geometry;
+        g.setDrawRange(0, n);
+        g.attributes.position.needsUpdate = true;
+        g.attributes.color.needsUpdate = true;
+    }
+
+    /* ---------------- item meshes ---------------- */
+
+    itemGeometry(id) {
+        let entry = this.itemGeoCache.get(id);
+        if (!entry) {
+            const { geo, cube } = itemGeometry(id);
+            entry = { geometry: this.toGeometry(geo), cube };
+            entry.geometry.computeBoundingSphere();
+            this.itemGeoCache.set(id, entry);
+        }
+        return entry;
+    }
+
+    //A mesh for a dropped item / falling block with its own light uniform
+    makeItemMesh(id) {
+        const entry = this.itemGeometry(id);
+        const mat = this.terrainMaterial({ alphaTest: 0.3, override: true });
+        const mesh = new THREE.Mesh(entry.geometry, mat);
+        mesh.userData.cube = entry.cube;
+        return mesh;
+    }
+
+    setMeshLight(mesh, sky, blk) {
+        const v = mesh.material.uniforms.uLightOverride.value;
+        v.set(1, sky, blk);
+    }
+
+    disposeItemMesh(mesh) {
+        mesh.material.dispose();
+        if (mesh.parent) {
+            mesh.parent.remove(mesh);
+        }
+    }
+
+    /* ---------------- held item ---------------- */
+
+    buildHand() {
+        this.handGroup = new THREE.Group();
+        this.handScene.add(this.handGroup);
+        this.handMat = this.terrainMaterial({ alphaTest: 0.3, override: true });
+        this.handMat.depthTest = true;
+        this.handMesh = null;
+        this.handId = -1;
+        //Bare arm: a skin coloured box with baked face shading and a sleeve
+        const armGeo = new THREE.BoxGeometry(0.17, 0.17, 0.66);
+        const normals = armGeo.attributes.normal, positions = armGeo.attributes.position;
+        const colors = new Float32Array(normals.count * 3);
+        for (let i = 0; i < normals.count; i++) {
+            const ny = normals.getY(i), nx = normals.getX(i);
+            const shade = ny > 0.5 ? 1 : ny < -0.5 ? 0.55 : nx !== 0 ? 0.72 : 0.86;
+            const sleeve = positions.getZ(i) > 0.12;
+            const base = sleeve ? [0.27, 0.42, 0.62] : [0.86, 0.64, 0.49];
+            colors[i * 3] = base[0] * shade;
+            colors[i * 3 + 1] = base[1] * shade;
+            colors[i * 3 + 2] = base[2] * shade;
+        }
+        armGeo.setAttribute("color", new THREE.BufferAttribute(colors, 3));
+        this.armMat = new THREE.MeshBasicMaterial({ vertexColors: true });
+        this.arm = new THREE.Mesh(armGeo, this.armMat);
+        this.handGroup.add(this.arm);
+    }
+
+    setHeldItem(id) {
+        if (id === this.handId) {
+            return;
+        }
+        this.handId = id;
+        if (this.handMesh) {
+            this.handGroup.remove(this.handMesh);
+            this.handMesh = null;
+        }
+        this.arm.visible = !id;
+        if (!id) {
+            return;
+        }
+        const entry = this.itemGeometry(id);
+        this.handMesh = new THREE.Mesh(entry.geometry, this.handMat);
+        this.handMesh.userData.cube = entry.cube;
+        this.handGroup.add(this.handMesh);
+    }
+
+    //pose: { swing 0-1, equip 0-1, bobX, bobY, eat 0-1, sky, blk }
+    updateHand(pose) {
+        this.handMat.uniforms.uLightOverride.value.set(1, pose.sky, pose.blk);
+        const c = Math.max(0.2, Math.max(pose.sky * this.shared.uDaylight.value, pose.blk));
+        this.armMat.color.setRGB(c, c, c);
+        const s = Math.sin(pose.swing * Math.PI);
+        const s2 = Math.sin(Math.sqrt(pose.swing) * Math.PI);
+        const g = this.handGroup;
+        g.position.set(0.52 + pose.bobX - s2 * 0.2, -0.5 + pose.bobY - pose.equip * 0.6 + s * 0.12 - pose.eat * 0.05 * Math.abs(Math.sin(pose.eatT * 18)), -0.9 - s * 0.15);
+        g.rotation.set(-s * 0.9 + pose.eat * 0.5, -s2 * 0.4 + pose.eat * 0.6, s * 0.2);
+        if (this.handMesh) {
+            if (this.handMesh.userData.cube) {
+                this.handMesh.scale.setScalar(0.32);
+                this.handMesh.position.set(0.06, 0.0, -0.02);
+                this.handMesh.rotation.set(0.1, Math.PI / 4, 0);
+            } else {
+                //A flat item held upright, turned a little toward the view
+                this.handMesh.scale.setScalar(0.42);
+                this.handMesh.position.set(0.02, 0.1, -0.05);
+                this.handMesh.rotation.set(0.1, -0.75, 0.12);
+            }
+        }
+        this.arm.position.set(0.12, -0.14, 0.24);
+        this.arm.rotation.set(0.55, 0.18, 0.1);
+    }
+
+    /* ---------------- chunk meshes ---------------- */
+
+    toGeometry(d) {
+        const g = new THREE.BufferGeometry();
+        g.setAttribute("position", new THREE.BufferAttribute(d.pos, 3));
+        g.setAttribute("uv", new THREE.BufferAttribute(d.uv, 2));
+        g.setAttribute("aLayer", new THREE.BufferAttribute(d.layer, 1));
+        g.setAttribute("aLight", new THREE.BufferAttribute(d.light, 2));
+        g.setAttribute("aColor", new THREE.BufferAttribute(d.color, 3));
+        g.setIndex(new THREE.BufferAttribute(d.index, 1));
+        return g;
+    }
+
+    attachWorld(world) {
+        this.detachWorld();
+        this.world = world;
+    }
+
+    detachWorld() {
+        if (!this.world) {
+            return;
+        }
+        for (const c of this.world.chunks.values()) {
+            this.disposeChunk(c);
+        }
+        this.world = null;
+        this.pCount = 0;
+        this.setSelection(null);
+        for (const l of this.lightning) {
+            this.scene.remove(l.group);
+        }
+        this.lightning = [];
+    }
+
+    disposeChunk(c) {
+        if (!c.meshes) {
+            return;
+        }
+        for (const s of c.meshes) {
+            if (!s) {
+                continue;
+            }
+            for (const m of [s.solid, s.water]) {
+                if (m) {
+                    this.scene.remove(m);
+                    m.geometry.dispose();
+                }
+            }
+        }
+        c.meshes = null;
+    }
+
+    setSectionMesh(c, sy, data) {
+        if (!c.meshes) {
+            c.meshes = new Array(SECTIONS).fill(null);
+        }
+        const old = c.meshes[sy];
+        if (old) {
+            for (const m of [old.solid, old.water]) {
+                if (m) {
+                    this.scene.remove(m);
+                    m.geometry.dispose();
+                }
+            }
+        }
+        const entry = { solid: null, water: null };
+        const sphere = new THREE.Sphere(new THREE.Vector3(8, 8, 8), 14);
+        if (data && data.solid) {
+            const g = this.toGeometry(data.solid);
+            g.boundingSphere = sphere;
+            const m = new THREE.Mesh(g, this.solidMat);
+            m.position.set(c.cx * 16, sy * 16, c.cz * 16);
+            m.matrixAutoUpdate = false;
+            m.updateMatrix();
+            this.scene.add(m);
+            entry.solid = m;
+        }
+        if (data && data.water) {
+            const g = this.toGeometry(data.water);
+            g.boundingSphere = sphere.clone();
+            const m = new THREE.Mesh(g, this.waterMat);
+            m.position.set(c.cx * 16, sy * 16, c.cz * 16);
+            m.matrixAutoUpdate = false;
+            m.updateMatrix();
+            m.renderOrder = 1;
+            this.scene.add(m);
+            entry.water = m;
+        }
+        c.meshes[sy] = entry;
+    }
+
+    //Rebuild dirty sections near the camera; returns sections still waiting
+    updateMeshes(world, camX, camZ, radius, deadline) {
+        const pcx = Math.floor(camX / 16), pcz = Math.floor(camZ / 16);
+        const list = [];
+        for (const c of world.chunks.values()) {
+            const dx = c.cx - pcx, dz = c.cz - pcz;
+            if (Math.abs(dx) > radius || Math.abs(dz) > radius) {
+                if (c.meshes && (Math.abs(dx) > radius + 1 || Math.abs(dz) > radius + 1)) {
+                    this.disposeChunk(c);
+                    c.dirty.fill(1);
+                }
+                continue;
+            }
+            let dirty = false;
+            for (let s = 0; s < SECTIONS; s++) {
+                if (c.dirty[s]) {
+                    dirty = true;
+                    break;
+                }
+            }
+            if (dirty && world.isMeshable(c)) {
+                list.push([dx * dx + dz * dz, c]);
+            }
+        }
+        list.sort((a, b) => a[0] - b[0]);
+        const opts = { fancyLeaves: this.settings.fancyLeaves };
+        let pending = 0;
+        for (const [, c] of list) {
+            for (let s = 0; s < SECTIONS; s++) {
+                if (!c.dirty[s]) {
+                    continue;
+                }
+                if (performance.now() > deadline) {
+                    pending++;
+                    continue;
+                }
+                c.dirty[s] = 0;
+                const data = meshSection(world, c, s, opts);
+                this.setSectionMesh(c, s, data.empty ? null : data);
+            }
+        }
+        return pending;
+    }
+
+    remeshAll(world) {
+        for (const c of world.chunks.values()) {
+            c.dirty.fill(1);
+        }
+    }
+
+    /* ---------------- environment & frame ---------------- */
+
+    //env: time (0-24000, 0 = sunrise), rain, thunder, flash, underwater,
+    //renderDistance, day (number of days for the moon phase)
+    applyEnvironment(env) {
+        const ang = (env.time / 24000) * Math.PI * 2;
+        const sunH = Math.sin(ang);
+        const day = clamp(0.5 + sunH * 2.2, 0, 1);
+        const rain = env.rain, thunder = env.thunder;
+        const daylightBase = lerp(0.16, 1.0, day) * (1 - rain * 0.22) * (1 - thunder * 0.3);
+        const daylight = Math.min(1.2, daylightBase + env.flash * 0.9);
+        this.shared.uDaylight.value = daylight;
+
+        const dayTop = [0.42, 0.62, 1.0], dayHor = [0.74, 0.85, 1.0];
+        const nightTop = [0.008, 0.01, 0.035], nightHor = [0.03, 0.04, 0.09];
+        const top = [0, 1, 2].map((i) => lerp(nightTop[i], dayTop[i], day));
+        const hor = [0, 1, 2].map((i) => lerp(nightHor[i], dayHor[i], day));
+        const grey = (c, amt, dark) => {
+            const g = (c[0] + c[1] + c[2]) / 3;
+            return c.map((v) => lerp(v, g * dark, amt));
+        };
+        let t = grey(top, rain * 0.8, 0.75), h = grey(hor, rain * 0.8, 0.8);
+        if (thunder > 0) {
+            t = t.map((v) => v * (1 - thunder * 0.4));
+            h = h.map((v) => v * (1 - thunder * 0.4));
+        }
+        if (env.flash > 0) {
+            t = t.map((v) => Math.min(1, v + env.flash * 0.5));
+            h = h.map((v) => Math.min(1, v + env.flash * 0.5));
+        }
+        this.skyUniforms.uTop.value.setRGB(t[0], t[1], t[2]);
+        this.skyUniforms.uHorizon.value.setRGB(h[0], h[1], h[2]);
+        this.skyUniforms.uBottom.value.setRGB(h[0] * 0.92, h[1] * 0.92, h[2] * 0.95);
+        const sunset = clamp(1 - Math.abs(sunH) * 3.2, 0, 1) * (1 - rain);
+        this.skyUniforms.uGlow.value = sunset * 0.9;
+        this.skyUniforms.uSunDir.value.set(Math.cos(ang), Math.sin(ang), 0);
+        this.celestial.rotation.z = ang;
+        this.sun.material.opacity = 1 - rain;
+        this.moonMat.opacity = 1 - rain * 0.9;
+        this.starMat.opacity = clamp(1 - day * 1.6, 0, 1) * (1 - rain);
+        const phase = ((env.day || 0) % 8);
+        if (phase !== this.moonPhase) {
+            this.moonPhase = phase;
+            //0 full, 4 new; the shadow disc slides across the moon
+            const shift = [0, -1.05, -0.7, -0.35, 0.001, 0.35, 0.7, 1.05][phase];
+            this.moonMat.map.dispose();
+            this.moonMat.map = new THREE.CanvasTexture(moonTexture(shift));
+            this.moonMat.needsUpdate = true;
+        }
+
+        //Fog matches the horizon (with a touch of sunset)
+        let fog = h.slice();
+        const look = new THREE.Vector3();
+        this.camera.getWorldDirection(look);
+        const towardSun = Math.max(0, look.x * Math.cos(ang)) * sunset;
+        fog = [lerp(fog[0], 1.0, towardSun * 0.45), lerp(fog[1], 0.55, towardSun * 0.3), lerp(fog[2], 0.3, towardSun * 0.3)];
+        const far = Math.max(24, env.renderDistance * 16 - 6);
+        if (env.underwater) {
+            const k = Math.max(0.15, daylight);
+            this.shared.uFogColor.value.setRGB(0.06 * k, 0.17 * k, 0.4 * k);
+            this.shared.uFogNear.value = 1;
+            this.shared.uFogFar.value = 24;
+        } else {
+            this.shared.uFogColor.value.setRGB(fog[0], fog[1], fog[2]);
+            this.shared.uFogFar.value = far * (1 - rain * 0.25);
+            this.shared.uFogNear.value = this.shared.uFogFar.value * (0.55 - rain * 0.25);
+        }
+        this.gl.setClearColor(new THREE.Color(h[0], h[1], h[2]));
+
+        //Clouds
+        const cc = lerp(0.12, 1.0, day) * (1 - rain * 0.35);
+        this.cloudUniforms.uColor.value.setRGB(cc, cc, cc * (1.02 + (1 - day) * 0.1));
+        this.cloudUniforms.uFade.value = Math.max(160, far * 2.2);
+        return { daylight, day };
+    }
+
+    render(dt, showHand) {
+        this.time += dt;
+        this.shared.uTime.value = this.time;
+        const cam = this.camera;
+        this.sky.position.copy(cam.position);
+        this.celestial.position.copy(cam.position);
+        this.clouds.position.set(cam.position.x, 112, cam.position.z);
+        this.cloudUniforms.uOffset.value.set(this.time * 1.2, 0);
+        this.cloudUniforms.uCam.value.copy(cam.position);
+        this.gl.clear();
+        this.gl.render(this.scene, cam);
+        if (showHand) {
+            this.gl.clearDepth();
+            this.gl.render(this.handScene, this.handCamera);
+        }
+    }
+}

+ 85 - 0
src/web/Blocky/js/shapes.js

@@ -0,0 +1,85 @@
+/*
+    Blocky - shapes.js
+
+    Collision and selection boxes of the non-cube block shapes, in block
+    local coordinates [x0, y0, z0, x1, y1, z1].
+*/
+
+import { B, SHAPE, SOLID } from "./blocks.js";
+
+const FULL = [0, 0, 0, 1, 1, 1];
+const NONE = [];
+
+//Direction of a face index (0:+x 1:-x 2:+y 3:-y 4:+z 5:-z)
+export const FACE_DIR = [
+    [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]
+];
+
+export function collisionBoxes(id, meta) {
+    if (!SOLID[id]) {
+        return NONE;
+    }
+    switch (SHAPE[id]) {
+        case "slab":
+            if (meta === 2) {
+                return [FULL];
+            }
+            return [meta === 1 ? [0, 0.5, 0, 1, 1, 1] : [0, 0, 0, 1, 0.5, 1]];
+        case "cactus":
+            return [[0.0625, 0, 0.0625, 0.9375, 1, 0.9375]];
+        case "farmland":
+            return [[0, 0, 0, 1, 0.9375, 1]];
+        default:
+            return [FULL];
+    }
+}
+
+export function selectionBox(id, meta) {
+    switch (SHAPE[id]) {
+        case "none":
+        case "liquid":
+            return null;
+        case "cross":
+            return [0.15, 0, 0.15, 0.85, 0.8, 0.85];
+        case "crop":
+            return [0, 0, 0, 1, Math.min(1, 0.2 + meta * 0.1), 1];
+        case "torch": {
+            if (meta === 2 || meta === 3) {
+                return [0.4, 0, 0.4, 0.6, 0.62, 0.6];
+            }
+            const d = FACE_DIR[meta];
+            const cx = 0.5 - d[0] * 0.33, cz = 0.5 - d[2] * 0.33;
+            return [cx - 0.12, 0.2, cz - 0.12, cx + 0.12, 0.8, cz + 0.12];
+        }
+        case "ladder": {
+            const d = FACE_DIR[meta] || FACE_DIR[4];
+            const t = 0.125;
+            if (d[0] === 1) {
+                return [0, 0, 0, t, 1, 1];
+            }
+            if (d[0] === -1) {
+                return [1 - t, 0, 0, 1, 1, 1];
+            }
+            if (d[2] === 1) {
+                return [0, 0, 0, 1, 1, t];
+            }
+            return [0, 0, 1 - t, 1, 1, 1];
+        }
+        case "slab":
+            if (meta === 2) {
+                return FULL;
+            }
+            return meta === 1 ? [0, 0.5, 0, 1, 1, 1] : [0, 0, 0, 1, 0.5, 1];
+        case "cactus":
+            return [0.0625, 0, 0.0625, 0.9375, 1, 0.9375];
+        case "farmland":
+            return [0, 0, 0, 1, 0.9375, 1];
+        default:
+            return FULL;
+    }
+}
+
+//True when an entity box overlaps a ladder in this block
+export function isClimbable(id) {
+    return id === B.LADDER;
+}

+ 160 - 0
src/web/Blocky/js/storage.js

@@ -0,0 +1,160 @@
+/*
+    Blocky - storage.js
+
+    Saves and loads worlds. Inside ArozOS worlds live in the user's appdata
+    folder through backend/worlds.agi, so they follow the user to any
+    device. When the gateway is not reachable (the app opened standalone)
+    the worlds are kept in this browser's IndexedDB instead.
+
+    A world is { meta, payload } where payload is a string (the compressed
+    world state); the server splits it into parts of PART_SIZE characters.
+*/
+
+const SCRIPT = "Blocky/backend/worlds.agi";
+const PART_SIZE = 3 * 1024 * 1024;
+const DB_NAME = "blocky-worlds";
+
+function agi(data, timeout = 60000) {
+    return new Promise((resolve, reject) => {
+        let done = false;
+        const timer = setTimeout(() => {
+            if (!done) {
+                done = true;
+                reject(new Error("timeout"));
+            }
+        }, timeout);
+        ao_module_agirun(SCRIPT, data, (resp) => {
+            if (done) {
+                return;
+            }
+            done = true;
+            clearTimeout(timer);
+            let obj = resp;
+            try {
+                if (typeof resp === "string") {
+                    obj = JSON.parse(resp);
+                }
+            } catch (e) {
+                reject(new Error("bad response"));
+                return;
+            }
+            if (!obj || obj.ok !== true) {
+                reject(new Error((obj && obj.error) || "request failed"));
+                return;
+            }
+            resolve(obj);
+        }, () => {
+            if (!done) {
+                done = true;
+                clearTimeout(timer);
+                reject(new Error("gateway unreachable"));
+            }
+        });
+    });
+}
+
+function idb() {
+    return new Promise((resolve, reject) => {
+        const req = indexedDB.open(DB_NAME, 1);
+        req.onupgradeneeded = () => {
+            req.result.createObjectStore("worlds", { keyPath: "id" });
+        };
+        req.onsuccess = () => resolve(req.result);
+        req.onerror = () => reject(req.error);
+    });
+}
+
+async function idbOp(mode, fn) {
+    const db = await idb();
+    return new Promise((resolve, reject) => {
+        const tx = db.transaction("worlds", mode);
+        const store = tx.objectStore("worlds");
+        const req = fn(store);
+        tx.oncomplete = () => resolve(req ? req.result : undefined);
+        tx.onerror = () => reject(tx.error);
+    });
+}
+
+export class Storage {
+    constructor() {
+        this.mode = "local";
+    }
+
+    //Pick the server when the AGI gateway answers, else IndexedDB
+    async init() {
+        if (typeof ao_module_agirun === "function" && typeof $ !== "undefined") {
+            try {
+                await agi({ action: "list" }, 8000);
+                this.mode = "server";
+                return this.mode;
+            } catch (e) {
+                //Fall through to local storage
+            }
+        }
+        this.mode = "local";
+        return this.mode;
+    }
+
+    get where() {
+        return this.mode === "server" ? "your ArozOS account" : "this browser";
+    }
+
+    async list() {
+        let worlds;
+        if (this.mode === "server") {
+            worlds = (await agi({ action: "list" })).worlds || [];
+        } else {
+            const rows = await idbOp("readonly", (s) => s.getAll());
+            worlds = (rows || []).map((r) => r.meta);
+        }
+        worlds.sort((a, b) => (b.lastPlayed || 0) - (a.lastPlayed || 0));
+        return worlds;
+    }
+
+    async load(id) {
+        if (this.mode === "server") {
+            const meta = (await agi({ action: "meta", id })).meta;
+            let payload = "";
+            for (let i = 0; i < meta.parts; i++) {
+                payload += (await agi({ action: "loadpart", id, gen: meta.gen, index: i })).data;
+            }
+            return { meta, payload };
+        }
+        const row = await idbOp("readonly", (s) => s.get(id));
+        if (!row) {
+            throw new Error("world not found");
+        }
+        return { meta: row.meta, payload: row.payload };
+    }
+
+    async save(meta, payload) {
+        if (this.mode === "server") {
+            const gen = (meta.gen || 0) + 1;
+            const parts = Math.max(1, Math.ceil(payload.length / PART_SIZE));
+            for (let i = 0; i < parts; i++) {
+                await agi({ action: "savepart", id: meta.id, gen, index: i, data: payload.slice(i * PART_SIZE, (i + 1) * PART_SIZE) });
+            }
+            const next = Object.assign({}, meta, { gen, parts, size: payload.length });
+            await agi({ action: "savemeta", id: meta.id, meta: JSON.stringify(next) });
+            meta.gen = gen;
+            meta.parts = parts;
+            meta.size = payload.length;
+            return;
+        }
+        meta.size = payload.length;
+        await idbOp("readwrite", (s) => s.put({ id: meta.id, meta, payload }));
+    }
+
+    async remove(id) {
+        if (this.mode === "server") {
+            await agi({ action: "delete", id });
+            return;
+        }
+        await idbOp("readwrite", (s) => s.delete(id));
+    }
+}
+
+export function newWorldId(name) {
+    const slug = String(name || "world").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24) || "world";
+    return slug + "-" + Date.now().toString(36);
+}

+ 1203 - 0
src/web/Blocky/js/textures.js

@@ -0,0 +1,1203 @@
+/*
+    Blocky - textures.js
+
+    Every texture in the game is painted here at start up: 16x16 pixel art
+    tiles for blocks and items, the block breaking crack stages, and the
+    isometric inventory icons. Nothing is loaded from image files, so the
+    look is entirely Blocky's own.
+
+    Output:
+        layers      - Uint8Array of all tiles stacked (RGBA, 16x16 each),
+                      uploaded as one texture array by the renderer
+        layerOf     - tile name -> layer index
+        canvases    - tile name -> 16x16 canvas (for icons and particles)
+        avgColor    - tile name -> [r, g, b] average of the opaque pixels
+*/
+
+import { mulberry32 } from "./util.js";
+
+const S = 16;
+
+//Grassland tints, also used to colour the inventory icons of tinted tiles
+export const GRASS_TINT = [0.62, 1.0, 0.43];
+export const FOLIAGE_TINT = [0.48, 0.86, 0.32];
+
+class Tile {
+    constructor(seed) {
+        this.d = new Uint8ClampedArray(S * S * 4);
+        this.rnd = mulberry32(seed);
+    }
+    r() {
+        return this.rnd();
+    }
+    ri(n) {
+        return Math.floor(this.rnd() * n);
+    }
+    set(x, y, c, a = 255) {
+        x = Math.round(x);
+        y = Math.round(y);
+        if (x < 0 || y < 0 || x >= S || y >= S) {
+            return;
+        }
+        const i = (y * S + x) * 4;
+        this.d[i] = c[0];
+        this.d[i + 1] = c[1];
+        this.d[i + 2] = c[2];
+        this.d[i + 3] = a;
+    }
+    get(x, y) {
+        const i = (y * S + x) * 4;
+        return [this.d[i], this.d[i + 1], this.d[i + 2], this.d[i + 3]];
+    }
+    alpha(x, y) {
+        return this.d[(y * S + x) * 4 + 3];
+    }
+    vary(c, v) {
+        const k = (this.rnd() - 0.5) * 2 * v;
+        return [c[0] + k, c[1] + k, c[2] + k];
+    }
+    fill(c, v = 0) {
+        for (let y = 0; y < S; y++) {
+            for (let x = 0; x < S; x++) {
+                this.set(x, y, this.vary(c, v));
+            }
+        }
+    }
+    clear() {
+        this.d.fill(0);
+    }
+    shade(x, y, f) {
+        if (x < 0 || y < 0 || x >= S || y >= S) {
+            return;
+        }
+        const i = (y * S + x) * 4;
+        this.d[i] *= f;
+        this.d[i + 1] *= f;
+        this.d[i + 2] *= f;
+    }
+    rect(x0, y0, w, h, c, v = 0, a = 255) {
+        for (let y = y0; y < y0 + h; y++) {
+            for (let x = x0; x < x0 + w; x++) {
+                this.set(x, y, this.vary(c, v), a);
+            }
+        }
+    }
+    border(c, v = 0) {
+        for (let i = 0; i < S; i++) {
+            this.set(i, 0, this.vary(c, v));
+            this.set(i, S - 1, this.vary(c, v));
+            this.set(0, i, this.vary(c, v));
+            this.set(S - 1, i, this.vary(c, v));
+        }
+    }
+    copy(other) {
+        this.d.set(other.d);
+    }
+    //Paint every pixel for which pred(x + 0.5, y + 0.5) is true
+    shape(pred, colorFn) {
+        for (let y = 0; y < S; y++) {
+            for (let x = 0; x < S; x++) {
+                if (pred(x + 0.5, y + 0.5)) {
+                    this.set(x, y, colorFn(x, y));
+                }
+            }
+        }
+    }
+    //Darken opaque pixels that touch a transparent pixel (item outlines)
+    outline(f = 0.55) {
+        const edge = [];
+        for (let y = 0; y < S; y++) {
+            for (let x = 0; x < S; x++) {
+                if (this.alpha(x, y) === 0) {
+                    continue;
+                }
+                const out = (xx, yy) => xx < 0 || yy < 0 || xx >= S || yy >= S || this.alpha(xx, yy) === 0;
+                if (out(x - 1, y) || out(x + 1, y) || out(x, y - 1) || out(x, y + 1)) {
+                    edge.push([x, y]);
+                }
+            }
+        }
+        for (const [x, y] of edge) {
+            this.shade(x, y, f);
+        }
+    }
+}
+
+/* ------------------------------------------------------------------ */
+/* Block tiles                                                         */
+/* ------------------------------------------------------------------ */
+
+function paintStone(t) {
+    t.fill([127, 127, 127], 9);
+    for (let k = 0; k < 8; k++) {
+        const x = t.ri(16), y = t.ri(16), len = 2 + t.ri(4);
+        for (let i = 0; i < len; i++) {
+            t.set((x + i) % 16, y + (i > 1 && t.r() < 0.3 ? 1 : 0), t.vary([104, 104, 104], 5));
+        }
+    }
+    for (let k = 0; k < 10; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([150, 150, 150], 6));
+    }
+}
+
+function wrapDist(ax, ay, bx, by) {
+    let dx = Math.abs(ax - bx), dy = Math.abs(ay - by);
+    dx = Math.min(dx, 16 - dx);
+    dy = Math.min(dy, 16 - dy);
+    return Math.sqrt(dx * dx + dy * dy);
+}
+
+function paintCobble(t, base = [128, 128, 128], spread = 28) {
+    const pts = [];
+    for (let i = 0; i < 11; i++) {
+        pts.push([t.r() * 16, t.r() * 16, (t.r() - 0.5) * spread]);
+    }
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            let d1 = 99, d2 = 99, cell = 0;
+            for (let i = 0; i < pts.length; i++) {
+                const d = wrapDist(x + 0.5, y + 0.5, pts[i][0], pts[i][1]);
+                if (d < d1) {
+                    d2 = d1; d1 = d; cell = i;
+                } else if (d < d2) {
+                    d2 = d;
+                }
+            }
+            if (d2 - d1 < 1.0) {
+                t.set(x, y, t.vary([base[0] * 0.55, base[1] * 0.55, base[2] * 0.55], 6));
+            } else {
+                const k = pts[cell][2] + (d1 < 1.6 ? 12 : 0);
+                t.set(x, y, t.vary([base[0] + k, base[1] + k, base[2] + k], 8));
+            }
+        }
+    }
+}
+
+function paintDirt(t) {
+    t.fill([134, 96, 67], 10);
+    for (let k = 0; k < 22; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([104, 74, 50], 6));
+    }
+    for (let k = 0; k < 12; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([162, 120, 86], 6));
+    }
+}
+
+function paintSand(t) {
+    t.fill([219, 207, 163], 6);
+    for (let k = 0; k < 16; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([198, 184, 138], 5));
+    }
+    for (let k = 0; k < 10; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([234, 226, 192], 4));
+    }
+}
+
+function paintOre(t, color, clusters) {
+    paintStone(t);
+    for (let c = 0; c < clusters; c++) {
+        const cx = 2 + t.ri(12), cy = 2 + t.ri(12);
+        const n = 3 + t.ri(3);
+        for (let i = 0; i < n; i++) {
+            const x = cx + t.ri(3) - 1, y = cy + t.ri(3) - 1;
+            t.set(x, y, t.vary(color, 12));
+            if (t.r() < 0.5) {
+                t.set(x + 1, y, t.vary([color[0] * 0.7, color[1] * 0.7, color[2] * 0.7], 8));
+            }
+        }
+        t.set(cx, cy, [Math.min(255, color[0] + 40), Math.min(255, color[1] + 40), Math.min(255, color[2] + 40)]);
+    }
+}
+
+function paintPlanks(t, base = [168, 134, 82]) {
+    for (let b = 0; b < 4; b++) {
+        const f = 0.9 + t.r() * 0.16;
+        const seam = (b * 7 + 3) % 16;
+        for (let yy = 0; yy < 4; yy++) {
+            const y = b * 4 + yy;
+            for (let x = 0; x < 16; x++) {
+                let c = [base[0] * f, base[1] * f, base[2] * f];
+                if (yy === 3) {
+                    c = [base[0] * 0.62, base[1] * 0.62, base[2] * 0.6];
+                } else if (x === seam) {
+                    c = [base[0] * 0.7, base[1] * 0.7, base[2] * 0.68];
+                } else if (t.r() < 0.12) {
+                    c = [c[0] * 0.88, c[1] * 0.88, c[2] * 0.88];
+                }
+                t.set(x, y, t.vary(c, 4));
+            }
+        }
+    }
+}
+
+function paintLogSide(t) {
+    const base = [104, 82, 52];
+    for (let x = 0; x < 16; x++) {
+        const f = 0.82 + t.r() * 0.3;
+        for (let y = 0; y < 16; y++) {
+            t.set(x, y, t.vary([base[0] * f, base[1] * f, base[2] * f], 6));
+        }
+    }
+    for (let k = 0; k < 9; k++) {
+        const x = t.ri(16), y = t.ri(16), len = 3 + t.ri(5);
+        for (let i = 0; i < len; i++) {
+            t.set(x, (y + i) % 16, t.vary([68, 52, 32], 5));
+        }
+    }
+}
+
+function paintLogTop(t) {
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            const dx = x - 7.5, dy = y - 7.5;
+            const d = Math.max(Math.abs(dx), Math.abs(dy)) * 0.55 + Math.sqrt(dx * dx + dy * dy) * 0.45;
+            if (d > 6.7) {
+                t.set(x, y, t.vary([100, 79, 50], 8));
+            } else {
+                const ring = Math.floor(d * 1.15) % 2;
+                t.set(x, y, t.vary(ring ? [184, 150, 94] : [160, 128, 78], 5));
+            }
+        }
+    }
+}
+
+function paintLeaves(t) {
+    t.fill([150, 150, 150], 24);
+    for (let k = 0; k < 26; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([104, 104, 104], 10));
+    }
+    for (let k = 0; k < 10; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([196, 196, 196], 8));
+    }
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            if (t.r() < 0.16) {
+                t.set(x, y, [0, 0, 0], 0);
+            }
+        }
+    }
+}
+
+function paintGlass(t) {
+    t.clear();
+    for (let i = 0; i < 16; i++) {
+        t.set(i, 0, [214, 234, 240]);
+        t.set(i, 15, [190, 214, 222]);
+        t.set(0, i, [214, 234, 240]);
+        t.set(15, i, [190, 214, 222]);
+    }
+    for (let i = 0; i < 4; i++) {
+        t.set(3 + i, 6 - i, [236, 250, 255], 230);
+    }
+    t.set(11, 11, [236, 250, 255], 210);
+    t.set(12, 10, [236, 250, 255], 210);
+}
+
+function paintBricks(t) {
+    t.fill([176, 170, 164], 5);
+    for (let row = 0; row < 4; row++) {
+        const off = (row % 2) * 4;
+        for (let b = 0; b < 3; b++) {
+            const bx = off + b * 8;
+            const tone = t.vary([150, 72, 56], 14);
+            for (let yy = 0; yy < 3; yy++) {
+                for (let xx = 0; xx < 7; xx++) {
+                    let c = t.vary(tone, 6);
+                    if (yy === 0) {
+                        c = [c[0] + 16, c[1] + 10, c[2] + 8];
+                    }
+                    t.set((bx + xx) % 16, row * 4 + yy, c);
+                }
+            }
+        }
+    }
+}
+
+function paintStoneBricks(t) {
+    t.fill([124, 124, 124], 7);
+    for (let x = 0; x < 16; x++) {
+        t.set(x, 7, t.vary([82, 82, 82], 4));
+        t.set(x, 15, t.vary([82, 82, 82], 4));
+        t.set(x, 0, t.vary([150, 150, 150], 4));
+        t.set(x, 8, t.vary([150, 150, 150], 4));
+        t.set(x, 6, t.vary([108, 108, 108], 4));
+        t.set(x, 14, t.vary([108, 108, 108], 4));
+    }
+    for (let y = 0; y < 8; y++) {
+        t.set(15, y, t.vary([82, 82, 82], 4));
+        t.set(7, y + 8, t.vary([82, 82, 82], 4));
+        t.set(0, y, t.vary([140, 140, 140], 4));
+        t.set(8, y + 8, t.vary([140, 140, 140], 4));
+    }
+}
+
+function paintSmoothStone(t, sideSplit) {
+    t.fill([164, 164, 164], 4);
+    t.border([118, 118, 118], 3);
+    if (sideSplit) {
+        for (let x = 0; x < 16; x++) {
+            t.set(x, 7, t.vary([118, 118, 118], 3));
+            t.set(x, 8, t.vary([180, 180, 180], 3));
+        }
+    }
+}
+
+function paintMetal(t, base, edge, dark) {
+    t.fill(base, 4);
+    t.border(edge, 3);
+    for (let i = 1; i < 15; i++) {
+        t.set(i, 1, [Math.min(255, base[0] + 25), Math.min(255, base[1] + 25), Math.min(255, base[2] + 25)]);
+        t.set(1, i, [Math.min(255, base[0] + 25), Math.min(255, base[1] + 25), Math.min(255, base[2] + 25)]);
+        t.set(i, 14, dark);
+        t.set(14, i, dark);
+    }
+    for (const [x, y] of [[3, 3], [12, 3], [3, 12], [12, 12]]) {
+        t.set(x, y, dark);
+    }
+}
+
+function paintFurnaceSide(t) {
+    t.fill([118, 118, 118], 7);
+    for (let k = 0; k < 12; k++) {
+        t.set(t.ri(16), t.ri(16), t.vary([98, 98, 98], 5));
+    }
+    t.border([84, 84, 84], 4);
+}
+
+function paintFurnaceFront(t, lit) {
+    paintFurnaceSide(t);
+    for (let x = 3; x < 13; x++) {
+        t.set(x, 7, [80, 80, 80]);
+    }
+    for (let y = 8; y < 14; y++) {
+        for (let x = 4; x < 12; x++) {
+            if (!lit) {
+                t.set(x, y, t.vary([28, 28, 30], 4));
+            } else {
+                const heat = (y - 8) / 6;
+                const flick = t.r();
+                const c = flick < 0.3 ? [255, 236, 140] : [255, 150 + heat * 60, 40 + heat * 20];
+                t.set(x, y, t.vary(c, 10));
+            }
+        }
+    }
+    for (let x = 4; x < 12; x += 2) {
+        t.set(x, 3, [70, 70, 70]);
+        t.set(x, 4, [70, 70, 70]);
+    }
+}
+
+function paintChest(t, kind) {
+    paintPlanks(t, [160, 112, 52]);
+    t.border([88, 60, 28], 4);
+    if (kind !== "top") {
+        for (let x = 0; x < 16; x++) {
+            t.set(x, 5, [88, 60, 28]);
+            t.set(x, 6, [118, 82, 40]);
+        }
+    }
+    if (kind === "front") {
+        t.rect(7, 4, 2, 4, [205, 205, 205]);
+        t.set(7, 7, [120, 120, 120]);
+        t.set(8, 7, [120, 120, 120]);
+    }
+}
+
+function paintWorkbench(t, kind) {
+    paintPlanks(t);
+    if (kind === "top") {
+        t.border([96, 70, 40], 3);
+        t.rect(2, 2, 12, 12, [150, 116, 70], 5);
+        for (let i = 2; i < 14; i++) {
+            t.set(i, 6, [112, 84, 50]);
+            t.set(i, 10, [112, 84, 50]);
+            t.set(6, i, [112, 84, 50]);
+            t.set(10, i, [112, 84, 50]);
+        }
+        return;
+    }
+    for (let x = 0; x < 16; x++) {
+        t.set(x, 0, [96, 70, 40]);
+        t.set(x, 1, [120, 90, 54]);
+    }
+    if (kind === "side") {
+        //Hammer
+        t.rect(2, 4, 5, 2, [150, 150, 154]);
+        t.rect(4, 6, 1, 6, [96, 66, 34]);
+        //Saw blade with teeth
+        for (let y = 4; y < 11; y++) {
+            for (let x = 9; x < 9 + Math.max(1, y - 3); x++) {
+                t.set(x, y, [182, 184, 190]);
+            }
+            t.set(9 + Math.max(1, y - 3), y, (y % 2) ? [120, 122, 128] : [182, 184, 190]);
+        }
+        t.rect(8, 3, 2, 2, [110, 76, 40]);
+    } else {
+        t.rect(3, 5, 10, 7, [112, 84, 50]);
+        t.rect(4, 6, 8, 5, [150, 116, 70], 4);
+        t.rect(7, 8, 2, 1, [70, 50, 28]);
+    }
+}
+
+function paintCactus(t, kind) {
+    if (kind === "side") {
+        t.fill([70, 138, 54], 6);
+        for (let y = 0; y < 16; y++) {
+            for (const x of [0, 5, 10, 15]) {
+                t.set(x, y, t.vary([48, 106, 38], 4));
+            }
+            if (y % 4 === 1) {
+                for (const x of [2, 7, 12]) {
+                    t.set(x, y, [214, 226, 176]);
+                }
+            }
+        }
+        return;
+    }
+    t.fill([84, 150, 62], 5);
+    t.border([52, 108, 40], 3);
+    for (let y = 4; y < 12; y++) {
+        for (let x = 4; x < 12; x++) {
+            if (x === 4 || x === 11 || y === 4 || y === 11) {
+                t.set(x, y, [62, 124, 48]);
+            }
+        }
+    }
+    t.set(7, 7, [140, 190, 110]);
+    t.set(8, 8, [140, 190, 110]);
+    if (kind === "bottom") {
+        for (let i = 0; i < 16 * 16; i++) {
+            t.d[i * 4] *= 0.8;
+            t.d[i * 4 + 1] *= 0.8;
+            t.d[i * 4 + 2] *= 0.8;
+        }
+    }
+}
+
+function paintFarmland(t, wet) {
+    const base = wet ? [86, 58, 38] : [124, 88, 60];
+    t.fill(base, 7);
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            if (y % 4 === 0) {
+                t.set(x, y, t.vary([base[0] * 0.72, base[1] * 0.72, base[2] * 0.72], 4));
+            } else if (y % 4 === 1) {
+                t.set(x, y, t.vary([base[0] * 1.15, base[1] * 1.15, base[2] * 1.15], 4));
+            }
+        }
+    }
+}
+
+function paintGrassBlades(t, gray) {
+    t.clear();
+    for (let b = 0; b < 8; b++) {
+        const x0 = 1 + t.ri(14);
+        const h = 6 + t.ri(9);
+        const lean = (t.r() - 0.5) * 0.5;
+        const c = gray ? t.vary([176, 176, 176], 30) : t.vary([90, 150, 60], 20);
+        for (let i = 0; i < h; i++) {
+            const y = 15 - i;
+            const x = x0 + lean * i;
+            t.set(x, y, i > h - 3 ? [c[0] * 1.12, c[1] * 1.12, c[2] * 1.12] : c);
+        }
+    }
+}
+
+function paintFlower(t, petal, center) {
+    t.clear();
+    for (let y = 8; y < 16; y++) {
+        t.set(7, y, [62, 136, 42]);
+    }
+    t.set(6, 12, [74, 156, 50]);
+    t.set(5, 11, [74, 156, 50]);
+    t.set(8, 11, [74, 156, 50]);
+    t.set(9, 10, [74, 156, 50]);
+    for (const [dx, dy] of [[0, -2], [-2, 0], [2, 0], [0, 2], [-1, -1], [1, -1], [-1, 1], [1, 1], [0, -1], [-1, 0], [1, 0], [0, 1]]) {
+        t.set(7 + dx, 5 + dy, t.vary(petal, 10));
+    }
+    t.set(7, 5, center);
+}
+
+function paintMushroom(t, cap, spots) {
+    t.clear();
+    t.rect(7, 10, 2, 5, [222, 212, 192], 6);
+    for (let y = 5; y < 10; y++) {
+        const half = y === 5 ? 2 : y === 6 ? 3 : 4;
+        for (let x = 8 - half; x < 8 + half; x++) {
+            const c = y < 7 ? [cap[0] * 1.15, cap[1] * 1.15, cap[2] * 1.15] : cap;
+            t.set(x, y, t.vary(c, 8));
+        }
+    }
+    if (spots) {
+        for (const [x, y] of [[6, 6], [9, 7], [5, 8], [10, 8]]) {
+            t.set(x, y, [240, 236, 228]);
+        }
+    }
+}
+
+function paintReeds(t) {
+    t.clear();
+    for (const x0 of [2, 7, 12]) {
+        const off = t.ri(5);
+        for (let y = 0; y < 16; y++) {
+            const joint = (y + off) % 5 === 0;
+            t.set(x0, y, joint ? [196, 226, 150] : t.vary([150, 200, 100], 8));
+            t.set(x0 + 1, y, joint ? [160, 196, 116] : t.vary([116, 166, 72], 8));
+        }
+        t.set(x0 - 1, 4 + off, [110, 170, 70]);
+        t.set(x0 + 2, 9 + off % 3, [110, 170, 70]);
+    }
+}
+
+function paintWheat(t, stage) {
+    t.clear();
+    const h = 2 + Math.round(stage * 1.75);
+    const ripe = stage / 7;
+    const stalk = [80 + 130 * ripe, 168 + 10 * ripe, 40 + 30 * ripe];
+    for (const x0 of [1, 4, 7, 10, 13]) {
+        const hh = h - t.ri(2);
+        for (let i = 0; i < hh; i++) {
+            t.set(x0 + (i > hh * 0.6 ? 1 : 0), 15 - i, t.vary(stalk, 10));
+        }
+        if (stage >= 5) {
+            for (let i = 0; i < 3; i++) {
+                t.set(x0 + 1, 15 - hh + i, t.vary([214 + 20 * ripe, 180, 70], 10));
+                t.set(x0 + 2, 15 - hh + i + 1, t.vary([200, 168, 64], 10));
+            }
+        }
+    }
+}
+
+function paintSapling(t) {
+    t.clear();
+    t.rect(7, 9, 2, 7, [104, 76, 44], 6);
+    for (let y = 1; y < 11; y++) {
+        for (let x = 2; x < 14; x++) {
+            const dx = x - 7.5, dy = (y - 5.5) * 1.2;
+            if (dx * dx + dy * dy < 22 && t.r() > 0.18) {
+                t.set(x, y, t.vary([58, 132, 44], 18));
+            }
+        }
+    }
+}
+
+function paintDeadBush(t) {
+    t.clear();
+    const twig = (x, y, dx, len) => {
+        for (let i = 0; i < len; i++) {
+            t.set(x + dx * i, y - i, [124, 88, 48]);
+        }
+    };
+    twig(7, 15, 0, 6);
+    twig(7, 11, -0.6, 7);
+    twig(8, 12, 0.7, 7);
+    twig(7, 9, 0.3, 6);
+    twig(4, 8, -0.4, 3);
+    twig(11, 9, 0.5, 3);
+}
+
+function paintWater(t) {
+    t.fill([52, 98, 212], 8);
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            const w = Math.sin((x + y * 0.5) * 0.8) + Math.sin((x * 0.5 - y) * 0.9);
+            if (w > 1.3) {
+                t.set(x, y, t.vary([96, 146, 236], 6));
+            }
+        }
+    }
+    for (let i = 0; i < S * S; i++) {
+        t.d[i * 4 + 3] = 178;
+    }
+}
+
+function paintLadder(t) {
+    t.clear();
+    for (let y = 0; y < 16; y++) {
+        t.set(2, y, [126, 94, 52]);
+        t.set(3, y, [100, 72, 40]);
+        t.set(12, y, [126, 94, 52]);
+        t.set(13, y, [100, 72, 40]);
+    }
+    for (const y of [2, 7, 12]) {
+        for (let x = 4; x < 12; x++) {
+            t.set(x, y, [146, 110, 64]);
+            t.set(x, y + 1, [110, 80, 46]);
+        }
+    }
+}
+
+function paintTorch(t) {
+    t.clear();
+    for (let y = 9; y < 16; y++) {
+        t.set(7, y, [138, 102, 54]);
+        t.set(8, y, [104, 76, 40]);
+    }
+    t.set(7, 6, [255, 196, 70]);
+    t.set(8, 6, [255, 170, 50]);
+    t.set(7, 7, [255, 248, 196]);
+    t.set(8, 7, [255, 226, 120]);
+    t.set(7, 8, [255, 204, 90]);
+    t.set(8, 8, [240, 150, 40]);
+}
+
+function paintLamp(t) {
+    for (let y = 0; y < 16; y++) {
+        for (let x = 0; x < 16; x++) {
+            const d = Math.max(Math.abs(x - 7.5), Math.abs(y - 7.5));
+            t.set(x, y, t.vary(d < 3 ? [255, 246, 212] : [255, 222, 146], 6));
+        }
+    }
+    t.border([122, 94, 58], 4);
+    for (let i = 1; i < 15; i++) {
+        t.set(i, 7, [122, 94, 58]);
+        t.set(7, i, [122, 94, 58]);
+    }
+}
+
+function paintCrystalBlock(t) {
+    t.fill([104, 224, 220], 6);
+    for (let i = -16; i < 32; i += 5) {
+        for (let k = 0; k < 16; k++) {
+            t.set(i + k, k, [170, 246, 242]);
+        }
+    }
+    t.border([60, 168, 166], 3);
+}
+
+/* ------------------------------------------------------------------ */
+/* Item tiles                                                          */
+/* ------------------------------------------------------------------ */
+
+//Coordinates along / across a handle running from bottom-left to top-right
+function handleFrame(x, y) {
+    const ox = 2.5, oy = 13.5;
+    const u = ((x - ox) - (y - oy)) * 0.7071;
+    const v = ((x - ox) + (y - oy)) * 0.7071;
+    return [u, v];
+}
+
+const WOOD_LIGHT = [150, 110, 62];
+const WOOD_DARK = [96, 68, 36];
+
+function paintHandle(t, len = 13) {
+    t.shape((x, y) => {
+        const [u, v] = handleFrame(x, y);
+        return u > -0.5 && u < len && Math.abs(v) < 0.75;
+    }, (x, y) => (handleFrame(x + 0.5, y + 0.5)[1] < 0 ? WOOD_LIGHT : WOOD_DARK));
+}
+
+function paintStick(t) {
+    t.clear();
+    paintHandle(t, 14.5);
+    t.outline(0.75);
+}
+
+function paintTool(t, kind, color) {
+    t.clear();
+    const light = [Math.min(255, color[0] + 40), Math.min(255, color[1] + 40), Math.min(255, color[2] + 40)];
+    const headColor = (x, y) => {
+        const [u, v] = handleFrame(x + 0.5, y + 0.5);
+        return (u + v * 0.3) > 11.6 ? light : color;
+    };
+    let head;
+    if (kind === "pickaxe") {
+        paintHandle(t, 11);
+        head = (x, y) => {
+            const [u, v] = handleFrame(x, y);
+            const uc = 11.2 - 0.07 * v * v;
+            return Math.abs(v) < 6.6 && Math.abs(u - uc) < 1.05 + (Math.abs(v) < 2 ? 0.35 : 0);
+        };
+    } else if (kind === "axe") {
+        paintHandle(t, 12.5);
+        head = (x, y) => {
+            const [u, v] = handleFrame(x, y);
+            return v > -5.2 && v < 0.9 && Math.abs(u - 10.6) < 1.3 + Math.max(0, -v) * 0.42;
+        };
+    } else if (kind === "shovel") {
+        paintHandle(t, 10);
+        head = (x, y) => {
+            const [u, v] = handleFrame(x, y);
+            return u > 9 && u < 14.6 && Math.abs(v) < (u < 13 ? 2.3 : 2.3 - (u - 13) * 1.3);
+        };
+    } else {
+        paintHandle(t, 12.5);
+        head = (x, y) => {
+            const [u, v] = handleFrame(x, y);
+            return (v > -4.6 && v < 0.9 && u > 11 && u < 12.8) || (v > -4.6 && v < -3.1 && u > 9.6 && u < 12.8);
+        };
+    }
+    t.shape(head, headColor);
+    t.outline(0.6);
+}
+
+function paintIngot(t, base) {
+    t.clear();
+    const light = [Math.min(255, base[0] + 45), Math.min(255, base[1] + 45), Math.min(255, base[2] + 45)];
+    const dark = [base[0] * 0.66, base[1] * 0.66, base[2] * 0.66];
+    for (let y = 5; y < 8; y++) {
+        for (let x = 4 + (7 - y); x < 13 + (7 - y); x++) {
+            t.set(x, y, light);
+        }
+    }
+    for (let y = 8; y < 11; y++) {
+        for (let x = 2; x < 12; x++) {
+            t.set(x, y, base);
+        }
+        t.set(12, y, dark);
+        t.set(13, y - 1, dark);
+        t.set(14, y - 2, dark);
+    }
+    t.outline(0.62);
+}
+
+function paintBlob(t, cx, cy, rx, ry, colorFn, jag = 0) {
+    t.shape((x, y) => {
+        const dx = (x - cx) / rx, dy = (y - cy) / ry;
+        return dx * dx + dy * dy < 1 - jag * (t.r() - 0.5);
+    }, colorFn);
+}
+
+function paintCoal(t) {
+    t.clear();
+    paintBlob(t, 7.8, 8.2, 5.6, 4.8, () => t.vary([44, 44, 48], 10), 0.3);
+    for (let k = 0; k < 6; k++) {
+        const x = 4 + t.ri(8), y = 5 + t.ri(6);
+        if (t.alpha(x, y)) {
+            t.set(x, y, [96, 96, 104]);
+        }
+    }
+    t.outline(0.6);
+}
+
+function paintCrystal(t) {
+    t.clear();
+    t.shape((x, y) => Math.abs(x - 8) / 6 + Math.abs(y - 8) / 7 < 1, (x, y) => {
+        if (y < 6) {
+            return [190, 252, 248];
+        }
+        return x < 8 ? [110, 232, 226] : [72, 196, 196];
+    });
+    t.set(6, 5, [255, 255, 255]);
+    t.outline(0.6);
+}
+
+function paintFlint(t) {
+    t.clear();
+    t.shape((x, y) => y > 3 && y < 14 && x > 3 + (13 - y) * 0.2 && x < 12 - Math.abs(y - 8) * 0.35, (x, y) => (x + y < 16 ? [104, 104, 110] : [62, 62, 68]));
+    t.outline(0.6);
+}
+
+function paintClayBall(t) {
+    t.clear();
+    paintBlob(t, 8, 8.5, 5, 4.6, (x, y) => (x + y < 14 ? [184, 190, 204] : [150, 156, 172]));
+    t.outline(0.65);
+}
+
+function paintSeeds(t) {
+    t.clear();
+    for (let k = 0; k < 8; k++) {
+        const x = 3 + t.ri(10), y = 4 + t.ri(9);
+        t.set(x, y, [96, 170, 60]);
+        t.set(x + 1, y, [70, 130, 44]);
+    }
+}
+
+function paintWheatItem(t) {
+    t.clear();
+    for (let s = 0; s < 5; s++) {
+        const x0 = 4 + s * 2;
+        for (let y = 7; y < 15; y++) {
+            t.set(x0 + (y > 11 ? (s < 2 ? 1 : s > 2 ? -1 : 0) : 0), y, [176, 160, 70]);
+        }
+        for (let y = 2; y < 7; y++) {
+            t.set(x0, y, t.vary([226, 196, 90], 12));
+        }
+    }
+    t.rect(5, 11, 7, 1, [140, 96, 40]);
+}
+
+function paintBread(t) {
+    t.clear();
+    paintBlob(t, 8, 9, 7, 4.2, (x, y) => (y < 8 ? [222, 162, 82] : [184, 120, 52]));
+    for (const x of [5, 8, 11]) {
+        t.set(x, 7, [150, 96, 40]);
+        t.set(x + 1, 6, [150, 96, 40]);
+    }
+    t.outline(0.62);
+}
+
+function paintApple(t) {
+    t.clear();
+    paintBlob(t, 8, 9.5, 5.5, 5, (x, y) => (x < 6 && y < 9 ? [246, 92, 80] : [204, 34, 36]));
+    t.set(5, 7, [255, 190, 180]);
+    t.set(8, 3, [104, 72, 40]);
+    t.set(8, 4, [104, 72, 40]);
+    t.set(9, 3, [70, 150, 50]);
+    t.set(10, 3, [70, 150, 50]);
+    t.set(10, 2, [70, 150, 50]);
+    t.outline(0.65);
+}
+
+function paintBowl(t, stew) {
+    t.clear();
+    t.shape((x, y) => {
+        const dx = (x - 8) / 7, dy = (y - 8) / 6;
+        return y > 8 && dx * dx + dy * dy < 1;
+    }, (x, y) => (y < 11 ? [150, 108, 60] : [118, 84, 46]));
+    for (let x = 1; x < 15; x++) {
+        t.set(x, 8, stew ? [146, 96, 54] : [86, 60, 32]);
+    }
+    if (stew) {
+        for (let x = 3; x < 13; x++) {
+            t.set(x, 7, [172, 120, 70]);
+        }
+        t.set(5, 7, [214, 196, 170]);
+        t.set(9, 6, [200, 60, 50]);
+        t.set(11, 7, [214, 196, 170]);
+    }
+    t.outline(0.65);
+}
+
+function paintBucket(t, water) {
+    t.clear();
+    for (let y = 5; y < 14; y++) {
+        const inset = (y - 5) * 0.25;
+        for (let x = Math.round(3 + inset); x < Math.round(13 - inset); x++) {
+            t.set(x, y, x < 7 ? [214, 214, 220] : [168, 168, 176]);
+        }
+    }
+    for (let x = 3; x < 13; x++) {
+        t.set(x, 5, water ? [70, 120, 226] : [64, 64, 70]);
+    }
+    for (let x = 4; x < 12; x++) {
+        t.set(x, 6, water ? [52, 98, 212] : [96, 96, 102]);
+    }
+    for (let i = 0; i < 9; i++) {
+        const a = Math.PI * (i / 8);
+        t.set(8 - Math.cos(a) * 5, 4 - Math.sin(a) * 3, [130, 130, 138]);
+    }
+    t.outline(0.6);
+}
+
+/* ------------------------------------------------------------------ */
+/* Crack overlays                                                      */
+/* ------------------------------------------------------------------ */
+
+function paintCracks(stage) {
+    const t = new Tile(4242);
+    t.clear();
+    const rng = mulberry32(777);
+    //Fixed crack paths; later stages reveal more of them
+    const pts = [];
+    for (let c = 0; c < 9; c++) {
+        let x = 8 + (rng() - 0.5) * 4, y = 8 + (rng() - 0.5) * 4;
+        const a0 = rng() * Math.PI * 2;
+        for (let i = 0; i < 9; i++) {
+            const a = a0 + (rng() - 0.5) * 1.2;
+            x += Math.cos(a) * 1.1;
+            y += Math.sin(a) * 1.1;
+            pts.push([x, y, c * 0.9 + i * 0.14]);
+        }
+    }
+    const limit = (stage + 1) * 0.95;
+    for (const [x, y, order] of pts) {
+        if (order < limit) {
+            t.set(x, y, [26, 26, 26], 210);
+        }
+    }
+    return t;
+}
+
+/* ------------------------------------------------------------------ */
+/* Registry                                                            */
+/* ------------------------------------------------------------------ */
+
+const PAINTERS = {
+    stone: paintStone,
+    cobblestone: (t) => paintCobble(t),
+    mossy: (t) => paintCobble(t, [110, 128, 104], 24),
+    dirt: paintDirt,
+    grass_top: (t) => {
+        t.fill([164, 164, 164], 20);
+        for (let k = 0; k < 24; k++) {
+            t.set(t.ri(16), t.ri(16), t.vary([124, 124, 124], 8));
+        }
+        for (let k = 0; k < 12; k++) {
+            t.set(t.ri(16), t.ri(16), t.vary([196, 196, 196], 8));
+        }
+    },
+    grass_side: (t) => {
+        paintDirt(t);
+        for (let x = 0; x < 16; x++) {
+            const h = 3 + (t.r() < 0.5 ? 1 : 0) + (t.r() < 0.25 ? 1 : 0);
+            for (let y = 0; y < h; y++) {
+                t.set(x, y, t.vary(y === h - 1 ? [78, 132, 54] : [100, 162, 70], 10));
+            }
+        }
+    },
+    sand: paintSand,
+    sandstone_top: (t) => {
+        t.fill([224, 212, 164], 4);
+        for (let k = 0; k < 10; k++) {
+            t.set(t.ri(16), t.ri(16), t.vary([206, 192, 146], 4));
+        }
+    },
+    sandstone_side: (t) => {
+        t.fill([216, 203, 155], 5);
+        for (let x = 0; x < 16; x++) {
+            for (let y = 0; y < 3; y++) {
+                t.set(x, y, t.vary([230, 220, 174], 4));
+            }
+            t.set(x, 3, t.vary([188, 172, 124], 4));
+            t.set(x, 10, t.vary([204, 190, 142], 4));
+            for (let y = 13; y < 16; y++) {
+                t.set(x, y, t.vary([200, 186, 138], 6));
+            }
+        }
+    },
+    sandstone_bottom: (t) => {
+        t.fill([206, 192, 144], 6);
+        for (let k = 0; k < 5; k++) {
+            const x = t.ri(16), y = t.ri(16);
+            for (let i = 0; i < 4; i++) {
+                t.set(x + i, y + (i > 1 ? 1 : 0), [180, 164, 118]);
+            }
+        }
+    },
+    gravel: (t) => {
+        t.fill([128, 122, 118], 8);
+        const tones = [[154, 148, 142], [100, 96, 92], [160, 142, 126], [88, 84, 82]];
+        for (let k = 0; k < 24; k++) {
+            const x = t.ri(16), y = t.ri(16), c = tones[t.ri(4)];
+            t.set(x, y, c);
+            t.set(x + 1, y, t.vary(c, 6));
+            if (t.r() < 0.5) {
+                t.set(x, y + 1, [c[0] * 0.8, c[1] * 0.8, c[2] * 0.8]);
+            }
+        }
+    },
+    bedrock: (t) => {
+        t.fill([86, 86, 86], 26);
+        for (let k = 0; k < 12; k++) {
+            const x = t.ri(16), y = t.ri(16), c = t.r() < 0.5 ? [36, 36, 36] : [146, 146, 146];
+            t.rect(x, y, 1 + t.ri(3), 1 + t.ri(2), c, 6);
+        }
+    },
+    log_side: paintLogSide,
+    log_top: paintLogTop,
+    planks: (t) => paintPlanks(t),
+    leaves: paintLeaves,
+    glass: paintGlass,
+    coal_ore: (t) => paintOre(t, [36, 36, 40], 5),
+    iron_ore: (t) => paintOre(t, [214, 172, 140], 4),
+    gold_ore: (t) => paintOre(t, [250, 218, 60], 4),
+    crystal_ore: (t) => paintOre(t, [96, 232, 228], 3),
+    clay: (t) => {
+        t.fill([160, 166, 180], 4);
+        for (let k = 0; k < 14; k++) {
+            t.set(t.ri(16), t.ri(16), t.vary([146, 152, 168], 3));
+        }
+    },
+    bricks: paintBricks,
+    stone_bricks: paintStoneBricks,
+    slab_top: (t) => paintSmoothStone(t, false),
+    slab_side: (t) => paintSmoothStone(t, true),
+    torch: paintTorch,
+    workbench_top: (t) => paintWorkbench(t, "top"),
+    workbench_side: (t) => paintWorkbench(t, "side"),
+    workbench_front: (t) => paintWorkbench(t, "front"),
+    furnace_side: paintFurnaceSide,
+    furnace_top: (t) => {
+        t.fill([132, 132, 132], 5);
+        t.border([92, 92, 92], 3);
+    },
+    furnace_front: (t) => paintFurnaceFront(t, false),
+    furnace_front_lit: (t) => paintFurnaceFront(t, true),
+    chest_top: (t) => paintChest(t, "top"),
+    chest_side: (t) => paintChest(t, "side"),
+    chest_front: (t) => paintChest(t, "front"),
+    tall_grass: (t) => paintGrassBlades(t, true),
+    flower_yellow: (t) => paintFlower(t, [250, 216, 40], [226, 140, 20]),
+    flower_red: (t) => paintFlower(t, [214, 36, 40], [96, 12, 12]),
+    mushroom_brown: (t) => paintMushroom(t, [150, 110, 80], false),
+    mushroom_red: (t) => paintMushroom(t, [204, 40, 32], true),
+    cactus_side: (t) => paintCactus(t, "side"),
+    cactus_top: (t) => paintCactus(t, "top"),
+    cactus_bottom: (t) => paintCactus(t, "bottom"),
+    reeds: paintReeds,
+    farmland_dry: (t) => paintFarmland(t, false),
+    farmland_wet: (t) => paintFarmland(t, true),
+    sapling: paintSapling,
+    dead_bush: paintDeadBush,
+    water: paintWater,
+    ladder: paintLadder,
+    iron_block: (t) => paintMetal(t, [216, 216, 220], [168, 168, 172], [150, 150, 156]),
+    gold_block: (t) => paintMetal(t, [250, 212, 70], [204, 152, 30], [190, 140, 26]),
+    crystal_block: paintCrystalBlock,
+    lamp: paintLamp,
+
+    //Items
+    stick: paintStick,
+    coal: paintCoal,
+    iron_ingot: (t) => paintIngot(t, [206, 206, 212]),
+    gold_ingot: (t) => paintIngot(t, [240, 196, 50]),
+    brick: (t) => paintIngot(t, [168, 82, 60]),
+    crystal: paintCrystal,
+    flint: paintFlint,
+    clay_ball: paintClayBall,
+    seeds: paintSeeds,
+    wheat_item: paintWheatItem,
+    bread: paintBread,
+    apple: paintApple,
+    bowl: (t) => paintBowl(t, false),
+    stew: (t) => paintBowl(t, true),
+    bucket: (t) => paintBucket(t, false),
+    water_bucket: (t) => paintBucket(t, true)
+};
+
+for (let s = 0; s < 8; s++) {
+    PAINTERS["wheat_" + s] = (t) => paintWheat(t, s);
+}
+
+export const TOOL_MATERIALS = [
+    { key: "wood", color: [150, 112, 64] },
+    { key: "stone", color: [128, 128, 128] },
+    { key: "iron", color: [212, 212, 218] },
+    { key: "gold", color: [244, 204, 60] },
+    { key: "crystal", color: [96, 226, 220] }
+];
+export const TOOL_KINDS = ["pickaxe", "axe", "shovel", "hoe"];
+
+for (const m of TOOL_MATERIALS) {
+    for (const k of TOOL_KINDS) {
+        PAINTERS[m.key + "_" + k] = (t) => paintTool(t, k, m.color);
+    }
+}
+
+for (let s = 0; s < 10; s++) {
+    PAINTERS["destroy_" + s] = null; //painted separately
+}
+
+//Tiles whose transparent pixels should not be colour-dilated (crisp items)
+function dilateTransparent(t) {
+    let sr = 0, sg = 0, sb = 0, n = 0;
+    for (let i = 0; i < S * S; i++) {
+        if (t.d[i * 4 + 3] > 0) {
+            sr += t.d[i * 4];
+            sg += t.d[i * 4 + 1];
+            sb += t.d[i * 4 + 2];
+            n++;
+        }
+    }
+    if (n === 0) {
+        return [0, 0, 0];
+    }
+    const avg = [sr / n, sg / n, sb / n];
+    for (let i = 0; i < S * S; i++) {
+        if (t.d[i * 4 + 3] === 0) {
+            t.d[i * 4] = avg[0];
+            t.d[i * 4 + 1] = avg[1];
+            t.d[i * 4 + 2] = avg[2];
+        }
+    }
+    return avg;
+}
+
+function tileToCanvas(d) {
+    const c = document.createElement("canvas");
+    c.width = S;
+    c.height = S;
+    const ctx = c.getContext("2d");
+    const img = ctx.createImageData(S, S);
+    img.data.set(d);
+    ctx.putImageData(img, 0, 0);
+    return c;
+}
+
+export function buildTextures() {
+    const names = Object.keys(PAINTERS);
+    const layers = new Uint8Array(names.length * S * S * 4);
+    const layerOf = new Map();
+    const canvases = new Map();
+    const avgColor = new Map();
+    names.forEach((name, i) => {
+        let t;
+        if (name.startsWith("destroy_")) {
+            t = paintCracks(Number(name.slice(8)));
+        } else {
+            let seed = 0;
+            for (let k = 0; k < name.length; k++) {
+                seed = (Math.imul(seed, 31) + name.charCodeAt(k)) | 0;
+            }
+            t = new Tile(seed);
+            PAINTERS[name](t);
+        }
+        //Keep an undilated copy for icons (transparent pixels stay clear)
+        canvases.set(name, tileToCanvas(t.d));
+        avgColor.set(name, dilateTransparent(t));
+        layers.set(t.d, i * S * S * 4);
+        layerOf.set(name, i);
+    });
+    return { names, layers, layerOf, canvases, avgColor, count: names.length };
+}
+
+/* ------------------------------------------------------------------ */
+/* Inventory icons                                                     */
+/* ------------------------------------------------------------------ */
+
+export const ICON = 64;
+
+function shadedTile(src, shade, tint) {
+    const c = document.createElement("canvas");
+    c.width = S;
+    c.height = S;
+    const ctx = c.getContext("2d");
+    ctx.drawImage(src, 0, 0);
+    if (tint || shade !== 1) {
+        const img = ctx.getImageData(0, 0, S, S);
+        const k = tint || [1, 1, 1];
+        for (let i = 0; i < S * S; i++) {
+            img.data[i * 4] *= k[0] * shade;
+            img.data[i * 4 + 1] *= k[1] * shade;
+            img.data[i * 4 + 2] *= k[2] * shade;
+        }
+        ctx.putImageData(img, 0, 0);
+    }
+    return c;
+}
+
+//Draw one isometric block (or slab) icon at (ox, oy) on ctx
+export function drawIsoIcon(ctx, ox, oy, tiles, opts = {}) {
+    const half = !!opts.half;
+    const sc = 0.86;
+    const off = (1 - sc) * ICON / 2;
+    const tf = (a, b, c, d, e, f) => {
+        ctx.setTransform(a * sc, b * sc, c * sc, d * sc, ox + e * sc + off, oy + f * sc + off);
+    };
+    const dy = half ? 16 : 0;
+    ctx.imageSmoothingEnabled = false;
+    //Top face
+    tf(2, -1, 2, 1, 0, 16 + dy);
+    ctx.drawImage(shadedTile(tiles.top, 1, opts.topTint), 0, 0);
+    //Left (front-left) face
+    tf(2, 1, 0, 2, 0, 16 + dy);
+    if (half) {
+        ctx.drawImage(shadedTile(tiles.left, 0.78, opts.sideTint), 0, 8, 16, 8, 0, 0, 16, 8);
+    } else {
+        ctx.drawImage(shadedTile(tiles.left, 0.78, opts.sideTint), 0, 0);
+    }
+    //Right (front-right) face
+    tf(2, -1, 0, 2, 32, 32 + dy);
+    if (half) {
+        ctx.drawImage(shadedTile(tiles.right, 0.6, opts.sideTint), 0, 8, 16, 8, 0, 0, 16, 8);
+    } else {
+        ctx.drawImage(shadedTile(tiles.right, 0.6, opts.sideTint), 0, 0);
+    }
+    ctx.setTransform(1, 0, 0, 1, 0, 0);
+}
+
+export function drawFlatIcon(ctx, ox, oy, tile, tint) {
+    ctx.imageSmoothingEnabled = false;
+    ctx.drawImage(shadedTile(tile, 1, tint), ox + 4, oy + 4, ICON - 8, ICON - 8);
+}

+ 155 - 0
src/web/Blocky/js/touch.js

@@ -0,0 +1,155 @@
+/*
+    Blocky - touch.js
+
+    On-screen controls for phones and tablets: a movement stick on the
+    left, drag anywhere on the right to look, tap to place / use, press and
+    hold to mine, plus jump, sneak, inventory and pause buttons. The hotbar
+    can be tapped directly.
+*/
+
+export function setupTouch(app) {
+    const input = app.input;
+    const stick = document.getElementById("stick");
+    const knob = document.getElementById("stickKnob");
+    const pad = document.getElementById("lookpad");
+    let stickId = null, sx = 0, sy = 0;
+
+    stick.addEventListener("touchstart", (e) => {
+        const t = e.changedTouches[0];
+        stickId = t.identifier;
+        const r = stick.getBoundingClientRect();
+        sx = r.left + r.width / 2;
+        sy = r.top + r.height / 2;
+        e.preventDefault();
+    }, { passive: false });
+    stick.addEventListener("touchmove", (e) => {
+        for (const t of e.changedTouches) {
+            if (t.identifier !== stickId) {
+                continue;
+            }
+            let dx = t.clientX - sx, dy = t.clientY - sy;
+            const len = Math.hypot(dx, dy), max = 50;
+            if (len > max) {
+                dx = dx / len * max;
+                dy = dy / len * max;
+            }
+            knob.style.transform = `translate(${dx}px, ${dy}px)`;
+            input.touchMove.forward = -dy / max;
+            input.touchMove.strafe = dx / max;
+        }
+        e.preventDefault();
+    }, { passive: false });
+    const endStick = (e) => {
+        for (const t of e.changedTouches) {
+            if (t.identifier === stickId) {
+                stickId = null;
+                knob.style.transform = "";
+                input.touchMove.forward = 0;
+                input.touchMove.strafe = 0;
+            }
+        }
+    };
+    stick.addEventListener("touchend", endStick);
+    stick.addEventListener("touchcancel", endStick);
+
+    let lookId = null, lx = 0, ly = 0, moved = 0, holdTimer = null, startT = 0;
+    pad.addEventListener("touchstart", (e) => {
+        const t = e.changedTouches[0];
+        lookId = t.identifier;
+        lx = t.clientX;
+        ly = t.clientY;
+        moved = 0;
+        startT = performance.now();
+        holdTimer = setTimeout(() => {
+            if (app.game && moved < 12) {
+                app.game.touchBreak = true;
+            }
+        }, 280);
+        e.preventDefault();
+    }, { passive: false });
+    pad.addEventListener("touchmove", (e) => {
+        for (const t of e.changedTouches) {
+            if (t.identifier !== lookId) {
+                continue;
+            }
+            const dx = t.clientX - lx, dy = t.clientY - ly;
+            lx = t.clientX;
+            ly = t.clientY;
+            moved += Math.abs(dx) + Math.abs(dy);
+            if (app.game) {
+                const s = 0.006 * app.settings.sensitivity;
+                const cur = app.game.touchLook || [0, 0];
+                app.game.touchLook = [cur[0] + dx * s, cur[1] + dy * s];
+            }
+        }
+        e.preventDefault();
+    }, { passive: false });
+    const endLook = (e) => {
+        for (const t of e.changedTouches) {
+            if (t.identifier !== lookId) {
+                continue;
+            }
+            clearTimeout(holdTimer);
+            lookId = null;
+            if (app.game) {
+                if (!app.game.touchBreak && moved < 12 && performance.now() - startT < 280) {
+                    app.game.touchUse = true;
+                }
+                app.game.touchBreak = false;
+            }
+        }
+    };
+    pad.addEventListener("touchend", endLook);
+    pad.addEventListener("touchcancel", endLook);
+
+    const hold = (id, on, off) => {
+        const el = document.getElementById(id);
+        el.addEventListener("touchstart", (e) => {
+            on();
+            e.preventDefault();
+        }, { passive: false });
+        el.addEventListener("touchend", (e) => {
+            off();
+            e.preventDefault();
+        }, { passive: false });
+    };
+    let lastJump = 0;
+    hold("tJump", () => {
+        input.touchJump = true;
+        const now = performance.now();
+        if (now - lastJump < 300 && app.game && app.game.creative) {
+            app.game.player.flying = !app.game.player.flying;
+        }
+        lastJump = now;
+    }, () => {
+        input.touchJump = false;
+    });
+    hold("tSneak", () => {
+        input.touchSneak = !input.touchSneak;
+        document.getElementById("tSneak").classList.toggle("on", input.touchSneak);
+    }, () => {});
+    hold("tInv", () => {
+        if (!app.game) {
+            return;
+        }
+        if (app.ui.isOpen()) {
+            app.game.closeScreen();
+        } else {
+            app.game.openScreen("inventory");
+        }
+    }, () => {});
+    hold("tPause", () => {
+        if (app.game && !app.game.paused) {
+            app.pause();
+        }
+    }, () => {});
+
+    //Hotbar taps
+    document.getElementById("hotbar").addEventListener("touchstart", (e) => {
+        const slot = e.target.closest(".slot");
+        if (slot && app.game) {
+            app.game.inventory.selected = Number(slot.dataset.ref.split(":")[1]);
+            e.preventDefault();
+        }
+    }, { passive: false });
+}

+ 820 - 0
src/web/Blocky/js/ui.js

@@ -0,0 +1,820 @@
+/*
+    Blocky - ui.js
+
+    The in-game HTML layer: the HUD (hotbar, health, food, air) and the
+    container screens (inventory with hand crafting, workbench, furnace,
+    chest, creative palette) with the usual slot mouse handling:
+
+        left click      pick up / put down / swap / merge a stack
+        right click     pick up half / put down one
+        shift click     move the stack to the other part of the screen
+        1-9 over a slot swap it with that hotbar slot
+*/
+
+import { ITEMS, RECIPES, SMELTING, SMELT_TICKS, fuelTicks, itemName, creativeGroups, matchRecipe, recipeLayout } from "./blocks.js";
+import { iconCss } from "./icons.js";
+import { maxStack, cloneStack, recipesFor } from "./inventory.js";
+import { escapeHtml } from "./util.js";
+
+const svgUrl = (svg) => `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
+const HEART = "M9 14.6C9 14.6 1.4 9.9 1.4 5.4C1.4 3.2 3.1 1.5 5.2 1.5C6.8 1.5 8.2 2.5 9 3.9C9.8 2.5 11.2 1.5 12.8 1.5C14.9 1.5 16.6 3.2 16.6 5.4C16.6 9.9 9 14.6 9 14.6Z";
+const LOAF = "M1.8 13.4L1.8 10.2C1.8 6.3 5 3.6 9 3.6C13 3.6 16.2 6.3 16.2 10.2L16.2 13.4Z";
+
+function iconSvg(path, full, empty, stroke, extra = "") {
+    const make = (fill, defs = "") => `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 16'>${defs}<path d='${path}' fill='${fill}' stroke='${stroke}' stroke-width='1.3' stroke-linejoin='round'/>${extra}</svg>`;
+    return {
+        full: svgUrl(make(full)),
+        half: svgUrl(make("url(#g)", `<defs><linearGradient id='g'><stop offset='0.5' stop-color='${full}'/><stop offset='0.5' stop-color='${empty}'/></linearGradient></defs>`)),
+        empty: svgUrl(make(empty))
+    };
+}
+
+const HEART_ICONS = iconSvg(HEART, "#e0302c", "#3a1414", "#1c0404", "<path d='M4 4.6C4.6 3.6 5.6 3.3 6.4 3.6' stroke='#ffb0a8' stroke-width='1.2' fill='none' stroke-linecap='round'/>");
+const FOOD_ICONS = iconSvg(LOAF, "#d8913e", "#3b2a18", "#2a1606", "<path d='M6 6.6L7.4 8.6M9 5.7L10.4 7.8M12 6.5L13.2 8.4' stroke='#8a5418' stroke-width='1.1'/>");
+const BUBBLE = svgUrl("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 16'><circle cx='9' cy='8' r='5.8' fill='#86bdfd' fill-opacity='0.55' stroke='#eaf5ff' stroke-width='1.3'/><path d='M6 6.4C6.6 5.4 7.6 5 8.4 5.2' stroke='#ffffff' stroke-width='1.2' fill='none' stroke-linecap='round'/></svg>");
+
+export class UI {
+    constructor(app) {
+        this.app = app;
+        this.icons = app.icons;
+        this.cursor = null;
+        this.screen = null;
+        this.hover = null;
+        this.hudKey = "";
+        this.creativeTab = 0;
+        this.onlyCraftable = false;
+        this.showBook = true;
+        try {
+            this.showBook = localStorage.getItem("blocky.book") !== "0";
+        } catch (e) {
+            //Default to showing the book
+        }
+        this.buildHud();
+        this.bindScreen();
+    }
+
+    get game() {
+        return this.app.game;
+    }
+
+    /* ---------------- shared slot rendering ---------------- */
+
+    slotHtml(ref, extraClass = "") {
+        return `<div class="slot ${extraClass}" data-ref="${ref}"><div class="ic"></div><span class="cnt"></span><div class="dura"><i></i></div></div>`;
+    }
+
+    renderSlot(el, stack, size = 36) {
+        const ic = el.firstElementChild;
+        const cnt = ic.nextElementSibling;
+        const dura = cnt.nextElementSibling;
+        if (!stack) {
+            ic.style.cssText = "background:none;";
+            cnt.textContent = "";
+            dura.style.display = "none";
+            return;
+        }
+        ic.style.cssText = iconCss(this.icons, stack.id, size);
+        cnt.textContent = stack.count > 1 ? String(stack.count) : "";
+        const it = ITEMS[stack.id];
+        if (it && it.tool && stack.dmg > 0) {
+            const f = Math.max(0, 1 - stack.dmg / it.tool.durability);
+            dura.style.display = "block";
+            dura.firstElementChild.style.width = (f * 100) + "%";
+            dura.firstElementChild.style.background = `hsl(${Math.round(f * 120)}, 85%, 45%)`;
+        } else {
+            dura.style.display = "none";
+        }
+    }
+
+    /* ---------------- HUD ---------------- */
+
+    buildHud() {
+        const hotbar = document.getElementById("hotbar");
+        hotbar.innerHTML = "";
+        for (let i = 0; i < 9; i++) {
+            hotbar.insertAdjacentHTML("beforeend", this.slotHtml("hot:" + i));
+        }
+        this.hotbarEls = Array.from(hotbar.children);
+        const row = (id, cls) => {
+            const el = document.getElementById(id);
+            el.innerHTML = "";
+            for (let i = 0; i < 10; i++) {
+                el.insertAdjacentHTML("beforeend", `<span class="${cls}"></span>`);
+            }
+            return Array.from(el.children);
+        };
+        this.heartEls = row("hearts", "hp");
+        this.foodEls = row("foodbar", "fd");
+        this.airEls = row("airbar", "air");
+        this.hotbarEls.forEach((el, i) => {
+            el.addEventListener("mousedown", (e) => {
+                if (this.game && !this.screen) {
+                    this.game.inventory.selected = i;
+                    e.preventDefault();
+                }
+            });
+        });
+    }
+
+    updateHud(game) {
+        const p = game.player, inv = game.inventory;
+        const slots = inv.slots.slice(0, 9).map((s) => (s ? s.id + "x" + s.count + "d" + (s.dmg || 0) : "-")).join(",");
+        const key = [slots, inv.selected, game.creative, Math.ceil(p.health), Math.ceil(p.food), Math.ceil(p.air), p.headInWater, p.hurtTime > 0.25].join("|");
+        if (key === this.hudKey) {
+            return;
+        }
+        this.hudKey = key;
+        for (let i = 0; i < 9; i++) {
+            this.renderSlot(this.hotbarEls[i], inv.slots[i]);
+            this.hotbarEls[i].classList.toggle("sel", i === inv.selected);
+        }
+        const bars = document.getElementById("statusbars");
+        bars.classList.toggle("hidden", game.creative);
+        const hp = Math.ceil(p.health), fd = Math.ceil(p.food);
+        this.heartEls.forEach((el, i) => {
+            const v = hp - i * 2;
+            el.style.backgroundImage = v >= 2 ? HEART_ICONS.full : v === 1 ? HEART_ICONS.half : HEART_ICONS.empty;
+        });
+        document.getElementById("hearts").classList.toggle("blink", p.hurtTime > 0.25);
+        this.foodEls.forEach((el, i) => {
+            const v = fd - i * 2;
+            el.style.backgroundImage = v >= 2 ? FOOD_ICONS.full : v === 1 ? FOOD_ICONS.half : FOOD_ICONS.empty;
+        });
+        document.getElementById("foodbar").classList.toggle("starving", fd <= 6);
+        const showAir = p.headInWater || p.air < 15;
+        const airBar = document.getElementById("airbar");
+        airBar.classList.toggle("hidden", !showAir);
+        const bubbles = Math.ceil(Math.max(0, p.air) / 1.5);
+        this.airEls.forEach((el, i) => {
+            el.style.backgroundImage = i < bubbles ? BUBBLE : "none";
+        });
+    }
+
+    showItemName(id) {
+        const el = document.getElementById("itemName");
+        el.textContent = id ? itemName(id) : "";
+        el.classList.remove("fade");
+        void el.offsetWidth;
+        if (id) {
+            el.classList.add("fade");
+        }
+    }
+
+    toast(msg) {
+        const el = document.getElementById("message");
+        el.textContent = msg;
+        el.classList.remove("fade");
+        void el.offsetWidth;
+        el.classList.add("fade");
+    }
+
+    /* ---------------- screens ---------------- */
+
+    bindScreen() {
+        const panel = document.getElementById("screenPanel");
+        panel.addEventListener("mousedown", (e) => {
+            const slot = e.target.closest(".slot");
+            if (slot && panel.contains(slot)) {
+                e.preventDefault();
+                this.slotClick(slot.dataset.ref, e.button, e.shiftKey);
+                return;
+            }
+            const rec = e.target.closest(".recipe");
+            if (rec) {
+                e.preventDefault();
+                this.bookClick(RECIPES[Number(rec.dataset.r)], e.shiftKey);
+                return;
+            }
+            if (e.target.closest(".bookbtn")) {
+                e.preventDefault();
+                this.showBook = !this.showBook;
+                try {
+                    localStorage.setItem("blocky.book", this.showBook ? "1" : "0");
+                } catch (err) {
+                    //Only a convenience
+                }
+                this.renderScreen(true);
+                return;
+            }
+            const tab = e.target.closest(".tab");
+            if (tab) {
+                this.creativeTab = Number(tab.dataset.tab);
+                this.renderScreen(true);
+                return;
+            }
+            const pal = e.target.closest(".pal");
+            if (pal) {
+                e.preventDefault();
+                this.paletteClick(Number(pal.dataset.id), e.button, e.shiftKey);
+            }
+        });
+        panel.addEventListener("change", (e) => {
+            if (e.target.id === "onlyCraftable") {
+                this.onlyCraftable = e.target.checked;
+                this.renderScreen(false);
+            }
+        });
+        panel.addEventListener("contextmenu", (e) => e.preventDefault());
+        panel.addEventListener("mouseover", (e) => {
+            const el = e.target.closest(".slot, .recipe, .pal");
+            this.hover = el && el.classList.contains("slot") ? el.dataset.ref : null;
+            this.showTooltip(el);
+        });
+        panel.addEventListener("mouseleave", () => {
+            this.hover = null;
+            this.showTooltip(null);
+        });
+        document.getElementById("screen").addEventListener("mousedown", (e) => {
+            //Clicking outside the panel throws the held stack
+            if (e.target.id === "screen" && this.cursor) {
+                const n = e.button === 2 ? 1 : this.cursor.count;
+                this.game.dropStack({ id: this.cursor.id, count: n, dmg: this.cursor.dmg });
+                this.cursor.count -= n;
+                if (this.cursor.count <= 0) {
+                    this.cursor = null;
+                }
+                this.renderCursor();
+            }
+        });
+        document.addEventListener("mousemove", (e) => {
+            this.mx = e.clientX;
+            this.my = e.clientY;
+            if (this.screen) {
+                const c = document.getElementById("cursorStack");
+                c.style.transform = `translate(${e.clientX - 20}px, ${e.clientY - 20}px)`;
+                const tip = document.getElementById("tooltip");
+                if (!tip.classList.contains("hidden")) {
+                    tip.style.transform = `translate(${e.clientX + 16}px, ${e.clientY - 8}px)`;
+                }
+            }
+        });
+    }
+
+    isOpen() {
+        return this.screen !== null;
+    }
+
+    open(kind, te = null) {
+        if (kind === "inventory" && this.game.creative) {
+            kind = "creative";
+        }
+        this.screen = { kind, te };
+        if (kind === "inventory" || kind === "workbench") {
+            const size = kind === "workbench" ? 3 : 2;
+            Object.assign(this.screen, { size, grid: new Array(size * size).fill(null), result: null, match: null });
+        }
+        document.getElementById("screen").classList.remove("hidden");
+        document.body.classList.add("screen-open");
+        this.renderScreen(true);
+    }
+
+    close() {
+        if (!this.screen) {
+            return;
+        }
+        if (this.screen.grid) {
+            this.returnGrid();
+        }
+        if (this.cursor) {
+            this.giveBack(this.cursor);
+            this.cursor = null;
+        }
+        this.screen = null;
+        this.renderCursor();
+        this.showTooltip(null);
+        document.getElementById("screen").classList.add("hidden");
+        document.body.classList.remove("screen-open");
+        this.hudKey = "";
+    }
+
+    invSection(title) {
+        let main = "", hot = "";
+        for (let i = 9; i < 36; i++) {
+            main += this.slotHtml("inv:" + i);
+        }
+        for (let i = 0; i < 9; i++) {
+            hot += this.slotHtml("inv:" + i);
+        }
+        return `<h3>${title}</h3><div class="slots grid9">${main}</div><div class="slots grid9 hotrow">${hot}</div>`;
+    }
+
+    renderScreen(rebuild) {
+        const s = this.screen;
+        if (!s) {
+            return;
+        }
+        const panel = document.getElementById("screenPanel");
+        if (rebuild) {
+            let html = "";
+            if (s.kind === "creative") {
+                const groups = creativeGroups();
+                const tabs = groups.map((g, i) => `<button class="tab ${i === this.creativeTab ? "on" : ""}" data-tab="${i}">${g.name}</button>`).join("");
+                const pal = groups[this.creativeTab].ids.map((id) => `<div class="pal" data-id="${id}"><div class="ic" style="${iconCss(this.icons, id, 36)}"></div></div>`).join("");
+                html = `<div class="scr-col wide"><div class="tabs">${tabs}</div><div class="palette">${pal}</div>
+                    ${this.invSection("Inventory")}<div class="trashrow"><span>Drop an item on the bin to delete it</span>${this.slotHtml("trash", "trash")}</div></div>`;
+            } else if (s.kind === "furnace") {
+                html = `<div class="scr-col"><h3>Furnace</h3><div class="furnace">
+                    <div class="fcol">${this.slotHtml("te:0")}<div class="flame"><i></i></div>${this.slotHtml("te:1")}</div>
+                    <div class="arrow"><i></i></div>${this.slotHtml("te:2", "big")}</div>
+                    ${this.invSection("Inventory")}</div>`;
+            } else if (s.kind === "chest") {
+                let cs = "";
+                for (let i = 0; i < 27; i++) {
+                    cs += this.slotHtml("te:" + i);
+                }
+                html = `<div class="scr-col"><h3>Chest</h3><div class="slots grid9">${cs}</div>${this.invSection("Inventory")}</div>`;
+            } else {
+                const bench = s.kind === "workbench";
+                let cells = "";
+                for (let i = 0; i < s.size * s.size; i++) {
+                    cells += this.slotHtml("craft:" + i);
+                }
+                const hint = bench
+                    ? "Click a recipe to lay it out on the grid; shift click lays out as many as you can."
+                    : "Click a recipe to lay it out. Bigger recipes need the 3 x 3 grid of a workbench.";
+                html = `<div class="scr-col">
+                    <h3>${bench ? "Workbench" : "Crafting"}<button class="bookbtn ${this.showBook ? "on" : ""}" title="Show or hide the recipe book">Recipe book</button></h3>
+                    <div class="craftrow"><div class="cgrid s${s.size}">${cells}</div><div class="arrow"><i></i></div>${this.slotHtml("result", "big result")}</div>
+                    ${this.invSection("Inventory")}</div>
+                    <div class="scr-col book ${this.showBook ? "" : "hidden"}"><h3>Recipes
+                    <label class="onlycan"><input type="checkbox" id="onlyCraftable" ${this.onlyCraftable ? "checked" : ""}> Only what I can make</label></h3>
+                    <div class="recipes"></div><p class="hint">${hint}</p></div>`;
+            }
+            panel.innerHTML = html;
+            panel.className = "panel kind-" + s.kind;
+        }
+        if (s.grid) {
+            this.updateResult();
+            panel.querySelector(".craftrow .arrow").classList.toggle("ready", !!s.result);
+        }
+        //Slots
+        panel.querySelectorAll(".slot").forEach((el) => {
+            this.renderSlot(el, this.getStack(el.dataset.ref));
+        });
+        const book = panel.querySelector(".book .recipes");
+        if (book && this.showBook) {
+            this.renderRecipes(book, s.size);
+        }
+        if (s.kind === "furnace") {
+            const te = s.te;
+            panel.querySelector(".arrow i").style.width = Math.round((te.cook / SMELT_TICKS) * 100) + "%";
+            panel.querySelector(".flame i").style.height = te.burnMax > 0 ? Math.round((te.burn / te.burnMax) * 100) + "%" : "0%";
+        }
+        this.renderCursor();
+    }
+
+    //How many of an item the player can use: inventory plus the grid
+    available(id) {
+        let n = this.game.inventory.count(id);
+        for (const st of this.screen.grid || []) {
+            if (st && st.id === id) {
+                n += st.count;
+            }
+        }
+        return n;
+    }
+
+    renderRecipes(box, size) {
+        const creative = this.game.creative;
+        const list = recipesFor(size).map((r) => ({
+            r, idx: RECIPES.indexOf(r), can: creative || r.inputs.every(([id, n]) => this.available(id) >= n)
+        }));
+        list.sort((a, b) => (b.can - a.can));
+        const mini = (id) => `<i class="ic" style="${iconCss(this.icons, id, 16)}"></i>`;
+        let html = "";
+        for (const { r, idx, can } of list) {
+            if (this.onlyCraftable && !can) {
+                continue;
+            }
+            let pattern;
+            if (r.items) {
+                pattern = `<div class="loose">${r.items.map((id) => `<b>${mini(id)}</b>`).join("")}<span>any layout</span></div>`;
+            } else {
+                let cells = "";
+                for (const row of r.shape) {
+                    for (const ch of row) {
+                        cells += ch === "." ? "<b></b>" : `<b>${mini(r.key[ch])}</b>`;
+                    }
+                }
+                pattern = `<div class="pattern" style="grid-template-columns:repeat(${r.w}, 18px)">${cells}</div>`;
+            }
+            html += `<div class="recipe ${can ? "can" : ""}" data-r="${idx}"><div class="ic" style="${iconCss(this.icons, r.out, 36)}"></div>
+                <div class="rinfo"><b>${escapeHtml(itemName(r.out))}${r.count > 1 ? " x" + r.count : ""}</b>${pattern}</div></div>`;
+        }
+        if (!html) {
+            html = "<p class=\"hint\">Nothing you can make right now.</p>";
+        }
+        box.innerHTML = html;
+    }
+
+    renderCursor() {
+        const el = document.getElementById("cursorStack");
+        if (!this.cursor || !this.screen) {
+            el.classList.add("hidden");
+            return;
+        }
+        el.classList.remove("hidden");
+        el.innerHTML = `<div class="ic" style="${iconCss(this.icons, this.cursor.id, 36)}"></div><span class="cnt">${this.cursor.count > 1 ? this.cursor.count : ""}</span>`;
+        el.style.transform = `translate(${(this.mx || 0) - 20}px, ${(this.my || 0) - 20}px)`;
+    }
+
+    showTooltip(el) {
+        const tip = document.getElementById("tooltip");
+        let id = 0;
+        if (el) {
+            if (el.classList.contains("slot")) {
+                const st = this.getStack(el.dataset.ref);
+                id = st ? st.id : 0;
+                if (el.dataset.ref === "trash") {
+                    tip.textContent = "Delete";
+                    tip.classList.remove("hidden");
+                    return;
+                }
+            } else if (el.classList.contains("recipe")) {
+                id = RECIPES[Number(el.dataset.r)].out;
+            } else {
+                id = Number(el.dataset.id);
+            }
+        }
+        if (!id || this.mx === undefined) {
+            tip.classList.add("hidden");
+            return;
+        }
+        const it = ITEMS[id];
+        let text = itemName(id);
+        if (it && it.food) {
+            text += ` (restores ${it.food.hunger / 2} food)`;
+        }
+        if (it && it.tool) {
+            const st = el.classList.contains("slot") ? this.getStack(el.dataset.ref) : null;
+            const left = it.tool.durability - ((st && st.dmg) || 0);
+            text += ` (${left}/${it.tool.durability})`;
+        }
+        if (SMELTING.has(id) && this.screen && this.screen.kind === "furnace") {
+            text += " - smelts into " + itemName(SMELTING.get(id));
+        }
+        tip.textContent = text;
+        tip.classList.remove("hidden");
+        tip.style.transform = `translate(${(this.mx || 0) + 16}px, ${(this.my || 0) - 8}px)`;
+    }
+
+    /* ---------------- slot logic ---------------- */
+
+    getStack(ref) {
+        const [kind, n] = ref.split(":");
+        const s = this.screen;
+        if (kind === "inv" || kind === "hot") {
+            return this.game.inventory.slots[Number(n)];
+        }
+        if (kind === "te" && s && s.te) {
+            return s.te.slots[Number(n)];
+        }
+        if (kind === "craft" && s && s.grid) {
+            return s.grid[Number(n)];
+        }
+        if (kind === "result" && s) {
+            return s.result || null;
+        }
+        return null;
+    }
+
+    setStack(ref, stack) {
+        const [kind, n] = ref.split(":");
+        if (stack && stack.count <= 0) {
+            stack = null;
+        }
+        if (kind === "inv") {
+            this.game.inventory.slots[Number(n)] = stack;
+        } else if (kind === "te" && this.screen && this.screen.te) {
+            this.screen.te.slots[Number(n)] = stack;
+        } else if (kind === "craft" && this.screen && this.screen.grid) {
+            this.screen.grid[Number(n)] = stack;
+        }
+    }
+
+    /* ---------------- crafting grid ---------------- */
+
+    //Put a stack back into the inventory, dropping what does not fit
+    giveBack(stack) {
+        const left = this.game.inventory.add(stack.id, stack.count, stack.dmg || 0);
+        if (left > 0) {
+            this.game.dropStack({ id: stack.id, count: left, dmg: stack.dmg });
+        }
+    }
+
+    returnGrid() {
+        const g = this.screen.grid;
+        for (let i = 0; i < g.length; i++) {
+            if (g[i]) {
+                this.giveBack(g[i]);
+                g[i] = null;
+            }
+        }
+        this.updateResult();
+    }
+
+    updateResult() {
+        const s = this.screen;
+        if (!s || !s.grid) {
+            return;
+        }
+        const r = matchRecipe(s.grid.map((st) => (st ? st.id : 0)), s.size);
+        s.match = r;
+        s.result = r ? { id: r.out, count: r.count, dmg: 0 } : null;
+    }
+
+    //Use up one item from every filled grid cell
+    consumeGrid() {
+        const g = this.screen.grid;
+        for (let i = 0; i < g.length; i++) {
+            if (g[i]) {
+                g[i].count--;
+                if (g[i].count <= 0) {
+                    g[i] = null;
+                }
+            }
+        }
+        this.updateResult();
+    }
+
+    //Click on the result slot (shift: craft as many as the grid allows)
+    takeResult(shift) {
+        const s = this.screen;
+        const r = s.match;
+        if (!r) {
+            return;
+        }
+        if (shift) {
+            for (let n = 0; n < 64 && s.match === r; n++) {
+                const left = this.game.inventory.add(r.out, r.count);
+                this.consumeGrid();
+                if (left > 0) {
+                    this.game.dropStack({ id: r.out, count: left });
+                    break;
+                }
+            }
+        } else {
+            if (this.cursor && (this.cursor.id !== r.out || this.cursor.count + r.count > maxStack(r.out))) {
+                return;
+            }
+            if (this.cursor) {
+                this.cursor.count += r.count;
+            } else {
+                this.cursor = { id: r.out, count: r.count, dmg: 0 };
+            }
+            this.consumeGrid();
+        }
+        this.game.sound.play("click");
+    }
+
+    //Lay a recipe out on the grid from the inventory (shift: as many as possible)
+    bookClick(r, shift) {
+        const s = this.screen;
+        if (!s || !s.grid) {
+            return;
+        }
+        if (!r.small && s.size < 3) {
+            this.toast("That recipe needs a workbench");
+            return;
+        }
+        const inv = this.game.inventory;
+        const creative = this.game.creative;
+        const layout = recipeLayout(r, s.size);
+        const same = s.grid.every((st, i) => (st ? st.id : 0) === layout[i]);
+        if (!same) {
+            this.returnGrid();
+        }
+        let placed = 0;
+        for (let k = 0; k < (shift ? 64 : 1); k++) {
+            if (!creative && !r.inputs.every(([id, n]) => inv.count(id) >= n)) {
+                break;
+            }
+            if (layout.some((id, i) => id && s.grid[i] && s.grid[i].count >= maxStack(id))) {
+                break;
+            }
+            layout.forEach((id, i) => {
+                if (!id) {
+                    return;
+                }
+                if (!creative) {
+                    inv.remove(id, 1);
+                }
+                if (s.grid[i]) {
+                    s.grid[i].count++;
+                } else {
+                    s.grid[i] = { id, count: 1, dmg: 0 };
+                }
+            });
+            placed++;
+        }
+        if (!placed) {
+            this.toast("You are missing some ingredients");
+        }
+        this.after();
+        this.game.sound.play("click");
+    }
+
+    accepts(ref, stack) {
+        if (!stack) {
+            return true;
+        }
+        if (ref === "result") {
+            return false;
+        }
+        if (this.screen && this.screen.kind === "furnace" && ref.startsWith("te:")) {
+            const n = Number(ref.slice(3));
+            if (n === 2) {
+                return false;
+            }
+            if (n === 1) {
+                return fuelTicks(stack.id) > 0;
+            }
+        }
+        return true;
+    }
+
+    slotClick(ref, button, shift) {
+        const game = this.game;
+        if (ref === "trash") {
+            this.cursor = null;
+            this.renderScreen(false);
+            return;
+        }
+        if (ref === "result") {
+            this.takeResult(shift);
+            this.after();
+            return;
+        }
+        if (shift && !this.cursor) {
+            this.quickMove(ref);
+            this.after();
+            return;
+        }
+        const slot = this.getStack(ref);
+        const max = (id) => maxStack(id);
+        const output = this.screen.kind === "furnace" && ref === "te:2";
+        if (output) {
+            if (!slot) {
+                return;
+            }
+            if (!this.cursor) {
+                this.cursor = slot;
+                this.setStack(ref, null);
+            } else if (this.cursor.id === slot.id && this.cursor.count + slot.count <= max(slot.id)) {
+                this.cursor.count += slot.count;
+                this.setStack(ref, null);
+            }
+            this.after();
+            return;
+        }
+        if (button === 0) {
+            if (!this.cursor) {
+                if (slot) {
+                    this.cursor = slot;
+                    this.setStack(ref, null);
+                }
+            } else if (!slot) {
+                if (this.accepts(ref, this.cursor)) {
+                    this.setStack(ref, this.cursor);
+                    this.cursor = null;
+                }
+            } else if (slot.id === this.cursor.id && max(slot.id) > 1 && (slot.dmg || 0) === (this.cursor.dmg || 0)) {
+                const n = Math.min(this.cursor.count, max(slot.id) - slot.count);
+                slot.count += n;
+                this.cursor.count -= n;
+                if (this.cursor.count <= 0) {
+                    this.cursor = null;
+                }
+            } else if (this.accepts(ref, this.cursor)) {
+                this.setStack(ref, this.cursor);
+                this.cursor = slot;
+            }
+        } else if (button === 2) {
+            if (!this.cursor) {
+                if (slot) {
+                    const half = Math.ceil(slot.count / 2);
+                    this.cursor = { id: slot.id, count: half, dmg: slot.dmg || 0 };
+                    slot.count -= half;
+                    if (slot.count <= 0) {
+                        this.setStack(ref, null);
+                    }
+                }
+            } else if (this.accepts(ref, this.cursor)) {
+                if (!slot) {
+                    this.setStack(ref, { id: this.cursor.id, count: 1, dmg: this.cursor.dmg || 0 });
+                    this.cursor.count--;
+                } else if (slot.id === this.cursor.id && slot.count < max(slot.id)) {
+                    slot.count++;
+                    this.cursor.count--;
+                }
+                if (this.cursor.count <= 0) {
+                    this.cursor = null;
+                }
+            }
+        }
+        this.after();
+        if (game) {
+            game.sound.play("click");
+        }
+    }
+
+    //Put a stack into the given refs (merge first, then empty slots)
+    moveInto(stack, refs) {
+        const max = maxStack(stack.id);
+        if (max > 1) {
+            for (const r of refs) {
+                const s = this.getStack(r);
+                if (s && s.id === stack.id && s.count < max && (s.dmg || 0) === (stack.dmg || 0)) {
+                    const n = Math.min(stack.count, max - s.count);
+                    s.count += n;
+                    stack.count -= n;
+                    if (stack.count === 0) {
+                        return 0;
+                    }
+                }
+            }
+        }
+        for (const r of refs) {
+            if (!this.getStack(r) && this.accepts(r, stack)) {
+                this.setStack(r, { id: stack.id, count: stack.count, dmg: stack.dmg || 0 });
+                stack.count = 0;
+                return 0;
+            }
+        }
+        return stack.count;
+    }
+
+    quickMove(ref) {
+        const s = this.getStack(ref);
+        if (!s) {
+            return;
+        }
+        const range = (p, a, b) => {
+            const out = [];
+            for (let i = a; i < b; i++) {
+                out.push(p + i);
+            }
+            return out;
+        };
+        const kind = this.screen.kind;
+        const stack = cloneStack(s);
+        let targets;
+        if (ref.startsWith("te:") || ref.startsWith("craft:")) {
+            targets = range("inv:", 9, 36).concat(range("inv:", 0, 9));
+        } else if (kind === "chest") {
+            targets = range("te:", 0, 27);
+        } else if (kind === "furnace" && SMELTING.has(s.id)) {
+            targets = ["te:0"];
+        } else if (kind === "furnace" && fuelTicks(s.id) > 0) {
+            targets = ["te:1"];
+        } else {
+            const n = Number(ref.slice(4));
+            targets = n < 9 ? range("inv:", 9, 36) : range("inv:", 0, 9);
+        }
+        const left = this.moveInto(stack, targets);
+        if (left === 0) {
+            this.setStack(ref, null);
+        } else {
+            s.count = left;
+        }
+    }
+
+    paletteClick(id, button, shift) {
+        if (this.cursor && button === 0 && this.cursor.id !== id) {
+            this.cursor = null;
+        } else if (shift) {
+            this.game.inventory.add(id, maxStack(id));
+        } else if (this.cursor && this.cursor.id === id && button === 0) {
+            this.cursor.count = Math.min(maxStack(id), this.cursor.count + 1);
+        } else {
+            this.cursor = { id, count: button === 2 ? 1 : maxStack(id), dmg: 0 };
+        }
+        this.after();
+    }
+
+    hotkey(n) {
+        const h = this.hover;
+        if (!h || !(h.startsWith("inv:") || h.startsWith("te:") || h.startsWith("craft:"))) {
+            return false;
+        }
+        if (this.screen.kind === "furnace" && this.hover === "te:2") {
+            return false;
+        }
+        const a = this.getStack(this.hover);
+        const b = this.game.inventory.slots[n];
+        if (b && !this.accepts(this.hover, b)) {
+            return true;
+        }
+        this.game.inventory.slots[n] = a;
+        this.setStack(this.hover, b);
+        this.after();
+        return true;
+    }
+
+    after() {
+        this.hudKey = "";
+        this.renderScreen(false);
+        const el = this.hover && document.querySelector(`#screenPanel .slot[data-ref="${this.hover}"]`);
+        this.showTooltip(el || null);
+    }
+}

+ 143 - 0
src/web/Blocky/js/util.js

@@ -0,0 +1,143 @@
+/*
+    Blocky - util.js
+
+    Small shared helpers: seeded random numbers, integer hashing, maths and
+    base64 / run-length encoding used by the save format.
+*/
+
+//Seeded 32 bit PRNG (mulberry32). Returns a function giving [0, 1).
+export function mulberry32(seed) {
+    let a = seed | 0;
+    return function () {
+        a = (a + 0x6D2B79F5) | 0;
+        let t = Math.imul(a ^ (a >>> 15), 1 | a);
+        t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+        return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+    };
+}
+
+//Integer hash of (seed, x, z) to an unsigned 32 bit value
+export function hash2(seed, x, z) {
+    let h = (seed ^ Math.imul(x, 0x27d4eb2d) ^ Math.imul(z, 0x165667b1)) | 0;
+    h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
+    h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
+    return (h ^ (h >>> 16)) >>> 0;
+}
+
+export function hash3(seed, x, y, z) {
+    return hash2(hash2(seed, x, z), y, 0x5bd1e995);
+}
+
+//Turn whatever the player typed in the seed box into a 32 bit seed
+export function seedFromString(text) {
+    const s = String(text || "").trim();
+    if (s === "") {
+        return (Math.random() * 4294967296) | 0;
+    }
+    if (/^-?\d{1,10}$/.test(s)) {
+        return Number(s) | 0;
+    }
+    let h = 0;
+    for (let i = 0; i < s.length; i++) {
+        h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;
+    }
+    return h;
+}
+
+export const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
+export const lerp = (a, b, t) => a + (b - a) * t;
+
+export function smoothstep(e0, e1, x) {
+    const t = clamp((x - e0) / (e1 - e0), 0, 1);
+    return t * t * (3 - 2 * t);
+}
+
+//Numeric key for a chunk coordinate pair (Map lookups on numbers are cheap)
+export function chunkKey(cx, cz) {
+    return (cx + 32768) * 65536 + (cz + 32768);
+}
+
+export function keyToChunk(key) {
+    return [Math.floor(key / 65536) - 32768, (key % 65536) - 32768];
+}
+
+/* ---------- Byte helpers for the save format ---------- */
+
+export function bytesToBase64(bytes) {
+    let out = "";
+    const CHUNK = 0x8000;
+    for (let i = 0; i < bytes.length; i += CHUNK) {
+        out += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
+    }
+    return btoa(out);
+}
+
+export function base64ToBytes(b64) {
+    const bin = atob(b64);
+    const out = new Uint8Array(bin.length);
+    for (let i = 0; i < bin.length; i++) {
+        out[i] = bin.charCodeAt(i);
+    }
+    return out;
+}
+
+//Run-length encode two parallel byte arrays (block id + meta) as
+//[run length (1-255), id, meta] triples.
+export function rleEncode(a, b) {
+    const n = a.length;
+    const out = new Uint8Array(n * 3);
+    let o = 0;
+    let i = 0;
+    while (i < n) {
+        const va = a[i];
+        const vb = b[i];
+        let run = 1;
+        while (i + run < n && run < 255 && a[i + run] === va && b[i + run] === vb) {
+            run++;
+        }
+        out[o++] = run;
+        out[o++] = va;
+        out[o++] = vb;
+        i += run;
+    }
+    return out.slice(0, o);
+}
+
+export function rleDecode(bytes, a, b) {
+    let p = 0;
+    for (let i = 0; i + 2 < bytes.length; i += 3) {
+        const run = bytes[i];
+        const va = bytes[i + 1];
+        const vb = bytes[i + 2];
+        for (let k = 0; k < run && p < a.length; k++, p++) {
+            a[p] = va;
+            b[p] = vb;
+        }
+    }
+}
+
+//Deflate / inflate a string when the browser has CompressionStream
+export async function deflateString(text) {
+    const input = new TextEncoder().encode(text);
+    if (typeof CompressionStream === "undefined") {
+        return { encoding: "plain", data: bytesToBase64(input) };
+    }
+    const stream = new Blob([input]).stream().pipeThrough(new CompressionStream("deflate"));
+    const buf = new Uint8Array(await new Response(stream).arrayBuffer());
+    return { encoding: "deflate", data: bytesToBase64(buf) };
+}
+
+export async function inflateString(encoding, b64) {
+    const bytes = base64ToBytes(b64);
+    if (encoding !== "deflate") {
+        return new TextDecoder().decode(bytes);
+    }
+    const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate"));
+    return await new Response(stream).text();
+}
+
+export function escapeHtml(s) {
+    return String(s).replace(/[&<>"']/g, (c) => ({
+        "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;"
+    })[c]);
+}

+ 1286 - 0
src/web/Blocky/js/world.js

@@ -0,0 +1,1286 @@
+/*
+    Blocky - world.js
+
+    Chunk storage and the simulation of the block world:
+
+    - chunks are 16 x 128 x 16 columns (index (x << 11) | (z << 7) | y),
+      rendered as eight 16-high sections
+    - light: sky light and block light (0-15 each) packed in one byte per
+      voxel, filled by a breadth first flood when a chunk is first lit and
+      updated incrementally (removal + refill) when a block changes
+    - block updates: water flow, falling sand and gravel, plants and torches
+      losing their support, leaf decay, crop / reed / cactus growth, grass
+      spreading, furnaces
+    - save data: only chunks that changed are stored, run-length encoded
+
+    The world never touches the renderer; it raises dirty flags per section
+    and the renderer rebuilds what it needs.
+*/
+
+import {
+    B, BLOCKS, LIGHT_OPACITY, LIGHT_EMIT, SHAPE, SOLID, RAIN_BLOCKING, isOpaqueAt,
+    blockDrops, SMELTING, SMELT_TICKS, fuelTicks, ITEMS
+} from "./blocks.js";
+import { TerrainGen, WORLD_H, SEA, idx } from "./worldgen.js";
+import { chunkKey, rleEncode, rleDecode, bytesToBase64, base64ToBytes, mulberry32 } from "./util.js";
+import { FACE_DIR } from "./shapes.js";
+
+export const SECTIONS = WORLD_H / 16;
+
+const IS_SLAB = new Uint8Array(256);
+const WASHABLE = new Uint8Array(256);
+for (let i = 0; i < 256; i++) {
+    IS_SLAB[i] = SHAPE[i] === "slab" ? 1 : 0;
+    WASHABLE[i] = (SHAPE[i] === "cross" || SHAPE[i] === "crop" || SHAPE[i] === "torch") && i !== B.REEDS ? 1 : 0;
+}
+
+function opacityOf(id, meta) {
+    const o = LIGHT_OPACITY[id];
+    if (o === 0 && IS_SLAB[id] === 1 && meta === 2) {
+        return 15;
+    }
+    return o;
+}
+
+const DIRS = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
+
+export class Chunk {
+    constructor(cx, cz) {
+        this.cx = cx;
+        this.cz = cz;
+        this.key = chunkKey(cx, cz);
+        this.blocks = new Uint8Array(16 * 16 * WORLD_H);
+        this.meta = new Uint8Array(16 * 16 * WORLD_H);
+        this.light = new Uint8Array(16 * 16 * WORLD_H);
+        this.biome = new Uint8Array(256);
+        this.tint = new Float32Array(256 * 6);
+        this.hmLight = new Uint8Array(256);
+        this.hmRain = new Uint8Array(256);
+        this.generated = false;
+        this.lit = false;
+        this.modified = false;
+        this.dirty = new Uint8Array(SECTIONS).fill(1);
+        this.meshes = null; //owned by the renderer
+    }
+}
+
+export class World {
+    constructor(seed, opts = {}) {
+        this.seed = seed | 0;
+        this.gen = new TerrainGen(this.seed);
+        this.chunks = new Map();
+        this.saved = new Map();
+        this.tileEntities = new Map();
+        this.schedBuckets = new Map();
+        this.schedSet = new Set();
+        this.tickCount = 0;
+        this.rng = mulberry32(this.seed ^ 0x51ed);
+        this.lastChunk = null;
+        this.skyDarken = 0;
+        this.raining = false;
+        this.order = null;
+        this.orderKey = "";
+        //Callbacks wired up by the game
+        this.onDrop = opts.onDrop || null;
+        this.onFalling = opts.onFalling || null;
+        this.onBlockBroken = opts.onBlockBroken || null;
+    }
+
+    /* ---------------- chunk access ---------------- */
+
+    chunkAt(cx, cz) {
+        const lc = this.lastChunk;
+        if (lc !== null && lc.cx === cx && lc.cz === cz) {
+            return lc;
+        }
+        const c = this.chunks.get(chunkKey(cx, cz));
+        if (c !== undefined) {
+            this.lastChunk = c;
+        }
+        return c;
+    }
+
+    isLoaded(x, z) {
+        const c = this.chunkAt(x >> 4, z >> 4);
+        return c !== undefined && c.generated;
+    }
+
+    getBlock(x, y, z) {
+        if (y < 0) {
+            return B.BEDROCK;
+        }
+        if (y >= WORLD_H) {
+            return B.AIR;
+        }
+        const c = this.chunkAt(x >> 4, z >> 4);
+        if (c === undefined || !c.generated) {
+            return B.AIR;
+        }
+        return c.blocks[((x & 15) << 11) | ((z & 15) << 7) | y];
+    }
+
+    getMeta(x, y, z) {
+        if (y < 0 || y >= WORLD_H) {
+            return 0;
+        }
+        const c = this.chunkAt(x >> 4, z >> 4);
+        if (c === undefined || !c.generated) {
+            return 0;
+        }
+        return c.meta[((x & 15) << 11) | ((z & 15) << 7) | y];
+    }
+
+    getSky(x, y, z) {
+        if (y >= WORLD_H) {
+            return 15;
+        }
+        if (y < 0) {
+            return 0;
+        }
+        const c = this.chunkAt(x >> 4, z >> 4);
+        if (c === undefined || !c.lit) {
+            return 15;
+        }
+        return c.light[((x & 15) << 11) | ((z & 15) << 7) | y] >> 4;
+    }
+
+    getBlockLight(x, y, z) {
+        if (y < 0 || y >= WORLD_H) {
+            return 0;
+        }
+        const c = this.chunkAt(x >> 4, z >> 4);
+        if (c === undefined) {
+            return 0;
+        }
+        return c.light[((x & 15) << 11) | ((z & 15) << 7) | y] & 15;
+    }
+
+    //Light level the way plants see it (sky dims at night)
+    effectiveLight(x, y, z) {
+        return Math.max(this.getSky(x, y, z) - this.skyDarken, this.getBlockLight(x, y, z));
+    }
+
+    biomeAt(x, z) {
+        const c = this.chunkAt(x >> 4, z >> 4);
+        if (c === undefined || !c.generated) {
+            return this.gen.column(x, z).biome;
+        }
+        return c.biome[(z & 15) * 16 + (x & 15)];
+    }
+
+    //First y above everything that stops rain in this column
+    rainTop(x, z) {
+        const c = this.chunkAt(x >> 4, z >> 4);
+        if (c === undefined || !c.generated) {
+            return -1;
+        }
+        return c.hmRain[(z & 15) * 16 + (x & 15)];
+    }
+
+    /* ---------------- generation & streaming ---------------- */
+
+    getOrCreate(cx, cz) {
+        let c = this.chunkAt(cx, cz);
+        if (c === undefined) {
+            c = new Chunk(cx, cz);
+            this.chunks.set(c.key, c);
+        }
+        return c;
+    }
+
+    generateChunk(c) {
+        const saved = this.saved.get(c.key);
+        if (saved !== undefined) {
+            rleDecode(base64ToBytes(saved), c.blocks, c.meta);
+            for (let lz = 0; lz < 16; lz++) {
+                for (let lx = 0; lx < 16; lx++) {
+                    const col = this.gen.columnCached(c.cx * 16 + lx, c.cz * 16 + lz);
+                    c.biome[lz * 16 + lx] = col.biome;
+                    c.tint.set(col.grass, (lz * 16 + lx) * 6);
+                    c.tint.set(col.leaf, (lz * 16 + lx) * 6 + 3);
+                }
+            }
+            c.modified = true;
+            this.saved.delete(c.key);
+        } else {
+            this.gen.generate(c);
+        }
+        this.computeHeightmaps(c);
+        c.generated = true;
+    }
+
+    computeHeightmaps(c) {
+        for (let lz = 0; lz < 16; lz++) {
+            for (let lx = 0; lx < 16; lx++) {
+                const base = (lx << 11) | (lz << 7);
+                let hl = 0, hr = 0;
+                for (let y = WORLD_H - 1; y >= 0; y--) {
+                    if (opacityOf(c.blocks[base | y], c.meta[base | y]) > 0) {
+                        hl = y + 1;
+                        break;
+                    }
+                }
+                for (let y = WORLD_H - 1; y >= 0; y--) {
+                    if (RAIN_BLOCKING[c.blocks[base | y]]) {
+                        hr = y + 1;
+                        break;
+                    }
+                }
+                c.hmLight[lz * 16 + lx] = hl;
+                c.hmRain[lz * 16 + lx] = hr;
+            }
+        }
+    }
+
+    neighborsReady(c, flag) {
+        for (let dx = -1; dx <= 1; dx++) {
+            for (let dz = -1; dz <= 1; dz++) {
+                if (dx === 0 && dz === 0) {
+                    continue;
+                }
+                const n = this.chunkAt(c.cx + dx, c.cz + dz);
+                if (n === undefined || !n[flag]) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    isMeshable(c) {
+        return c.lit && this.neighborsReady(c, "lit");
+    }
+
+    //Generate and light chunks around (pcx, pcz) until the deadline.
+    //Returns true when everything in range is ready.
+    stream(pcx, pcz, radius, deadline) {
+        const key = pcx + "," + pcz + "," + radius;
+        if (key !== this.orderKey) {
+            this.orderKey = key;
+            const list = [];
+            const R = radius + 2;
+            for (let dx = -R; dx <= R; dx++) {
+                for (let dz = -R; dz <= R; dz++) {
+                    list.push([dx, dz, dx * dx + dz * dz, Math.max(Math.abs(dx), Math.abs(dz))]);
+                }
+            }
+            list.sort((a, b) => a[2] - b[2]);
+            this.order = list;
+            this.streamDone = false;
+        }
+        if (this.streamDone) {
+            return true;
+        }
+        let allDone = true;
+        for (const [dx, dz, , cheb] of this.order) {
+            const c = this.getOrCreate(pcx + dx, pcz + dz);
+            if (!c.generated) {
+                if (performance.now() > deadline) {
+                    return false;
+                }
+                this.generateChunk(c);
+            }
+            if (cheb <= radius + 1 && !c.lit) {
+                if (this.neighborsReady(c, "generated")) {
+                    if (performance.now() > deadline) {
+                        return false;
+                    }
+                    this.lightChunk(c);
+                } else {
+                    allDone = false;
+                }
+            }
+        }
+        if (allDone) {
+            this.streamDone = true;
+        }
+        return allDone;
+    }
+
+    //Drop chunks far from the player; returns the removed chunks
+    unloadFar(pcx, pcz, radius) {
+        const out = [];
+        const R = radius + 4;
+        for (const c of this.chunks.values()) {
+            if (Math.abs(c.cx - pcx) > R || Math.abs(c.cz - pcz) > R) {
+                if (c.modified && c.generated) {
+                    this.saved.set(c.key, bytesToBase64(rleEncode(c.blocks, c.meta)));
+                }
+                out.push(c);
+            }
+        }
+        for (const c of out) {
+            this.chunks.delete(c.key);
+        }
+        if (out.length) {
+            this.lastChunk = null;
+            this.orderKey = "";
+        }
+        return out;
+    }
+
+    /* ---------------- lighting ---------------- */
+
+    lightChunk(c) {
+        const x0 = c.cx * 16, z0 = c.cz * 16;
+        //Straight down sky light
+        for (let lz = 0; lz < 16; lz++) {
+            for (let lx = 0; lx < 16; lx++) {
+                let level = 15;
+                for (let y = WORLD_H - 1; y >= 0; y--) {
+                    const i = (lx << 11) | (lz << 7) | y;
+                    const op = opacityOf(c.blocks[i], c.meta[i]);
+                    if (op >= 15) {
+                        break;
+                    }
+                    if (!(level === 15 && op === 0)) {
+                        level = level - 1 - op;
+                        if (level <= 0) {
+                            break;
+                        }
+                    }
+                    if (level > (c.light[i] >> 4)) {
+                        c.light[i] = (level << 4) | (c.light[i] & 15);
+                    }
+                }
+            }
+        }
+        //Seeds: open sky voxels next to taller neighbouring columns
+        const sky = [];
+        for (let lz = 0; lz < 16; lz++) {
+            for (let lx = 0; lx < 16; lx++) {
+                const h = c.hmLight[lz * 16 + lx];
+                let maxN = h;
+                for (let d = 0; d < 4; d++) {
+                    const nx = x0 + lx + (d === 0 ? 1 : d === 1 ? -1 : 0);
+                    const nz = z0 + lz + (d === 2 ? 1 : d === 3 ? -1 : 0);
+                    const nc = this.chunkAt(nx >> 4, nz >> 4);
+                    if (nc !== undefined && nc.generated) {
+                        const nh = nc.hmLight[(nz & 15) * 16 + (nx & 15)];
+                        if (nh > maxN) {
+                            maxN = nh;
+                        }
+                    }
+                }
+                for (let y = h; y < maxN; y++) {
+                    sky.push(x0 + lx, y, z0 + lz);
+                }
+            }
+        }
+        //Block light sources
+        const blk = [];
+        const blocks = c.blocks;
+        for (let i = 0; i < blocks.length; i++) {
+            const em = LIGHT_EMIT[blocks[i]];
+            if (em > 0) {
+                c.light[i] = (c.light[i] & 0xf0) | em;
+                blk.push(x0 + (i >> 11), i & 127, z0 + ((i >> 7) & 15));
+            }
+        }
+        c.lit = true;
+        this.propagate(sky, true);
+        this.propagate(blk, false);
+        c.dirty.fill(1);
+    }
+
+    propagate(q, isSky) {
+        let i = 0;
+        while (i < q.length) {
+            const x = q[i++], y = q[i++], z = q[i++];
+            const c = this.chunkAt(x >> 4, z >> 4);
+            if (c === undefined || !c.generated) {
+                continue;
+            }
+            const li = ((x & 15) << 11) | ((z & 15) << 7) | y;
+            const level = isSky ? c.light[li] >> 4 : c.light[li] & 15;
+            if (level <= 1) {
+                continue;
+            }
+            for (let d = 0; d < 18; d += 3) {
+                const ny = y + DIRS[d + 1];
+                if (ny < 0 || ny >= WORLD_H) {
+                    continue;
+                }
+                const nx = x + DIRS[d], nz = z + DIRS[d + 2];
+                const nc = (DIRS[d] !== 0 || DIRS[d + 2] !== 0) ? this.chunkAt(nx >> 4, nz >> 4) : c;
+                if (nc === undefined || !nc.generated) {
+                    continue;
+                }
+                const ni = ((nx & 15) << 11) | ((nz & 15) << 7) | ny;
+                const op = opacityOf(nc.blocks[ni], nc.meta[ni]);
+                if (op >= 15) {
+                    continue;
+                }
+                const nl = (isSky && d === 9 && level === 15 && op === 0) ? 15 : level - 1 - op;
+                if (nl <= 0) {
+                    continue;
+                }
+                const cur = isSky ? nc.light[ni] >> 4 : nc.light[ni] & 15;
+                if (nl > cur) {
+                    nc.light[ni] = isSky ? (nl << 4) | (nc.light[ni] & 15) : (nc.light[ni] & 0xf0) | nl;
+                    this.markDirtyAround(nx, ny, nz, nc);
+                    q.push(nx, ny, nz);
+                }
+            }
+            if (i > 300000) {
+                q.splice(0, i);
+                i = 0;
+            }
+        }
+    }
+
+    //Clear the light a voxel used to spread; refill candidates go to add
+    removeLight(x, y, z, level, isSky, add) {
+        const c0 = this.chunkAt(x >> 4, z >> 4);
+        const li0 = ((x & 15) << 11) | ((z & 15) << 7) | y;
+        c0.light[li0] = isSky ? c0.light[li0] & 15 : c0.light[li0] & 0xf0;
+        const rq = [x, y, z, level];
+        let i = 0;
+        while (i < rq.length) {
+            const cx = rq[i++], cy = rq[i++], cz = rq[i++], lv = rq[i++];
+            for (let d = 0; d < 18; d += 3) {
+                const ny = cy + DIRS[d + 1];
+                if (ny < 0 || ny >= WORLD_H) {
+                    continue;
+                }
+                const nx = cx + DIRS[d], nz = cz + DIRS[d + 2];
+                const nc = this.chunkAt(nx >> 4, nz >> 4);
+                if (nc === undefined || !nc.generated) {
+                    continue;
+                }
+                const ni = ((nx & 15) << 11) | ((nz & 15) << 7) | ny;
+                const nl = isSky ? nc.light[ni] >> 4 : nc.light[ni] & 15;
+                if (nl === 0) {
+                    continue;
+                }
+                if (!isSky) {
+                    const em = LIGHT_EMIT[nc.blocks[ni]];
+                    if (em > 0) {
+                        if (nl < lv && nl > em) {
+                            nc.light[ni] = (nc.light[ni] & 0xf0) | em;
+                            this.markDirtyAround(nx, ny, nz, nc);
+                        }
+                        add.push(nx, ny, nz);
+                        continue;
+                    }
+                }
+                const straightDown = isSky && d === 9 && lv === 15 && nl === 15;
+                if (nl < lv || straightDown) {
+                    nc.light[ni] = isSky ? nc.light[ni] & 15 : nc.light[ni] & 0xf0;
+                    this.markDirtyAround(nx, ny, nz, nc);
+                    rq.push(nx, ny, nz, nl);
+                } else {
+                    add.push(nx, ny, nz);
+                }
+            }
+        }
+    }
+
+    relight(x, y, z, oldId, oldMeta, newId, newMeta) {
+        const oldOp = opacityOf(oldId, oldMeta), newOp = opacityOf(newId, newMeta);
+        const oldEm = LIGHT_EMIT[oldId], newEm = LIGHT_EMIT[newId];
+        const c = this.chunkAt(x >> 4, z >> 4);
+        const li = ((x & 15) << 11) | ((z & 15) << 7) | y;
+        const pushNeighbors = (arr) => {
+            for (let d = 0; d < 18; d += 3) {
+                const ny = y + DIRS[d + 1];
+                if (ny >= 0 && ny < WORLD_H) {
+                    arr.push(x + DIRS[d], ny, z + DIRS[d + 2]);
+                }
+            }
+        };
+        if (oldEm !== newEm || oldOp !== newOp) {
+            const add = [];
+            const cur = c.light[li] & 15;
+            if (cur > 0) {
+                this.removeLight(x, y, z, cur, false, add);
+            }
+            if (newEm > 0) {
+                c.light[li] = (c.light[li] & 0xf0) | newEm;
+                add.push(x, y, z);
+            } else if (newOp < 15) {
+                pushNeighbors(add);
+            }
+            this.propagate(add, false);
+        }
+        if (oldOp !== newOp) {
+            const add = [];
+            const cur = c.light[li] >> 4;
+            if (newOp > oldOp) {
+                if (cur > 0) {
+                    this.removeLight(x, y, z, cur, true, add);
+                }
+            } else {
+                pushNeighbors(add);
+            }
+            this.propagate(add, true);
+        }
+    }
+
+    markDirtyAround(x, y, z, c) {
+        const lx = x & 15, lz = z & 15, ly = y & 15;
+        const sec = y >> 4;
+        c.dirty[sec] = 1;
+        if (lx !== 0 && lx !== 15 && lz !== 0 && lz !== 15 && ly !== 0 && ly !== 15) {
+            return;
+        }
+        const xa = lx === 0 ? -1 : lx === 15 ? 1 : 0;
+        const za = lz === 0 ? -1 : lz === 15 ? 1 : 0;
+        const ya = ly === 0 ? -1 : ly === 15 ? 1 : 0;
+        for (let dx = 0; dx <= 1; dx++) {
+            if (dx === 1 && xa === 0) {
+                break;
+            }
+            for (let dz = 0; dz <= 1; dz++) {
+                if (dz === 1 && za === 0) {
+                    break;
+                }
+                for (let dy = 0; dy <= 1; dy++) {
+                    if (dy === 1 && ya === 0) {
+                        break;
+                    }
+                    const ns = sec + (dy ? ya : 0);
+                    if (ns < 0 || ns >= SECTIONS) {
+                        continue;
+                    }
+                    const nc = (dx || dz) ? this.chunkAt(c.cx + (dx ? xa : 0), c.cz + (dz ? za : 0)) : c;
+                    if (nc !== undefined) {
+                        nc.dirty[ns] = 1;
+                    }
+                }
+            }
+        }
+    }
+
+    /* ---------------- block changes ---------------- */
+
+    setBlock(x, y, z, id, meta = 0, notify = true) {
+        if (y < 0 || y >= WORLD_H) {
+            return false;
+        }
+        const c = this.chunkAt(x >> 4, z >> 4);
+        if (c === undefined || !c.generated) {
+            return false;
+        }
+        const i = ((x & 15) << 11) | ((z & 15) << 7) | y;
+        const oldId = c.blocks[i], oldMeta = c.meta[i];
+        if (oldId === id && oldMeta === meta) {
+            return false;
+        }
+        c.blocks[i] = id;
+        c.meta[i] = meta;
+        //Grass spreading and plants growing in a chunk nobody touched are
+        //not worth a save entry; the chunk simply regenerates
+        if (!this.quiet) {
+            c.modified = true;
+        }
+        this.updateHeightmaps(c, x & 15, y, z & 15);
+        if (c.lit) {
+            this.relight(x, y, z, oldId, oldMeta, id, meta);
+        }
+        this.markDirtyAround(x, y, z, c);
+        if (oldId !== id) {
+            if ((oldId === B.LOG || oldId === B.LEAVES) && id !== B.LOG) {
+                this.scheduleLeafChecks(x, y, z);
+            }
+            if (oldId === B.FURNACE || oldId === B.FURNACE_LIT || oldId === B.CHEST) {
+                if (id !== B.FURNACE && id !== B.FURNACE_LIT) {
+                    this.dropTileEntity(x, y, z);
+                }
+            }
+        }
+        if (notify) {
+            this.notifyNeighbors(x, y, z);
+        }
+        return true;
+    }
+
+    setMeta(x, y, z, meta) {
+        return this.setBlock(x, y, z, this.getBlock(x, y, z), meta, false);
+    }
+
+    updateHeightmaps(c, lx, y, lz) {
+        const ci = lz * 16 + lx;
+        const base = (lx << 11) | (lz << 7);
+        const id = c.blocks[base | y];
+        if (opacityOf(id, c.meta[base | y]) > 0) {
+            if (y + 1 > c.hmLight[ci]) {
+                c.hmLight[ci] = y + 1;
+            }
+        } else if (y + 1 === c.hmLight[ci]) {
+            let yy = y - 1;
+            while (yy >= 0 && opacityOf(c.blocks[base | yy], c.meta[base | yy]) === 0) {
+                yy--;
+            }
+            c.hmLight[ci] = yy + 1;
+        }
+        if (RAIN_BLOCKING[id]) {
+            if (y + 1 > c.hmRain[ci]) {
+                c.hmRain[ci] = y + 1;
+            }
+        } else if (y + 1 === c.hmRain[ci]) {
+            let yy = y - 1;
+            while (yy >= 0 && !RAIN_BLOCKING[c.blocks[base | yy]]) {
+                yy--;
+            }
+            c.hmRain[ci] = yy + 1;
+        }
+    }
+
+    notifyNeighbors(x, y, z) {
+        this.neighborChanged(x, y, z);
+        for (let d = 0; d < 18; d += 3) {
+            this.neighborChanged(x + DIRS[d], y + DIRS[d + 1], z + DIRS[d + 2]);
+        }
+    }
+
+    neighborChanged(x, y, z) {
+        if (y < 0 || y >= WORLD_H || !this.isLoaded(x, z)) {
+            return;
+        }
+        const id = this.getBlock(x, y, z);
+        if (id === B.AIR) {
+            return;
+        }
+        const def = BLOCKS[id];
+        if (id === B.WATER) {
+            this.schedule(x, y, z, 5);
+        } else if (def.gravity) {
+            if (this.canFallInto(this.getBlock(x, y - 1, z))) {
+                this.schedule(x, y, z, 2);
+            }
+        } else if (def.support) {
+            this.schedule(x, y, z, 1);
+        } else if (id === B.FARMLAND) {
+            const above = this.getBlock(x, y + 1, z);
+            if (isOpaqueAt(above, this.getMeta(x, y + 1, z))) {
+                this.setBlock(x, y, z, B.DIRT);
+            }
+        }
+    }
+
+    canFallInto(id) {
+        return id === B.AIR || id === B.WATER || WASHABLE[id] === 1;
+    }
+
+    hasSupport(x, y, z, id, meta) {
+        const below = this.getBlock(x, y - 1, z);
+        const belowMeta = this.getMeta(x, y - 1, z);
+        switch (BLOCKS[id].support) {
+            case "soil":
+                return below === B.GRASS || below === B.DIRT || below === B.FARMLAND;
+            case "solid":
+                return isOpaqueAt(below, belowMeta);
+            case "sand":
+                return below === B.SAND || below === B.GRASS || below === B.DIRT;
+            case "farmland":
+                return below === B.FARMLAND;
+            case "reeds":
+                if (below === B.REEDS) {
+                    return true;
+                }
+                if (below !== B.GRASS && below !== B.DIRT && below !== B.SAND) {
+                    return false;
+                }
+                return this.waterBeside(x, y - 1, z);
+            case "cactus":
+                if (below !== B.CACTUS && below !== B.SAND) {
+                    return false;
+                }
+                for (let d = 0; d < 18; d += 3) {
+                    if (DIRS[d + 1] !== 0) {
+                        continue;
+                    }
+                    if (SOLID[this.getBlock(x + DIRS[d], y, z + DIRS[d + 2])]) {
+                        return false;
+                    }
+                }
+                return true;
+            case "torch":
+            case "wall": {
+                const n = FACE_DIR[meta] || FACE_DIR[2];
+                const ax = x - n[0], ay = y - n[1], az = z - n[2];
+                const aid = this.getBlock(ax, ay, az), am = this.getMeta(ax, ay, az);
+                if (isOpaqueAt(aid, am)) {
+                    return true;
+                }
+                //Torches also stand on top slabs
+                return BLOCKS[id].support === "torch" && meta === 2 && IS_SLAB[aid] === 1 && am === 1;
+            }
+            default:
+                return true;
+        }
+    }
+
+    waterBeside(x, y, z) {
+        for (let d = 0; d < 18; d += 3) {
+            if (DIRS[d + 1] === 0 && this.getBlock(x + DIRS[d], y, z + DIRS[d + 2]) === B.WATER) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    //Break a block as if it broke by itself (drops items)
+    breakNaturally(x, y, z) {
+        const id = this.getBlock(x, y, z);
+        const meta = this.getMeta(x, y, z);
+        if (id === B.AIR || id === B.WATER) {
+            return;
+        }
+        const drops = blockDrops(id, meta, this.rng, 0);
+        this.setBlock(x, y, z, B.AIR, 0);
+        if (this.onDrop) {
+            for (const [did, n] of drops) {
+                this.onDrop(x + 0.5, y + 0.4, z + 0.5, did, n);
+            }
+        }
+        if (this.onBlockBroken) {
+            this.onBlockBroken(x, y, z, id, true);
+        }
+    }
+
+    /* ---------------- scheduled ticks ---------------- */
+
+    schedule(x, y, z, delay) {
+        const key = x + "," + y + "," + z;
+        if (this.schedSet.has(key)) {
+            return;
+        }
+        this.schedSet.add(key);
+        const t = this.tickCount + Math.max(1, delay | 0);
+        let b = this.schedBuckets.get(t);
+        if (b === undefined) {
+            b = [];
+            this.schedBuckets.set(t, b);
+        }
+        b.push(x, y, z);
+    }
+
+    runScheduled() {
+        const b = this.schedBuckets.get(this.tickCount);
+        if (b === undefined) {
+            return;
+        }
+        this.schedBuckets.delete(this.tickCount);
+        const limit = Math.min(b.length, 3 * 600);
+        for (let i = 0; i < limit; i += 3) {
+            const x = b[i], y = b[i + 1], z = b[i + 2];
+            this.schedSet.delete(x + "," + y + "," + z);
+            if (this.isLoaded(x, z)) {
+                this.scheduledTick(x, y, z);
+            }
+        }
+        if (limit < b.length) {
+            //Too much at once: carry the rest over to the next tick
+            const rest = b.slice(limit);
+            const nb = this.schedBuckets.get(this.tickCount + 1) || [];
+            this.schedBuckets.set(this.tickCount + 1, nb.concat(rest));
+        }
+    }
+
+    scheduledTick(x, y, z) {
+        const id = this.getBlock(x, y, z);
+        const meta = this.getMeta(x, y, z);
+        const def = BLOCKS[id];
+        if (id === B.WATER) {
+            this.waterTick(x, y, z, meta);
+        } else if (def.gravity) {
+            if (this.canFallInto(this.getBlock(x, y - 1, z)) && y > 0) {
+                if (this.onFalling) {
+                    this.setBlock(x, y, z, B.AIR, 0);
+                    this.onFalling(x, y, z, id, meta);
+                }
+            }
+        } else if (def.support) {
+            if (!this.hasSupport(x, y, z, id, meta)) {
+                this.breakNaturally(x, y, z);
+            }
+        } else if (id === B.LEAVES && (meta & 1) === 0) {
+            if (!this.logNearby(x, y, z)) {
+                this.breakNaturally(x, y, z);
+            }
+        }
+    }
+
+    /* ---------------- water ---------------- */
+
+    flowInto(x, y, z, level) {
+        const id = this.getBlock(x, y, z);
+        if (WASHABLE[id] === 1) {
+            this.breakNaturally(x, y, z);
+        }
+        this.setBlock(x, y, z, B.WATER, level);
+    }
+
+    canFlow(id) {
+        return id === B.AIR || WASHABLE[id] === 1;
+    }
+
+    waterTick(x, y, z, m) {
+        if (m !== 0) {
+            let newM;
+            if (this.getBlock(x, y + 1, z) === B.WATER) {
+                newM = 8;
+            } else {
+                let best = 99, sources = 0;
+                for (let d = 0; d < 18; d += 3) {
+                    if (DIRS[d + 1] !== 0) {
+                        continue;
+                    }
+                    const nx = x + DIRS[d], nz = z + DIRS[d + 2];
+                    if (this.getBlock(nx, y, nz) === B.WATER) {
+                        const nm = this.getMeta(nx, y, nz);
+                        if (nm === 0) {
+                            sources++;
+                        }
+                        const eff = nm === 8 ? 0 : nm;
+                        if (eff + 1 < best) {
+                            best = eff + 1;
+                        }
+                    }
+                }
+                const below = this.getBlock(x, y - 1, z);
+                if (sources >= 2 && (isOpaqueAt(below, this.getMeta(x, y - 1, z)) || (below === B.WATER && this.getMeta(x, y - 1, z) === 0))) {
+                    newM = 0;
+                } else {
+                    newM = best <= 7 ? best : -1;
+                }
+            }
+            if (newM === -1) {
+                this.setBlock(x, y, z, B.AIR, 0);
+                return;
+            }
+            if (newM !== m) {
+                this.setBlock(x, y, z, B.WATER, newM);
+                m = newM;
+            }
+        }
+        const below = this.getBlock(x, y - 1, z);
+        if (y > 0 && this.canFlow(below)) {
+            this.flowInto(x, y - 1, z, 8);
+            return;
+        }
+        if (below === B.WATER) {
+            return;
+        }
+        const next = (m === 0 || m === 8) ? 1 : m + 1;
+        if (next > 7) {
+            return;
+        }
+        for (let d = 0; d < 18; d += 3) {
+            if (DIRS[d + 1] !== 0) {
+                continue;
+            }
+            const nx = x + DIRS[d], nz = z + DIRS[d + 2];
+            if (!this.isLoaded(nx, nz)) {
+                continue;
+            }
+            const nid = this.getBlock(nx, y, nz);
+            if (this.canFlow(nid)) {
+                this.flowInto(nx, y, nz, next);
+            } else if (nid === B.WATER) {
+                const nm = this.getMeta(nx, y, nz);
+                if (nm !== 0 && nm !== 8 && nm > next) {
+                    this.setBlock(nx, y, nz, B.WATER, next);
+                }
+            }
+        }
+    }
+
+    /* ---------------- leaves ---------------- */
+
+    scheduleLeafChecks(x, y, z) {
+        for (let dx = -4; dx <= 4; dx++) {
+            for (let dy = -4; dy <= 4; dy++) {
+                for (let dz = -4; dz <= 4; dz++) {
+                    const yy = y + dy;
+                    if (yy < 0 || yy >= WORLD_H) {
+                        continue;
+                    }
+                    if (this.getBlock(x + dx, yy, z + dz) === B.LEAVES && (this.getMeta(x + dx, yy, z + dz) & 1) === 0) {
+                        this.schedule(x + dx, yy, z + dz, 10 + Math.floor(this.rng() * 70));
+                    }
+                }
+            }
+        }
+    }
+
+    logNearby(x, y, z) {
+        const R = 4, W = 9;
+        const seen = new Uint8Array(W * W * W);
+        const q = [x, y, z, 0];
+        seen[(R * W + R) * W + R] = 1;
+        let i = 0;
+        while (i < q.length) {
+            const cx = q[i++], cy = q[i++], cz = q[i++], dist = q[i++];
+            for (let d = 0; d < 18; d += 3) {
+                const nx = cx + DIRS[d], ny = cy + DIRS[d + 1], nz = cz + DIRS[d + 2];
+                const ox = nx - x + R, oy = ny - y + R, oz = nz - z + R;
+                if (ox < 0 || oy < 0 || oz < 0 || ox >= W || oy >= W || oz >= W) {
+                    continue;
+                }
+                const si = (ox * W + oy) * W + oz;
+                if (seen[si]) {
+                    continue;
+                }
+                seen[si] = 1;
+                const id = this.getBlock(nx, ny, nz);
+                if (id === B.LOG) {
+                    return true;
+                }
+                if (id === B.LEAVES && dist + 1 < R) {
+                    q.push(nx, ny, nz, dist + 1);
+                }
+            }
+        }
+        return false;
+    }
+
+    /* ---------------- random ticks ---------------- */
+
+    randomTicks(pcx, pcz, radius) {
+        const rng = this.rng;
+        for (const c of this.chunks.values()) {
+            if (!c.lit || Math.abs(c.cx - pcx) > radius || Math.abs(c.cz - pcz) > radius) {
+                continue;
+            }
+            for (let s = 0; s < SECTIONS; s++) {
+                for (let k = 0; k < 3; k++) {
+                    const r = (rng() * 4096) | 0;
+                    const lx = r & 15, lz = (r >> 4) & 15, y = s * 16 + (r >> 8);
+                    const id = c.blocks[(lx << 11) | (lz << 7) | y];
+                    if (id === B.GRASS || id === B.SAPLING || id === B.WHEAT || id === B.FARMLAND || id === B.REEDS || id === B.CACTUS) {
+                        this.randomTick(c.cx * 16 + lx, y, c.cz * 16 + lz, id);
+                    }
+                }
+            }
+        }
+    }
+
+    randomTick(x, y, z, id) {
+        if (id === B.GRASS || id === B.REEDS || id === B.CACTUS) {
+            this.quiet = true;
+            try {
+                this.naturalTick(x, y, z, id);
+            } finally {
+                this.quiet = false;
+            }
+            return;
+        }
+        const rng = this.rng;
+        const meta = this.getMeta(x, y, z);
+        if (id === B.SAPLING) {
+            if (this.effectiveLight(x, y, z) >= 9 && rng() < 0.07) {
+                this.growTree(x, y, z);
+            }
+        } else if (id === B.WHEAT) {
+            if (meta < 7 && this.effectiveLight(x, y, z) >= 9) {
+                const wet = this.getMeta(x, y - 1, z) > 0;
+                if (rng() < (wet ? 0.3 : 0.12)) {
+                    this.setBlock(x, y, z, B.WHEAT, meta + 1, false);
+                }
+            }
+        } else if (id === B.FARMLAND) {
+            let wet = this.raining && this.rainTop(x, z) <= y + 1;
+            if (!wet) {
+                for (let dx = -4; dx <= 4 && !wet; dx++) {
+                    for (let dz = -4; dz <= 4 && !wet; dz++) {
+                        for (let dy = 0; dy <= 1; dy++) {
+                            if (this.getBlock(x + dx, y + dy, z + dz) === B.WATER) {
+                                wet = true;
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+            if (wet) {
+                if (meta !== 7) {
+                    this.setBlock(x, y, z, B.FARMLAND, 7, false);
+                }
+            } else if (meta > 0) {
+                this.setBlock(x, y, z, B.FARMLAND, meta - 1, false);
+            } else if (this.getBlock(x, y + 1, z) !== B.WHEAT && rng() < 0.3) {
+                this.setBlock(x, y, z, B.DIRT);
+            }
+        }
+    }
+
+    //Grass spreading / dying and reeds / cactus growing
+    naturalTick(x, y, z, id) {
+        const rng = this.rng;
+        if (id === B.GRASS) {
+            const above = this.getBlock(x, y + 1, z);
+            if (isOpaqueAt(above, this.getMeta(x, y + 1, z)) || above === B.WATER) {
+                this.setBlock(x, y, z, B.DIRT);
+                return;
+            }
+            if (this.effectiveLight(x, y + 1, z) >= 9) {
+                const tx = x + Math.floor(rng() * 3) - 1;
+                const ty = y + Math.floor(rng() * 5) - 3;
+                const tz = z + Math.floor(rng() * 3) - 1;
+                if (this.getBlock(tx, ty, tz) === B.DIRT) {
+                    const a = this.getBlock(tx, ty + 1, tz);
+                    if (!isOpaqueAt(a, this.getMeta(tx, ty + 1, tz)) && a !== B.WATER && this.effectiveLight(tx, ty + 1, tz) >= 4) {
+                        this.setBlock(tx, ty, tz, B.GRASS);
+                    }
+                }
+            }
+            return;
+        }
+        if (this.getBlock(x, y + 1, z) !== B.AIR || rng() > 0.08) {
+            return;
+        }
+        let h = 1;
+        while (h < 4 && this.getBlock(x, y - h, z) === id) {
+            h++;
+        }
+        if (h < 3) {
+            this.setBlock(x, y + 1, z, id, 0);
+        }
+    }
+
+    growTree(x, y, z) {
+        const plan = this.gen.treeBlocks(x, y, z, this.rng);
+        if (y + plan.height >= WORLD_H - 1) {
+            return false;
+        }
+        //Trunk needs free space
+        for (const [bx, by, bz, id] of plan.blocks) {
+            if (id === B.LOG && !(bx === x && by === y && bz === z)) {
+                const cur = this.getBlock(bx, by, bz);
+                if (cur !== B.AIR && cur !== B.LEAVES && cur !== B.TALL_GRASS) {
+                    return false;
+                }
+            }
+        }
+        this.setBlock(x, y, z, B.AIR, 0, false);
+        if (this.getBlock(x, y - 1, z) === B.GRASS) {
+            this.setBlock(x, y - 1, z, B.DIRT, 0, false);
+        }
+        for (const [bx, by, bz, id] of plan.blocks) {
+            const cur = this.getBlock(bx, by, bz);
+            if (id === B.LOG || cur === B.AIR || cur === B.TALL_GRASS) {
+                this.setBlock(bx, by, bz, id, 0, false);
+            }
+        }
+        return true;
+    }
+
+    /* ---------------- tile entities ---------------- */
+
+    teKey(x, y, z) {
+        return x + "," + y + "," + z;
+    }
+
+    getTileEntity(x, y, z) {
+        return this.tileEntities.get(this.teKey(x, y, z)) || null;
+    }
+
+    createTileEntity(x, y, z, type) {
+        const te = type === "furnace"
+            ? { type, slots: [null, null, null], burn: 0, burnMax: 0, cook: 0 }
+            : { type, slots: new Array(27).fill(null) };
+        this.tileEntities.set(this.teKey(x, y, z), te);
+        return te;
+    }
+
+    dropTileEntity(x, y, z) {
+        const key = this.teKey(x, y, z);
+        const te = this.tileEntities.get(key);
+        if (!te) {
+            return;
+        }
+        this.tileEntities.delete(key);
+        if (this.onDrop) {
+            for (const s of te.slots) {
+                if (s && s.count > 0) {
+                    this.onDrop(x + 0.5, y + 0.5, z + 0.5, s.id, s.count, s.dmg || 0);
+                }
+            }
+        }
+    }
+
+    tickFurnaces() {
+        for (const [key, te] of this.tileEntities) {
+            if (te.type !== "furnace") {
+                continue;
+            }
+            const p = key.split(",").map(Number);
+            if (!this.isLoaded(p[0], p[2])) {
+                continue;
+            }
+            const [input, fuel, output] = te.slots;
+            const result = input ? SMELTING.get(input.id) : undefined;
+            const canSmelt = result !== undefined &&
+                (!output || (output.id === result && output.count < ((ITEMS[result] && ITEMS[result].stack) || 64)));
+            const wasBurning = te.burn > 0;
+            if (te.burn > 0) {
+                te.burn--;
+            }
+            if (te.burn === 0 && canSmelt && fuel && fuelTicks(fuel.id) > 0) {
+                te.burn = te.burnMax = fuelTicks(fuel.id);
+                fuel.count--;
+                if (fuel.count <= 0) {
+                    te.slots[1] = null;
+                }
+            }
+            if (te.burn > 0 && canSmelt) {
+                te.cook++;
+                if (te.cook >= SMELT_TICKS) {
+                    te.cook = 0;
+                    input.count--;
+                    if (input.count <= 0) {
+                        te.slots[0] = null;
+                    }
+                    if (output) {
+                        output.count++;
+                    } else {
+                        te.slots[2] = { id: result, count: 1 };
+                    }
+                }
+            } else {
+                te.cook = Math.max(0, te.cook - 2);
+            }
+            const burning = te.burn > 0;
+            if (burning !== wasBurning) {
+                const id = this.getBlock(p[0], p[1], p[2]);
+                if (id === B.FURNACE || id === B.FURNACE_LIT) {
+                    this.setBlock(p[0], p[1], p[2], burning ? B.FURNACE_LIT : B.FURNACE, this.getMeta(p[0], p[1], p[2]), false);
+                }
+            }
+        }
+    }
+
+    /* ---------------- per tick ---------------- */
+
+    tick(pcx, pcz) {
+        this.tickCount++;
+        this.runScheduled();
+        this.randomTicks(pcx, pcz, 6);
+        this.tickFurnaces();
+    }
+
+    /* ---------------- raycast ---------------- */
+
+    //Voxel walk from origin along dir; boxes(id, meta) gives hit boxes
+    raycast(ox, oy, oz, dx, dy, dz, maxDist, boxes) {
+        let x = Math.floor(ox), y = Math.floor(oy), z = Math.floor(oz);
+        const stepX = dx > 0 ? 1 : -1, stepY = dy > 0 ? 1 : -1, stepZ = dz > 0 ? 1 : -1;
+        const tDeltaX = dx !== 0 ? Math.abs(1 / dx) : Infinity;
+        const tDeltaY = dy !== 0 ? Math.abs(1 / dy) : Infinity;
+        const tDeltaZ = dz !== 0 ? Math.abs(1 / dz) : Infinity;
+        let tMaxX = dx !== 0 ? ((dx > 0 ? x + 1 - ox : ox - x) * tDeltaX) : Infinity;
+        let tMaxY = dy !== 0 ? ((dy > 0 ? y + 1 - oy : oy - y) * tDeltaY) : Infinity;
+        let tMaxZ = dz !== 0 ? ((dz > 0 ? z + 1 - oz : oz - z) * tDeltaZ) : Infinity;
+        for (let guard = 0; guard < 64; guard++) {
+            const id = this.getBlock(x, y, z);
+            if (id !== B.AIR && y >= 0 && y < WORLD_H) {
+                const box = boxes(id, this.getMeta(x, y, z));
+                if (box) {
+                    const hit = rayBox(ox - x, oy - y, oz - z, dx, dy, dz, box);
+                    if (hit && hit.t <= maxDist) {
+                        return { x, y, z, id, meta: this.getMeta(x, y, z), face: hit.face, t: hit.t, box,
+                            point: [ox + dx * hit.t, oy + dy * hit.t, oz + dz * hit.t] };
+                    }
+                }
+            }
+            if (tMaxX < tMaxY && tMaxX < tMaxZ) {
+                if (tMaxX > maxDist) {
+                    break;
+                }
+                x += stepX;
+                tMaxX += tDeltaX;
+            } else if (tMaxY < tMaxZ) {
+                if (tMaxY > maxDist) {
+                    break;
+                }
+                y += stepY;
+                tMaxY += tDeltaY;
+            } else {
+                if (tMaxZ > maxDist) {
+                    break;
+                }
+                z += stepZ;
+                tMaxZ += tDeltaZ;
+            }
+        }
+        return null;
+    }
+
+    /* ---------------- save data ---------------- */
+
+    serialize() {
+        const chunks = {};
+        for (const [k, v] of this.saved) {
+            chunks[keyName(k)] = v;
+        }
+        for (const c of this.chunks.values()) {
+            if (c.modified && c.generated) {
+                chunks[keyName(c.key)] = bytesToBase64(rleEncode(c.blocks, c.meta));
+            }
+        }
+        const tileEntities = {};
+        for (const [k, v] of this.tileEntities) {
+            tileEntities[k] = v;
+        }
+        return { chunks, tileEntities };
+    }
+
+    load(data) {
+        this.saved.clear();
+        if (data && data.chunks) {
+            for (const name of Object.keys(data.chunks)) {
+                const [cx, cz] = name.split(",").map(Number);
+                this.saved.set(chunkKey(cx, cz), data.chunks[name]);
+            }
+        }
+        this.tileEntities.clear();
+        if (data && data.tileEntities) {
+            for (const k of Object.keys(data.tileEntities)) {
+                this.tileEntities.set(k, data.tileEntities[k]);
+            }
+        }
+    }
+}
+
+function keyName(key) {
+    return (Math.floor(key / 65536) - 32768) + "," + ((key % 65536) - 32768);
+}
+
+//Ray against an axis aligned box in block local space
+function rayBox(ox, oy, oz, dx, dy, dz, b) {
+    let tmin = -Infinity, tmax = Infinity, face = -1;
+    const axes = [[ox, dx, b[0], b[3], 1, 0], [oy, dy, b[1], b[4], 3, 2], [oz, dz, b[2], b[5], 5, 4]];
+    for (const [o, d, lo, hi, faceLo, faceHi] of axes) {
+        if (Math.abs(d) < 1e-9) {
+            if (o < lo || o > hi) {
+                return null;
+            }
+            continue;
+        }
+        let t1 = (lo - o) / d, t2 = (hi - o) / d;
+        let f1 = faceLo, f2 = faceHi;
+        if (t1 > t2) {
+            [t1, t2] = [t2, t1];
+            [f1, f2] = [f2, f1];
+        }
+        if (t1 > tmin) {
+            tmin = t1;
+            face = f1;
+        }
+        if (t2 < tmax) {
+            tmax = t2;
+        }
+        if (tmin > tmax) {
+            return null;
+        }
+    }
+    if (tmax < 0) {
+        return null;
+    }
+    return { t: Math.max(0, tmin), face };
+}
+
+export { opacityOf, SEA, WORLD_H };

+ 443 - 0
src/web/Blocky/js/worldgen.js

@@ -0,0 +1,443 @@
+/*
+    Blocky - worldgen.js
+
+    Deterministic terrain generator. A column's height and biome come from
+    2D noise only, so any column can be asked about without generating its
+    chunk; that is what lets trees straddle chunk borders: every chunk
+    re-derives the trees of its eight neighbours and stamps the parts that
+    fall inside itself.
+
+    Biomes: ocean, grassland, desert, forest (plus sandy beaches along water).
+*/
+
+import { Noise } from "./noise.js";
+import { B } from "./blocks.js";
+import { mulberry32, hash2, hash3, smoothstep, lerp } from "./util.js";
+
+export const WORLD_H = 128;
+export const SEA = 62;
+
+export const BIOME = { OCEAN: 0, GRASSLAND: 1, DESERT: 2, FOREST: 3, BEACH: 4 };
+export const BIOME_NAMES = ["Ocean", "Grassland", "Desert", "Forest", "Beach"];
+
+//Grass and foliage tints per biome blend
+const GRASS_PLAIN = [0.62, 1.0, 0.43];
+const GRASS_FOREST = [0.5, 0.9, 0.36];
+const GRASS_DRY = [0.82, 0.92, 0.42];
+const LEAF_PLAIN = [0.48, 0.86, 0.32];
+const LEAF_FOREST = [0.38, 0.76, 0.28];
+
+export const idx = (x, y, z) => (x << 11) | (z << 7) | y;
+
+export class TerrainGen {
+    constructor(seed) {
+        this.seed = seed | 0;
+        this.nCont = new Noise(seed ^ 0x1a2b3c);
+        this.nTemp = new Noise(seed ^ 0x2b3c4d);
+        this.nHum = new Noise(seed ^ 0x3c4d5e);
+        this.nHill = new Noise(seed ^ 0x4d5e6f);
+        this.nDetail = new Noise(seed ^ 0x5e6f70);
+        this.nCaveA = new Noise(seed ^ 0x6f7081);
+        this.nCaveB = new Noise(seed ^ 0x708192);
+        this.nFloor = new Noise(seed ^ 0x8192a3);
+        this.nPeak = new Noise(seed ^ 0x92a3b4);
+        this.colCache = new Map();
+    }
+
+    //Height, biome and tints of one column
+    column(x, z) {
+        const cont = this.nCont.fbm2(x / 560, z / 560, 4);
+        const temp = this.nTemp.fbm2(x / 400 + 311, z / 400 - 127, 3);
+        const hum = this.nHum.fbm2(x / 340 - 97, z / 340 + 53, 3);
+        const land = smoothstep(-0.2, -0.06, cont);
+        const forest = smoothstep(0.0, 0.16, hum);
+        const desert = smoothstep(0.06, 0.2, temp) * (1 - forest);
+        const hill = this.nHill.fbm2(x / 150, z / 150, 4);
+        const detail = this.nDetail.fbm2(x / 34, z / 34, 2);
+        const amp = 5 + 7 * forest - 2.5 * desert + 4 * Math.max(0, cont);
+        let landH = SEA + 3 + Math.max(0, cont + 0.06) * 16 + hill * amp + detail * 1.5;
+        const peak = this.nPeak.fbm2(x / 220, z / 220, 3);
+        if (peak > 0.45) {
+            landH += (peak - 0.45) * 46 * (1 - desert);
+        }
+        landH += desert * Math.abs(this.nDetail.noise2(x / 22, z / 22)) * 3;
+        const oceanH = SEA - 11 + this.nFloor.fbm2(x / 60, z / 60, 3) * 5 + Math.min(0, cont + 0.2) * 14;
+        const h = Math.max(4, Math.min(WORLD_H - 20, Math.floor(lerp(oceanH, landH, land))));
+
+        let biome;
+        if (land < 0.5) {
+            biome = BIOME.OCEAN;
+        } else if (desert > 0.5) {
+            biome = BIOME.DESERT;
+        } else if (forest > 0.5) {
+            biome = BIOME.FOREST;
+        } else {
+            biome = BIOME.GRASSLAND;
+        }
+        if (biome !== BIOME.OCEAN && biome !== BIOME.DESERT && h <= SEA + 1 && h >= SEA - 2) {
+            const beachy = this.nDetail.noise2(x / 18 + 50, z / 18) > -0.35;
+            if (beachy) {
+                biome = BIOME.BEACH;
+            }
+        }
+        const dry = desert;
+        const grass = [0, 1, 2].map((i) => lerp(lerp(GRASS_PLAIN[i], GRASS_FOREST[i], forest), GRASS_DRY[i], dry * 0.8));
+        const leaf = [0, 1, 2].map((i) => lerp(LEAF_PLAIN[i], LEAF_FOREST[i], forest));
+        return { h, biome, grass, leaf, forest, desert };
+    }
+
+    //Cached column lookup for neighbouring tree origins
+    columnCached(x, z) {
+        const k = (x + 32768) * 65536 + (z + 32768);
+        let c = this.colCache.get(k);
+        if (!c) {
+            c = this.column(x, z);
+            if (this.colCache.size > 20000) {
+                this.colCache.clear();
+            }
+            this.colCache.set(k, c);
+        }
+        return c;
+    }
+
+    generate(chunk) {
+        const { blocks, meta } = chunk;
+        const x0 = chunk.cx * 16, z0 = chunk.cz * 16;
+        const cols = new Array(256);
+        let maxH = SEA;
+        for (let lz = 0; lz < 16; lz++) {
+            for (let lx = 0; lx < 16; lx++) {
+                const c = this.columnCached(x0 + lx, z0 + lz);
+                cols[lz * 16 + lx] = c;
+                chunk.biome[lz * 16 + lx] = c.biome;
+                chunk.tint.set(c.grass, (lz * 16 + lx) * 6);
+                chunk.tint.set(c.leaf, (lz * 16 + lx) * 6 + 3);
+                if (c.h > maxH) {
+                    maxH = c.h;
+                }
+            }
+        }
+
+        //Coarse cave noise grid (every 4 blocks), trilinearly interpolated
+        const gy = Math.min(32, (maxH >> 2) + 2);
+        const caveA = new Float32Array(5 * 5 * (gy + 1));
+        const caveB = new Float32Array(5 * 5 * (gy + 1));
+        for (let ix = 0; ix < 5; ix++) {
+            for (let iz = 0; iz < 5; iz++) {
+                for (let iy = 0; iy <= gy; iy++) {
+                    const wx = x0 + ix * 4, wy = iy * 4, wz = z0 + iz * 4;
+                    const g = (ix * 5 + iz) * (gy + 1) + iy;
+                    caveA[g] = this.nCaveA.noise3(wx / 42, wy / 24, wz / 42);
+                    caveB[g] = this.nCaveB.noise3(wx / 42, wy / 24, wz / 42);
+                }
+            }
+        }
+        const sample = (arr, lx, y, lz) => {
+            const fx = lx / 4, fy = y / 4, fz = lz / 4;
+            const ix = Math.min(3, fx | 0), iy = Math.min(gy - 1, fy | 0), iz = Math.min(3, fz | 0);
+            const tx = fx - ix, ty = fy - iy, tz = fz - iz;
+            const g = (a, b, c) => arr[((ix + a) * 5 + (iz + c)) * (gy + 1) + iy + b];
+            const c00 = lerp(g(0, 0, 0), g(1, 0, 0), tx), c01 = lerp(g(0, 0, 1), g(1, 0, 1), tx);
+            const c10 = lerp(g(0, 1, 0), g(1, 1, 0), tx), c11 = lerp(g(0, 1, 1), g(1, 1, 1), tx);
+            return lerp(lerp(c00, c01, tz), lerp(c10, c11, tz), ty);
+        };
+
+        const rng = mulberry32(hash2(this.seed, chunk.cx, chunk.cz));
+
+        for (let lz = 0; lz < 16; lz++) {
+            for (let lx = 0; lx < 16; lx++) {
+                const c = cols[lz * 16 + lx];
+                const h = c.h;
+                const underwater = h < SEA;
+                const floorN = this.nFloor.noise2((x0 + lx) / 14, (z0 + lz) / 14);
+                const top = Math.max(h, SEA);
+                for (let y = 0; y <= top; y++) {
+                    const i = idx(lx, y, lz);
+                    let id;
+                    if (y === 0 || (y < 4 && rng() < (4 - y) / 5)) {
+                        id = B.BEDROCK;
+                    } else if (y <= h) {
+                        const depth = h - y;
+                        id = B.STONE;
+                        if (underwater) {
+                            if (depth < 3) {
+                                id = floorN > 0.45 ? B.GRAVEL : floorN < -0.55 && depth === 0 ? B.CLAY : floorN > 0.2 && c.biome !== BIOME.OCEAN ? B.DIRT : B.SAND;
+                            }
+                        } else if (c.biome === BIOME.DESERT) {
+                            id = depth < 4 ? B.SAND : depth < 7 ? B.SANDSTONE : B.STONE;
+                        } else if (c.biome === BIOME.BEACH) {
+                            id = depth < 3 ? B.SAND : depth < 5 ? B.SANDSTONE : B.STONE;
+                        } else {
+                            const soil = 3 + ((hash2(this.seed, x0 + lx, z0 + lz) & 1));
+                            id = depth === 0 ? B.GRASS : depth <= soil ? B.DIRT : B.STONE;
+                        }
+                        //Caves: two ridged noises crossing carve tunnels
+                        if (y > 4 && id !== B.BEDROCK) {
+                            const nearWater = h < SEA + 4 && y > h - 9;
+                            if (!nearWater) {
+                                const a = sample(caveA, lx, y, lz);
+                                const b = sample(caveB, lx, y, lz);
+                                const t = y < 28 ? 0.085 : 0.065;
+                                if (Math.abs(a) < t && Math.abs(b) < t * 1.4) {
+                                    id = B.AIR;
+                                }
+                            }
+                        }
+                    } else {
+                        id = y <= SEA ? B.WATER : B.AIR;
+                    }
+                    blocks[i] = id;
+                }
+            }
+        }
+
+        //Ores and underground pockets
+        const vein = (id, tries, size, ymin, ymax, replace) => {
+            for (let t = 0; t < tries; t++) {
+                let x = Math.floor(rng() * 16), z = Math.floor(rng() * 16);
+                let y = ymin + Math.floor(rng() * (ymax - ymin));
+                for (let s = 0; s < size; s++) {
+                    if (x >= 0 && x < 16 && z >= 0 && z < 16 && y > 0 && y < WORLD_H) {
+                        const i = idx(x, y, z);
+                        if (blocks[i] === replace) {
+                            blocks[i] = id;
+                        }
+                    }
+                    const r = rng();
+                    if (r < 0.33) {
+                        x += rng() < 0.5 ? -1 : 1;
+                    } else if (r < 0.66) {
+                        z += rng() < 0.5 ? -1 : 1;
+                    } else {
+                        y += rng() < 0.5 ? -1 : 1;
+                    }
+                }
+            }
+        };
+        vein(B.DIRT, 6, 22, 10, Math.max(12, maxH - 4), B.STONE);
+        vein(B.GRAVEL, 5, 20, 6, Math.max(8, maxH - 4), B.STONE);
+        vein(B.COAL_ORE, 18, 10, 5, 100, B.STONE);
+        vein(B.IRON_ORE, 12, 7, 5, 64, B.STONE);
+        vein(B.GOLD_ORE, 2, 7, 5, 32, B.STONE);
+        vein(B.CRYSTAL_ORE, 1, 5, 5, 17, B.STONE);
+
+        this.placeTrees(chunk, cols);
+        this.placePlants(chunk, cols, rng);
+    }
+
+    //Trees of this chunk and its neighbours, clipped to this chunk
+    placeTrees(chunk) {
+        const { blocks, meta } = chunk;
+        const x0 = chunk.cx * 16, z0 = chunk.cz * 16;
+        for (let dcx = -1; dcx <= 1; dcx++) {
+            for (let dcz = -1; dcz <= 1; dcz++) {
+                const ncx = chunk.cx + dcx, ncz = chunk.cz + dcz;
+                const trng = mulberry32(hash2(this.seed ^ 0x7eee, ncx, ncz));
+                const candidates = 12;
+                for (let t = 0; t < candidates; t++) {
+                    const tx = ncx * 16 + Math.floor(trng() * 16);
+                    const tz = ncz * 16 + Math.floor(trng() * 16);
+                    const roll = trng();
+                    const kind = trng();
+                    const heightRoll = trng();
+                    const c = this.columnCached(tx, tz);
+                    let chance = 0;
+                    if (c.biome === BIOME.FOREST) {
+                        chance = 0.72;
+                    } else if (c.biome === BIOME.GRASSLAND) {
+                        chance = 0.035;
+                    }
+                    if (roll >= chance || c.h < SEA) {
+                        continue;
+                    }
+                    const tall = c.biome === BIOME.FOREST && kind < 0.3;
+                    const trunk = tall ? 7 + Math.floor(heightRoll * 3) : 4 + Math.floor(heightRoll * 3);
+                    this.stampTree(blocks, meta, x0, z0, tx, c.h + 1, tz, trunk, tall);
+                }
+            }
+        }
+    }
+
+    stampTree(blocks, meta, x0, z0, tx, ty, tz, trunk, tall) {
+        const inside = (x, y, z) => x >= x0 && x < x0 + 16 && z >= z0 && z < z0 + 16 && y > 0 && y < WORLD_H;
+        const topY = ty + trunk - 1;
+        //Canopy
+        const r = tall ? 3 : 2;
+        const dyMin = tall ? -4 : -2;
+        for (let dy = dyMin; dy <= 1; dy++) {
+            for (let dx = -r; dx <= r; dx++) {
+                for (let dz = -r; dz <= r; dz++) {
+                    const x = tx + dx, y = topY + dy, z = tz + dz;
+                    if (!inside(x, y, z)) {
+                        continue;
+                    }
+                    let keep;
+                    const jitter = (hash3(this.seed, x, y, z) & 255) / 255;
+                    if (tall) {
+                        const rad = 2.7 - (dy - dyMin) * 0.42;
+                        keep = dx * dx + dz * dz <= rad * rad + jitter * 1.2;
+                    } else {
+                        const d = dx * dx + dz * dz + (dy + 0.5) * (dy + 0.5) * 1.6;
+                        keep = d <= 5.2 + jitter * 1.8;
+                    }
+                    if (!keep) {
+                        continue;
+                    }
+                    const i = idx(x - x0, y, z - z0);
+                    const cur = blocks[i];
+                    if (cur === B.AIR || cur === B.TALL_GRASS) {
+                        blocks[i] = B.LEAVES;
+                        meta[i] = 0;
+                    }
+                }
+            }
+        }
+        //Trunk (overwrites leaves)
+        for (let y = ty; y <= topY; y++) {
+            if (inside(tx, y, tz)) {
+                const i = idx(tx - x0, y, tz - z0);
+                const cur = blocks[i];
+                if (cur === B.AIR || cur === B.LEAVES || cur === B.TALL_GRASS) {
+                    blocks[i] = B.LOG;
+                }
+            }
+        }
+        if (inside(tx, ty - 1, tz)) {
+            const i = idx(tx - x0, ty - 1, tz - z0);
+            if (blocks[i] === B.GRASS) {
+                blocks[i] = B.DIRT;
+            }
+        }
+    }
+
+    placePlants(chunk, cols, rng) {
+        const { blocks, meta } = chunk;
+        const columnTop = (lx, lz) => {
+            for (let y = WORLD_H - 1; y > 0; y--) {
+                if (blocks[idx(lx, y, lz)] !== B.AIR) {
+                    return y;
+                }
+            }
+            return 0;
+        };
+        for (let lz = 0; lz < 16; lz++) {
+            for (let lx = 0; lx < 16; lx++) {
+                const c = cols[lz * 16 + lx];
+                const y = c.h;
+                if (y < SEA || y >= WORLD_H - 4) {
+                    continue;
+                }
+                const ground = blocks[idx(lx, y, lz)];
+                const above = idx(lx, y + 1, lz);
+                if (blocks[above] !== B.AIR) {
+                    continue;
+                }
+                const r = rng();
+                if (ground === B.GRASS) {
+                    if (c.biome === BIOME.GRASSLAND) {
+                        if (r < 0.2) {
+                            blocks[above] = B.TALL_GRASS;
+                        } else if (r < 0.225) {
+                            blocks[above] = rng() < 0.6 ? B.FLOWER_YELLOW : B.FLOWER_RED;
+                        }
+                    } else if (c.biome === BIOME.FOREST) {
+                        const shaded = columnTop(lx, lz) > y + 2;
+                        if (r < 0.09) {
+                            blocks[above] = B.TALL_GRASS;
+                        } else if (shaded && r < 0.11) {
+                            blocks[above] = rng() < 0.6 ? B.MUSHROOM_BROWN : B.MUSHROOM_RED;
+                        } else if (r < 0.115) {
+                            blocks[above] = B.FLOWER_RED;
+                        }
+                    }
+                }
+                if (ground === B.SAND && c.biome === BIOME.DESERT) {
+                    if (r < 0.006 && lx > 0 && lx < 15 && lz > 0 && lz < 15) {
+                        const hgt = 1 + Math.floor(rng() * 3);
+                        let free = true;
+                        for (const [dx, dz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
+                            for (let k = 1; k <= hgt; k++) {
+                                if (blocks[idx(lx + dx, y + k, lz + dz)] !== B.AIR) {
+                                    free = false;
+                                }
+                            }
+                        }
+                        if (free) {
+                            for (let k = 1; k <= hgt; k++) {
+                                blocks[idx(lx, y + k, lz)] = B.CACTUS;
+                            }
+                        }
+                    } else if (r < 0.016) {
+                        blocks[above] = B.DEAD_BUSH;
+                    }
+                }
+                //Reeds grow beside water
+                if ((ground === B.GRASS || ground === B.SAND || ground === B.DIRT) && y === SEA && r > 0.86) {
+                    let wet = false;
+                    for (const [dx, dz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
+                        const nx = lx + dx, nz = lz + dz;
+                        if (nx >= 0 && nx < 16 && nz >= 0 && nz < 16 && blocks[idx(nx, y, nz)] === B.WATER) {
+                            wet = true;
+                        }
+                    }
+                    if (wet) {
+                        const hgt = 1 + Math.floor(rng() * 3);
+                        for (let k = 1; k <= hgt; k++) {
+                            blocks[idx(lx, y + k, lz)] = B.REEDS;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    //Grow a tree at runtime (from a sapling); returns the block list to set
+    treeBlocks(x, y, z, rng) {
+        const tall = rng() < 0.2;
+        const trunk = tall ? 7 + Math.floor(rng() * 3) : 4 + Math.floor(rng() * 3);
+        const out = [];
+        const topY = y + trunk - 1;
+        const r = tall ? 3 : 2;
+        const dyMin = tall ? -4 : -2;
+        for (let dy = dyMin; dy <= 1; dy++) {
+            for (let dx = -r; dx <= r; dx++) {
+                for (let dz = -r; dz <= r; dz++) {
+                    const jitter = (hash3(this.seed, x + dx, topY + dy, z + dz) & 255) / 255;
+                    let keep;
+                    if (tall) {
+                        const rad = 2.7 - (dy - dyMin) * 0.42;
+                        keep = dx * dx + dz * dz <= rad * rad + jitter * 1.2;
+                    } else {
+                        const d = dx * dx + dz * dz + (dy + 0.5) * (dy + 0.5) * 1.6;
+                        keep = d <= 5.2 + jitter * 1.8;
+                    }
+                    if (keep) {
+                        out.push([x + dx, topY + dy, z + dz, B.LEAVES]);
+                    }
+                }
+            }
+        }
+        for (let yy = y; yy <= topY; yy++) {
+            out.push([x, yy, z, B.LOG]);
+        }
+        return { blocks: out, height: trunk + 2 };
+    }
+
+    //A dry land spot near the origin to spawn on
+    findSpawn() {
+        for (let r = 0; r < 600; r += 8) {
+            for (let a = 0; a < 16; a++) {
+                const ang = (a / 16) * Math.PI * 2;
+                const x = Math.round(Math.cos(ang) * r), z = Math.round(Math.sin(ang) * r);
+                const c = this.column(x, z);
+                if (c.h >= SEA + 1 && c.biome !== BIOME.OCEAN) {
+                    return { x: x + 0.5, z: z + 0.5, h: c.h };
+                }
+                if (r === 0) {
+                    break;
+                }
+            }
+        }
+        return { x: 0.5, z: 0.5, h: SEA + 1 };
+    }
+}

+ 21 - 0
src/web/Blocky/lib/three/LICENSE

@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright © 2010-2026 three.js authors
+
+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, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+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, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

Разница между файлами не показана из-за своего большого размера
+ 5 - 0
src/web/Blocky/lib/three/three.core.min.js


Разница между файлами не показана из-за своего большого размера
+ 5 - 0
src/web/Blocky/lib/three/three.module.min.js


Некоторые файлы не были показаны из-за большого количества измененных файлов