Compare commits
109
Commits
98fa45ebd1
...
native
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ced27d3400 | ||
|
|
90dd86b336 | ||
|
|
cbd662dc2a | ||
|
|
ed6f5fe0df | ||
|
|
25937f2c31 | ||
|
|
0d770c7bc4 | ||
|
|
a552883795 | ||
|
|
681d3afb4d | ||
|
|
527f2fb5a7 | ||
|
|
df7a1a94d6 | ||
|
|
a26d801f4e | ||
|
|
fe09e0cdd7 | ||
|
|
b9deda1a55 | ||
|
|
784bac7dd2 | ||
|
|
ac791b886e | ||
|
|
e751d22c6e | ||
|
|
dee07eaa0c | ||
|
|
c2e885f23a | ||
|
|
dfb110e0f8 | ||
|
|
8add5f852e | ||
|
|
487d5ae2a9 | ||
|
|
8a13854f39 | ||
|
|
5d374091cd | ||
|
|
d18fe19027 | ||
|
|
da44685f54 | ||
|
|
8e587f6446 | ||
|
|
47934b272c | ||
|
|
f308ab52f1 | ||
|
|
0c711b8163 | ||
|
|
69ad4b80d0 | ||
|
|
607be76ca6 | ||
|
|
4bdf5203d4 | ||
|
|
717d2cb766 | ||
|
|
94463b3cea | ||
|
|
2563ec3f69 | ||
|
|
b4f07272d8 | ||
|
|
357f8f2bd4 | ||
|
|
0f58a9cbfe | ||
|
|
dd53613758 | ||
|
|
277664d2d9 | ||
|
|
e72932456a | ||
|
|
edce5bac29 | ||
|
|
e1c2b13d1f | ||
|
|
60a7cae86e | ||
|
|
65865033c1 | ||
|
|
04c9511b6c | ||
|
|
c4eda256a1 | ||
|
|
f36176a872 | ||
|
|
c0c182490e | ||
|
|
00a679b053 | ||
|
|
38716ba8c3 | ||
|
|
6c38166325 | ||
|
|
c0c728c066 | ||
|
|
8c2364fa91 | ||
|
|
8230fe297d | ||
|
|
1b06fa29e1 | ||
|
|
188b05f598 | ||
|
|
eedaa955f6 | ||
|
|
94b0e3789c | ||
|
|
7369bf2e5f | ||
|
|
5301e0307c | ||
|
|
be0770f3cf | ||
|
|
7435a6bb7c | ||
|
|
17f39bfa4d | ||
|
|
b4adf85f03 | ||
|
|
a10748b5eb | ||
|
|
0564275f58 | ||
|
|
6bb2c87373 | ||
|
|
59bfed58bf | ||
|
|
2fa109026c | ||
|
|
afacd10a18 | ||
|
|
2282abc3bc | ||
|
|
95e058d659 | ||
|
|
a69db0cd2a | ||
|
|
313098892e | ||
|
|
605008f584 | ||
|
|
297d87164c | ||
|
|
6c6be61dd0 | ||
|
|
9bf6b98953 | ||
|
|
c74ddedd6e | ||
|
|
d48fa8cca5 | ||
|
|
51b5d148bd | ||
|
|
8b1ccb329a | ||
|
|
f95d036f72 | ||
|
|
e8ca9753f5 | ||
|
|
e013fbe550 | ||
|
|
76802ed430 | ||
|
|
e7fe663746 | ||
|
|
c639d1231b | ||
|
|
206cd38f26 | ||
|
|
22191d260c | ||
|
|
b726ce9695 | ||
|
|
71cbf901a5 | ||
|
|
8e14e9842a | ||
|
|
1fa47c027d | ||
|
|
818ce22dd6 | ||
|
|
7458a2d42a | ||
|
|
9bec0f3718 | ||
|
|
58b142cac3 | ||
|
|
4766c9a808 | ||
|
|
34f001285d | ||
|
|
9bc8fd992a | ||
|
|
0e2d8fdcac | ||
|
|
f449e081c6 | ||
|
|
4ff8821562 | ||
|
|
5baaf0239a | ||
|
|
fe0d857021 | ||
|
|
4683b09e10 | ||
|
|
ba4b2a8798 |
@@ -16,7 +16,8 @@ Always ask before making even the simplest models, unless it's coming from ports
|
|||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
- `server/`: the game server, world, saves and server-side game logic
|
- `server/`: the game server, world, saves and server-side game logic
|
||||||
- `client/`: the browser client: rendering, meshing and lighting workers, UI
|
- `client/`: the client: rendering, meshing and lighting workers, UI. `client/native/` runs it in the desktop app
|
||||||
|
- `desktop/`: the desktop app: its window, sound, singleplayer and client updates (see "Desktop first")
|
||||||
- `common/`: code shared by both, including world generation, the protocol and the modding API (`common/mod_api/`)
|
- `common/`: code shared by both, including world generation, the protocol and the modding API (`common/mod_api/`)
|
||||||
- `mods/`: mods, with JSON data (blocks, items, recipes, worldgen, tags), textures and TypeScript scripts
|
- `mods/`: mods, with JSON data (blocks, items, recipes, worldgen, tags), textures and TypeScript scripts
|
||||||
- `docs/`: modding docs and `docs/modding_plan.md`
|
- `docs/`: modding docs and `docs/modding_plan.md`
|
||||||
@@ -33,6 +34,8 @@ deno test -A tests/door_test.ts # one test file, prefer this while working
|
|||||||
deno task check-mods # validate and typecheck every mod in mods/
|
deno task check-mods # validate and typecheck every mod in mods/
|
||||||
deno task build # pack mods and build the client, then keeps rebuilding on changes
|
deno task build # pack mods and build the client, then keeps rebuilding on changes
|
||||||
deno task server # start a server with the mods from the last build
|
deno task server # start a server with the mods from the last build
|
||||||
|
deno task desktop # run the desktop app with what the last build made
|
||||||
|
deno task compile [linux] [windows] # build the desktop app's executables into dist/
|
||||||
deno fmt # format (tabs, 120 columns), applies to JSON too
|
deno fmt # format (tabs, 120 columns), applies to JSON too
|
||||||
deno task import KIND IN --output OUT # convert a java mod's resources, see tools/importer.ts
|
deno task import KIND IN --output OUT # convert a java mod's resources, see tools/importer.ts
|
||||||
```
|
```
|
||||||
@@ -50,6 +53,24 @@ engine, since other mods would hit the same wall. See "The Engine and the Base G
|
|||||||
When changing the modding API, update the docs that cover it: `MODS.md` and `docs/modding/`, which follows the layout of
|
When changing the modding API, update the docs that cover it: `MODS.md` and `docs/modding/`, which follows the layout of
|
||||||
`ports/neoforge-docs`.
|
`ports/neoforge-docs`.
|
||||||
|
|
||||||
|
## Desktop first
|
||||||
|
|
||||||
|
The desktop app is the main target and the browser a secondary one, so build and try new features in the desktop app
|
||||||
|
first. The app (`desktop/`) is an SDL3 window that the client draws into with Deno's WebGPU, running in a Deno worker
|
||||||
|
(`client/native/`), with sound through OpenAL Soft and a singleplayer server of its own.
|
||||||
|
|
||||||
|
- The client keeps using web APIs: WebGPU, Web Audio, fetch, WebSocket. Where Deno doesn't have one, polyfill the part
|
||||||
|
the game uses, like `client/native/web_audio.ts` does over OpenAL, instead of writing engine code only the desktop app
|
||||||
|
can run.
|
||||||
|
- What has to differ between the two goes through `Platform` (`client/platform.ts`), which `client/browser_platform.ts`
|
||||||
|
and `client/native/main.ts` implement, rather than checks for the DOM in shared code.
|
||||||
|
- Keep the browser working, but a browser limitation doesn't block a feature: it can be missing or simpler there.
|
||||||
|
- The client worker runs servers' mods, so it only gets the network and reading its own files, and gives up FFI once the
|
||||||
|
window's surface exists. Don't widen its permissions.
|
||||||
|
- The Windows build ships SDL3 and OpenAL Soft from `desktop/windows/`: unmodified files from their tagged releases,
|
||||||
|
with their licenses and where they came from in `credits.txt` there, which the app shows in its credits. Update it
|
||||||
|
along with the DLLs.
|
||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
- Classes are PascalCase, everything else is snake_case: functions, variables, fields, files and ids.
|
- Classes are PascalCase, everything else is snake_case: functions, variables, fields, files and ids.
|
||||||
@@ -76,6 +97,7 @@ When changing the modding API, update the docs that cover it: `MODS.md` and `doc
|
|||||||
|
|
||||||
`ports/` holds source from other projects to consult, not to edit:
|
`ports/` holds source from other projects to consult, not to edit:
|
||||||
|
|
||||||
|
- `ports/horizon`: cleanroom implementation of minecraft, very useful for a lot of various things
|
||||||
- `ports/neoforge` and `ports/neoforge-docs`: check these whenever adding to the modding API. The API should often
|
- `ports/neoforge` and `ports/neoforge-docs`: check these whenever adding to the modding API. The API should often
|
||||||
resemble NeoForge's.
|
resemble NeoForge's.
|
||||||
- `ports/justenoughitems`: check when working on the recipe viewer mod (`mods/recipe_viewer`).
|
- `ports/justenoughitems`: check when working on the recipe viewer mod (`mods/recipe_viewer`).
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ vanilla textures they use (pistons, redstone torches, rails) aren't in bworld ye
|
|||||||
**What `texture` does today.** It copies PNGs keeping their folders, since bworld already names a texture in a subfolder
|
**What `texture` does today.** It copies PNGs keeping their folders, since bworld already names a texture in a subfolder
|
||||||
by joining the folders with `_`, which is the same id the converted models use. A `.png.mcmeta` becomes the `.json` next
|
by joining the folders with `_`, which is the same id the converted models use. A `.png.mcmeta` becomes the `.json` next
|
||||||
to the png, keeping only its `animation` section: bworld reads the same format. It checks every texture against the
|
to the png, keeping only its `animation` section: bworld reads the same format. It checks every texture against the
|
||||||
limits a `.bmod` checks, skips Minecraft's own textures (the remap points at bworld's), and needs `--namespace` when a
|
limits a `.cubi` checks, skips Minecraft's own textures (the remap points at bworld's), and needs `--namespace` when a
|
||||||
folder holds textures of more than one mod, since a texture's namespace comes from the mod it ends up in. For Create
|
folder holds textures of more than one mod, since a texture's namespace comes from the mod it ends up in. For Create
|
||||||
0.5.0.j it copies 989 textures and 11 animations, and skips the six 512×512 title screen panoramas. Its textures and
|
0.5.0.j it copies 989 textures and 11 animations, and skips the six 512×512 title screen panoramas. Its textures and
|
||||||
models together make a mod `check-mods` accepts, with warnings only for the 27 missing textures.
|
models together make a mod `check-mods` accepts, with warnings only for the 27 missing textures.
|
||||||
@@ -393,8 +393,7 @@ Stonecutting is built, as `bworld:stonecutting` with the stonecutter, and the sa
|
|||||||
are mostly those. They're components with placement rules in `mods/bworld`, like the fence and trapdoor.
|
are mostly those. They're components with placement rules in `mods/bworld`, like the fence and trapdoor.
|
||||||
|
|
||||||
**S11. Layered ore features** (P2). Create's striated ores are bands of stone types, not blobs. A worldgen feature in
|
**S11. Layered ore features** (P2). Create's striated ores are bands of stone types, not blobs. A worldgen feature in
|
||||||
`mods/create/scripts/worldgen.ts`, or a data feature if STRUCTURES.md's data features exist by then. Zinc is a plain ore
|
`mods/create/scripts/worldgen.ts`, or a data feature if those exist by then. Zinc is a plain ore in `ores.json`.
|
||||||
in `ores.json`.
|
|
||||||
|
|
||||||
**S12. Mod config** (P1, built). A mod's settings and their defaults in its `config.json`, which the server script reads
|
**S12. Mod config** (P1, built). A mod's settings and their defaults in its `config.json`, which the server script reads
|
||||||
as `ctx.config` from `setup` on, like NeoForge's server configs. A server changes them in `config/<mod id>.json` next to
|
as `ctx.config` from `setup` on, like NeoForge's server configs. A server changes them in `config/<mod id>.json` next to
|
||||||
@@ -403,8 +402,7 @@ starting. Players' copies of a mod leave the config out, so what clients need is
|
|||||||
change settings with `test_game`'s fourth argument. Create's stress values, speed limits and processing times go there
|
change settings with `test_game`'s fourth argument. Create's stress values, speed limits and processing times go there
|
||||||
as the machines that use them are built.
|
as the machines that use them are built.
|
||||||
|
|
||||||
**S13. NBT** (P11). Reading and writing structure NBT, shared with STRUCTURES.md's `common/nbt.ts`, for schematics and
|
**S13. NBT** (P11). Reading and writing structure NBT, for schematics and ponder scenes.
|
||||||
ponder scenes.
|
|
||||||
|
|
||||||
**S14. Uploading files** (P11). A client sending a file to the server in pieces over a mod channel, for schematics.
|
**S14. Uploading files** (P11). A client sending a file to the server in pieces over a mod channel, for schematics.
|
||||||
|
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ install anything themselves.
|
|||||||
The base game is a mod too: `mods/bworld` is written against the same API as any other mod, so anything it does, your
|
The base game is a mod too: `mods/bworld` is written against the same API as any other mod, so anything it does, your
|
||||||
mod can do, and it's the best place to look for examples.
|
mod can do, and it's the best place to look for examples.
|
||||||
|
|
||||||
A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from
|
A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from one
|
||||||
TypeScript scripts: a server script for game logic, a client script for what players see, and a worldgen script for
|
TypeScript script, whose exports are its phases: `server` for game logic, `client` for what players see, and `worldgen`
|
||||||
terrain features.
|
for terrain features.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
deno task new-mod copper_tools "Copper Tools" # a new mod in mods/copper_tools, from templates/mod
|
deno task new-mod copper_tools "Copper Tools" # a new mod in mods/copper_tools, from templates/mod
|
||||||
@@ -22,7 +22,7 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
**Getting started**
|
**Getting started**
|
||||||
|
|
||||||
- [Getting Started](docs/modding/gettingstarted/index.md): making, checking, running and testing a mod
|
- [Getting Started](docs/modding/gettingstarted/index.md): making, checking, running and testing a mod
|
||||||
- [Mod Files](docs/modding/gettingstarted/modfiles.md): the folder layout, `manifest.json`, scripts and `.bmod` files
|
- [Mod Files](docs/modding/gettingstarted/modfiles.md): the folder layout, `manifest.json`, scripts and `.cubi` files
|
||||||
|
|
||||||
**Concepts**
|
**Concepts**
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
|
|
||||||
- [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement
|
- [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement
|
||||||
- [Block States](docs/modding/blocks/states.md): state bits, variants and facing
|
- [Block States](docs/modding/blocks/states.md): state bits, variants and facing
|
||||||
- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from a server script
|
- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from the server phase
|
||||||
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or
|
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or
|
||||||
show items
|
show items
|
||||||
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a
|
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a
|
||||||
@@ -51,7 +51,8 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
|
|
||||||
**Entities**
|
**Entities**
|
||||||
|
|
||||||
- [Entities](docs/modding/entities/index.md): animals, monsters, natural spawning, scripted entities and entity models
|
- [Entities](docs/modding/entities/index.md): animals, monsters, custom behaviors and their goals, how mobs get around,
|
||||||
|
natural spawning, scripted entities, entity models and their animations
|
||||||
- [Players](docs/modding/entities/players.md): the player API, health and hunger
|
- [Players](docs/modding/entities/players.md): the player API, health and hunger
|
||||||
|
|
||||||
**Inventories**
|
**Inventories**
|
||||||
@@ -62,6 +63,7 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
**Resources**
|
**Resources**
|
||||||
|
|
||||||
- [Textures](docs/modding/resources/textures.md)
|
- [Textures](docs/modding/resources/textures.md)
|
||||||
|
- [Sounds](docs/modding/resources/sounds.md): sound files, and playing them on a player's client
|
||||||
- [Block Models](docs/modding/resources/models.md)
|
- [Block Models](docs/modding/resources/models.md)
|
||||||
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing, stonecutting and your own recipe types
|
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing, stonecutting and your own recipe types
|
||||||
- [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to
|
- [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to
|
||||||
@@ -72,20 +74,22 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
**Everything else**
|
**Everything else**
|
||||||
|
|
||||||
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
||||||
- [Biomes](docs/modding/worldgen/biomes.md): surfaces, colors, trees and seasons
|
- [Biomes](docs/modding/worldgen/biomes.md): surfaces, colors and seasons
|
||||||
- [Screens](docs/modding/gui/index.md): plain screens, inventory overlays and drawing with `Graphics`
|
- [Screens](docs/modding/gui/index.md): plain screens, inventory overlays and drawing with `Graphics`
|
||||||
|
- [HUD](docs/modding/gui/hud.md): layers drawn over the world, like the base game's hotbar and hearts
|
||||||
- [Networking](docs/modding/networking/index.md): how players get mods and the world
|
- [Networking](docs/modding/networking/index.md): how players get mods and the world
|
||||||
- [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last
|
- [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last
|
||||||
- [Config](docs/modding/misc/config.md): settings a server can change, like how fast a machine works
|
- [Config](docs/modding/misc/config.md): settings a server can change, like how fast a machine works
|
||||||
- [Commands](docs/modding/misc/commands.md)
|
- [Commands](docs/modding/misc/commands.md)
|
||||||
- [Time](docs/modding/misc/time.md): ticks, timers, days and nights
|
- [Time](docs/modding/misc/time.md): ticks, timers, days and nights
|
||||||
|
- [Schematics](docs/modding/misc/schematics.md): saving a box of the world, blocks, data and entities, to a file
|
||||||
- [Engine Access](docs/modding/misc/engine.md): reaching into the engine and hooking its methods, for what the API
|
- [Engine Access](docs/modding/misc/engine.md): reaching into the engine and hooking its methods, for what the API
|
||||||
doesn't cover yet
|
doesn't cover yet
|
||||||
|
|
||||||
## API Types
|
## API Types
|
||||||
|
|
||||||
The API types are the reference for everything scripts can call. Scripts import them as `bworld/server`, `bworld/client`
|
The API types are the reference for everything scripts can call. Scripts import them as `cubi/server`, `cubi/client`,
|
||||||
and `bworld/worldgen`, and they live in [`common/mod_api/`](common/mod_api/).
|
`cubi/shared`, `cubi/worldgen` and `cubi/content`, and they live in [`common/mod_api/`](common/mod_api/).
|
||||||
|
|
||||||
A few parts of those types aren't built yet and throw when used: forms, custom screens, HUD elements and keybinds.
|
A few parts of those types aren't built yet and throw when used: forms, custom screens and keybinds.
|
||||||
[`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the mod API.
|
[`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the mod API.
|
||||||
|
|||||||
-892
@@ -1,892 +0,0 @@
|
|||||||
# Structures and Features
|
|
||||||
|
|
||||||
A plan for generating structures (villages, ruins, towers) and data-driven features (fossils, boulders, springs) in
|
|
||||||
bworld, in bworld's data style, while reading Minecraft Java's datapack formats closely enough that datapacks and mods
|
|
||||||
like [Trek](ports/trek) can be imported with a tool instead of rewritten.
|
|
||||||
|
|
||||||
Nothing here is built yet. Numbers about Trek come from reading every file in `ports/trek`.
|
|
||||||
|
|
||||||
## Where We Are
|
|
||||||
|
|
||||||
What world generation has today (see [World Generation](docs/modding/worldgen/index.md)):
|
|
||||||
|
|
||||||
- **The server generates every chunk** (`server/game/world.ts`, `common/generation.ts`). Players only get finished
|
|
||||||
chunks, so generation code and data never have to reach clients.
|
|
||||||
- **Three passes per chunk:** terrain (data, see [terrain.md](docs/modding/worldgen/terrain.md)), then ores
|
|
||||||
(`worldgen/ores.json`), then features, code or data, by step. The base game's trees are a code feature in
|
|
||||||
`vegetal_decoration`.
|
|
||||||
- **Chunks generate alone.** A feature may write up to one chunk away. Those writes are "spills" that only fill air in
|
|
||||||
the neighbor, so the result doesn't depend on which chunk generates first.
|
|
||||||
- **Determinism matters at chunk borders.** Every chunk generated is saved whole, like Minecraft, so a change to
|
|
||||||
generation only shows in chunks never generated before. A chunk generated next to a saved one still takes the saved
|
|
||||||
one's spills from generation, so features cross the border the same way only when generation hasn't changed.
|
|
||||||
- **Heights and biomes for any column**, without generating its chunk: `OverworldTerrain.column` and `estimate_biome`.
|
|
||||||
The biome is exact away from coasts and cliffs. The height is the height before 3D noise, so it isn't the real
|
|
||||||
surface.
|
|
||||||
- **Blocks:** numeric states (up to 16 bits), `variants`, `parts`, shapes, tile data, containers, components and shared
|
|
||||||
rules. Tags exist for blocks, items and entities. Biomes are a registry of data (`worldgen/biomes/` in a mod), but
|
|
||||||
which one a column gets is data too, a biome source's rules (see [biomes.md](docs/modding/worldgen/biomes.md)).
|
|
||||||
- **Loot:** a block's `drops` is one item id. There are no loot tables.
|
|
||||||
|
|
||||||
What's missing for structures:
|
|
||||||
|
|
||||||
- anything planned before blocks exist, or that spans more than three chunks;
|
|
||||||
- a block template format, and turning blocks when a piece is turned;
|
|
||||||
- terrain shaped around what's placed on it;
|
|
||||||
- a way to read Minecraft's content: NBT, `minecraft:` ids, string block states.
|
|
||||||
|
|
||||||
## Features and Structures
|
|
||||||
|
|
||||||
The same split as Minecraft's. A **feature** is a small thing placed while a chunk is decorated, like a boulder, a
|
|
||||||
spring or a fossil. It's decided from that chunk alone and forgotten once it's written. A **structure** is planned
|
|
||||||
before any block exists: a grid picks where structures start, the start is assembled into pieces with bounding boxes,
|
|
||||||
and every chunk a piece overlaps writes its own part of it. Structures can be large, made of many pieces, kept apart
|
|
||||||
from each other, and found again (`/locate`).
|
|
||||||
|
|
||||||
The order a chunk generates in becomes:
|
|
||||||
|
|
||||||
```
|
|
||||||
1. structure starts which structures overlap this chunk, assembled into pieces (cached, never saved)
|
|
||||||
2. terrain the overworld, shaped around pieces that adapt the terrain
|
|
||||||
3. ores as now
|
|
||||||
4. structures each overlapping piece writes the blocks inside this chunk, by step
|
|
||||||
5. features data features and script features, by step
|
|
||||||
```
|
|
||||||
|
|
||||||
Steps order structures and features the way Minecraft's decoration steps do, so a village is placed before trees and
|
|
||||||
flowers decorate around it: `raw_generation`, `lakes`, `local_modifications`, `underground_structures`,
|
|
||||||
`surface_structures`, `strongholds`, `underground_ores`, `underground_decoration`, `fluid_springs`,
|
|
||||||
`vegetal_decoration`, `top_layer_modification`. Script features from `register_feature` keep running last, as now.
|
|
||||||
|
|
||||||
## Principles
|
|
||||||
|
|
||||||
1. **bworld's data style.** Every JSON file has `format_version`, a wrapper key and an `id`, lives in a plural folder,
|
|
||||||
and is checked by `check-mods`. Inside the wrapper, fields keep **Minecraft's names and meanings**, so the Minecraft
|
|
||||||
Wiki's documentation applies, and importing a datapack is mostly renaming ids.
|
|
||||||
2. **Templates stay `.nbt`.** Minecraft's structure template format, unchanged. Templates can be built in Minecraft with
|
|
||||||
structure blocks and saved, read by existing NBT tools, and imported without converting them.
|
|
||||||
3. **One mapping from Minecraft to bworld, written once.** The base game ships what each `minecraft:` block, item, biome
|
|
||||||
and entity is in bworld. A template can keep vanilla ids in its palette and the mapping is applied when it loads, so
|
|
||||||
every imported pack gets better when a block is added to bworld.
|
|
||||||
4. **Deterministic, nothing saved.** Starts and pieces are recomputed from the seed whenever they're needed, like
|
|
||||||
everything else generation makes. No structure data goes into saves.
|
|
||||||
5. **Server only.** Templates, pools, structures, features and loot tables are server data, left out of the copy of a
|
|
||||||
`.bmod` players download, like worldgen scripts are now. The only thing clients need is the blocks.
|
|
||||||
6. **No goal of matching Minecraft's positions.** bworld's seeds and random numbers aren't Java's, and its terrain is
|
|
||||||
its own, so structures land in different places than in Minecraft with the same seed. What has to match is how pieces
|
|
||||||
fit together and what each field means.
|
|
||||||
|
|
||||||
## Data Formats
|
|
||||||
|
|
||||||
### Mod Folders
|
|
||||||
|
|
||||||
New folders, next to the ones a mod has now (see [Mod Files](docs/modding/gettingstarted/modfiles.md)):
|
|
||||||
|
|
||||||
```
|
|
||||||
copper_tools/
|
|
||||||
structures/<path>.nbt # templates, Minecraft's structure format
|
|
||||||
worldgen/structures/<path>.json # what a structure is: its start pool, size, biomes, terrain adaptation
|
|
||||||
worldgen/structure_sets/<path>.json # where structures start
|
|
||||||
worldgen/template_pools/<path>.json # pieces to choose from
|
|
||||||
worldgen/processor_lists/<path>.json # changes made to template blocks as they're placed
|
|
||||||
worldgen/features/<path>.json # data features: what, where, which biomes
|
|
||||||
loot_tables/<path>.json # what chests from templates are filled with
|
|
||||||
tags/biomes/<namespace>/<path>.json # biome tags, like tags/blocks
|
|
||||||
remaps/<namespace>.json # what another game's ids are here, in the base game: remaps/minecraft.json
|
|
||||||
```
|
|
||||||
|
|
||||||
Ids are the mod's namespace and the path, like `trek:village/plains/town_centers`. Paths can have folders, as in
|
|
||||||
Minecraft. Templates take their id from their path (`structures/ruins/ruin_1.nbt` is `copper_tools:ruins/ruin_1`). JSON
|
|
||||||
files also state it in `id`, and `check-mods` checks that it matches the path.
|
|
||||||
|
|
||||||
`check-mods` checks every reference: pools, templates, processor lists, structures, sets, loot tables, tags, blocks and
|
|
||||||
biomes. Missing references are errors, except the ones in an import's report (see [The Importer](#the-importer)).
|
|
||||||
|
|
||||||
### Named State Values
|
|
||||||
|
|
||||||
Blocks' states get optional value names, in Minecraft's order:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"states": [
|
|
||||||
{ "name": "facing", "bits": 2, "default": 0, "values": ["north", "east", "south", "west"] },
|
|
||||||
{ "name": "half", "bits": 1, "default": 0, "values": ["bottom", "top"] },
|
|
||||||
{ "name": "shape", "bits": 3, "default": 0, "values": ["straight", "inner_left", "inner_right", "outer_left", "outer_right"] }
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
- `bits` can be left out when `values` is given: it's the fewest bits that fit them.
|
|
||||||
- Variant and part conditions can use names: `"facing=east,half=top"`, the same as `"facing=1,half=1"`.
|
|
||||||
- Existing blocks keep working unchanged. The base game's blocks get names that match Minecraft's (trapdoors and fences
|
|
||||||
already use Minecraft's state names and orders).
|
|
||||||
- Named values are what the remap and turning below are built on.
|
|
||||||
|
|
||||||
### Turning Blocks
|
|
||||||
|
|
||||||
Jigsaw turns pieces by 90, 180 or 270 degrees, so every block's states have to turn with the piece, like Minecraft's
|
|
||||||
`BlockState.rotate`. With named values, turning works out from the names:
|
|
||||||
|
|
||||||
| State | Turned clockwise by 90° |
|
|
||||||
| ------------------------------------------------------ | ------------------------------------------------------------- |
|
|
||||||
| values are directions (`north`, `east`, `south`, ...) | each value turns: `north` → `east`, `up` stays `up` |
|
|
||||||
| values are `x`, `y`, `z` (`axis`) | `x` ↔ `z` |
|
|
||||||
| the state's name is a direction (`north`, `east`, ...) | values move between states: `north=1` becomes `east=1` |
|
|
||||||
| `rotation` with 16 values (signs, banners, heads) | +4 |
|
|
||||||
| anything else (`half`, `open`, `shape` of stairs) | unchanged, like Minecraft (a stair's shape is relative to it) |
|
|
||||||
|
|
||||||
Odd cases, like rails' `shape` (`north_south` ↔ `east_west`, `ascending_east` → `ascending_south`), name their turns
|
|
||||||
explicitly:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"name": "shape",
|
|
||||||
"values": ["north_south", "east_west", "ascending_east", "..."],
|
|
||||||
"turns": { "north_south": "east_west", "...": "..." }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Mirroring (Minecraft's `Mirror`) uses the same rules plus `left` ↔ `right` in values. Jigsaw never mirrors, so it can
|
|
||||||
wait.
|
|
||||||
|
|
||||||
Unit tests turn a few of each kind four times and check they're back where they started, and that turning a fence
|
|
||||||
connected north and east gives one connected east and south.
|
|
||||||
|
|
||||||
### Remaps
|
|
||||||
|
|
||||||
What another game's ids are in bworld. The base game ships `mods/bworld/remaps/minecraft.json`; any mod can add one for
|
|
||||||
its own blocks, like Trek's, or for another mod's namespace, like `remaps/waystones.json`.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"format_version": 1,
|
|
||||||
"remap": {
|
|
||||||
"namespace": "minecraft",
|
|
||||||
"blocks": {
|
|
||||||
"grass_block": "bworld:grass",
|
|
||||||
"farmland": "bworld:hoed_dirt",
|
|
||||||
"snow_block": "bworld:snow_block",
|
|
||||||
"spruce_stairs": "bworld:spruce_stairs",
|
|
||||||
"chest": { "id": "bworld:chest", "states": { "facing": "facing" } },
|
|
||||||
"oak_wall_sign": {
|
|
||||||
"id": "bworld:oak_sign",
|
|
||||||
"states": { "facing": "facing" },
|
|
||||||
"set": { "on_wall": "true" }
|
|
||||||
},
|
|
||||||
"short_grass": "bworld:short_grass",
|
|
||||||
"grass": "bworld:short_grass",
|
|
||||||
"structure_void": null
|
|
||||||
},
|
|
||||||
"items": { "wheat_seeds": "bworld:wheat_seeds" },
|
|
||||||
"biomes": {
|
|
||||||
"plains": "bworld:plains",
|
|
||||||
"sunflower_plains": "bworld:plains",
|
|
||||||
"old_growth_pine_taiga": "bworld:taiga"
|
|
||||||
},
|
|
||||||
"entities": { "chicken": "bworld:chicken" },
|
|
||||||
"block_tags": { "features_cannot_replace": "#bworld:features_cannot_replace" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- A string maps to that id, carrying over every state whose name and value names match. That's most blocks once their
|
|
||||||
states are named like Minecraft's.
|
|
||||||
- `{ id, states, set }` renames states and sets fixed ones. Properties bworld doesn't model (`waterlogged`, `powered`)
|
|
||||||
are dropped.
|
|
||||||
- `null` means known, and nothing there. Ids not in the map at all are reported as unmapped and, while generating,
|
|
||||||
treated as nothing: the template keeps whatever the world had in that spot.
|
|
||||||
- Old and new names both go in, since templates from different Minecraft versions use both. Trek's templates were saved
|
|
||||||
by 1.19 to 1.21 (DataVersion 3105 to 3953), so `grass` and `short_grass` both appear.
|
|
||||||
- Remaps apply when data loads: to template palettes, and to ids in processor lists, pools, loot tables and tags that
|
|
||||||
still use a `minecraft:` id. The engine only ever deals with bworld ids.
|
|
||||||
|
|
||||||
### Templates
|
|
||||||
|
|
||||||
`.nbt` files exactly as Minecraft saves them (gzipped, big endian):
|
|
||||||
|
|
||||||
```
|
|
||||||
{ DataVersion, size: [x, y, z], palette: [{ Name, Properties }], blocks: [{ pos, state, nbt? }], entities: [{ pos, blockPos, nbt }] }
|
|
||||||
```
|
|
||||||
|
|
||||||
`palettes` (several palettes, one picked at random) is read too. Meanings that matter:
|
|
||||||
|
|
||||||
- **A position missing from `blocks` keeps what the world has there** (Minecraft's structure void). Air in `blocks`
|
|
||||||
clears what was there, except in `legacy_single_pool_element` pieces, which skip air.
|
|
||||||
- **`nbt` is a block entity:**
|
|
||||||
- `minecraft:chest` and `minecraft:barrel` with `LootTable` become tile data that fills the container the first time
|
|
||||||
it's opened.
|
|
||||||
- `minecraft:jigsaw` holds `name`, `target`, `pool`, `joint` and `final_state`, used by assembly.
|
|
||||||
- Anything else (signs, spawners, banners) is ignored until bworld has a use for it.
|
|
||||||
- **`entities`** are spawned the first time their chunk is generated, mapped through the remap. Unmapped ones are
|
|
||||||
skipped.
|
|
||||||
|
|
||||||
An NBT reader (`common/nbt.ts`) is about 60 lines. Templates are parsed once and kept as the remapped palette and
|
|
||||||
compact arrays: positions and palette indexes as typed arrays, block entities in a map. They're packed into `.bmod`
|
|
||||||
files as they are, like textures, and only the server copy keeps them.
|
|
||||||
|
|
||||||
### Processor Lists
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"format_version": 1,
|
|
||||||
"processor_list": {
|
|
||||||
"id": "trek:stone/mossify_20",
|
|
||||||
"processors": [{
|
|
||||||
"processor_type": "minecraft:rule",
|
|
||||||
"rules": [{
|
|
||||||
"location_predicate": { "predicate_type": "minecraft:always_true" },
|
|
||||||
"input_predicate": {
|
|
||||||
"predicate_type": "minecraft:random_block_match",
|
|
||||||
"block": "minecraft:stone_bricks",
|
|
||||||
"probability": 0.2
|
|
||||||
},
|
|
||||||
"output_state": { "Name": "minecraft:mossy_stone_bricks" }
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
One of the two rules in Trek's `stone/mossify_20`, as imported: its `minecraft:` ids stay as they are and the remap
|
|
||||||
turns them into `bworld:stone_bricks` and `bworld:mossy_stone_bricks` when it loads.
|
|
||||||
|
|
||||||
What Trek uses, which is the first set to support:
|
|
||||||
|
|
||||||
- **`rule`**, with input and location predicates `always_true`, `block_match`, `blockstate_match`, `random_block_match`,
|
|
||||||
`random_blockstate_match` and `tag_match`, and position predicates `linear_pos` and `axis_aligned_linear_pos`. The
|
|
||||||
output is `output_state` (`{ Name, Properties }`, remapped like palettes).
|
|
||||||
- **`protected_blocks`**: never replace blocks in a tag.
|
|
||||||
|
|
||||||
Random predicates are seeded from the block's world position and the world's seed, so a block always comes out the same
|
|
||||||
whichever chunk places it. `minecraft:empty` is a list with no processors. Processor types are open: worldgen scripts
|
|
||||||
can register more with `register_processor`.
|
|
||||||
|
|
||||||
### Template Pools
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"format_version": 1,
|
|
||||||
"template_pool": {
|
|
||||||
"id": "trek:village/plains/town_centers",
|
|
||||||
"fallback": "minecraft:empty",
|
|
||||||
"elements": [
|
|
||||||
{
|
|
||||||
"weight": 49,
|
|
||||||
"element": {
|
|
||||||
"element_type": "minecraft:single_pool_element",
|
|
||||||
"location": "trek:village/plains/town_centers/plains_market_1",
|
|
||||||
"processors": "minecraft:empty",
|
|
||||||
"projection": "rigid"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Element types: `single_pool_element`, `legacy_single_pool_element` (skips the template's air), `list_pool_element`
|
|
||||||
(several elements in the same spot), `feature_pool_element` (a data feature at the jigsaw's position) and
|
|
||||||
`empty_pool_element`. `projection` is `rigid` (placed as built) or `terrain_matching` (each column follows the ground,
|
|
||||||
for paths). Element types keep their `minecraft:` names: they're types, not content, so remaps don't apply to them.
|
|
||||||
|
|
||||||
### Structures
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"format_version": 1,
|
|
||||||
"structure": {
|
|
||||||
"id": "trek:overworld/very_common/rocks",
|
|
||||||
"type": "minecraft:jigsaw",
|
|
||||||
"biomes": "#trek:combination/plains_forest_desert_no_snow_jungle",
|
|
||||||
"start_pool": "trek:overworld/very_common/rocks",
|
|
||||||
"size": 1,
|
|
||||||
"start_height": { "absolute": 0 },
|
|
||||||
"project_start_to_heightmap": "WORLD_SURFACE_WG",
|
|
||||||
"max_distance_from_center": 64,
|
|
||||||
"terrain_adaptation": "none",
|
|
||||||
"step": "surface_structures"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `type` is `minecraft:jigsaw` for now. Other types, like Undergarden's `bigger_jigsaw` (jigsaw with a higher `size`
|
|
||||||
limit), map onto it with different limits. Mods can register types written in code from a worldgen script with
|
|
||||||
`register_structure_type`, for structures made in code instead of from templates.
|
|
||||||
- `size` is how many connections deep assembly goes. Minecraft allows up to 20.
|
|
||||||
- `project_start_to_heightmap` is `WORLD_SURFACE_WG` (the surface, or the water's surface) or `OCEAN_FLOOR_WG` (the
|
|
||||||
ground under water).
|
|
||||||
- `terrain_adaptation` is `none`, `beard_thin`, `beard_box`, `bury` or `encapsulate`. See
|
|
||||||
[Terrain Adaptation](#terrain-adaptation).
|
|
||||||
- `spawn_overrides` replaces which mobs spawn inside the structure. It can wait until natural spawning reads it.
|
|
||||||
|
|
||||||
### Structure Sets
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"format_version": 1,
|
|
||||||
"structure_set": {
|
|
||||||
"id": "trek:overworld/medium",
|
|
||||||
"structures": [{ "structure": "trek:overworld/medium/oasis", "weight": 1 }],
|
|
||||||
"placement": {
|
|
||||||
"type": "minecraft:random_spread",
|
|
||||||
"spacing": 30,
|
|
||||||
"separation": 12,
|
|
||||||
"spread_type": "linear",
|
|
||||||
"salt": 98700002,
|
|
||||||
"frequency": 1,
|
|
||||||
"exclusion_zone": { "chunk_count": 6, "other_set": "trek:village" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**`random_spread`:** the world is split into cells of `spacing` × `spacing` chunks. Each cell has at most one start, in
|
|
||||||
a chunk picked inside its first `spacing - separation` chunks on each axis. `linear` picks evenly, `triangular` leans
|
|
||||||
towards the middle. The random generator is seeded from the world's seed, the set's id, `salt` and the cell, so sets
|
|
||||||
don't move each other, and any chunk can find the starts near it without generating anything. Then:
|
|
||||||
|
|
||||||
1. `frequency` skips some starts.
|
|
||||||
2. One of `structures` is picked by weight. A structure whose biome check fails is removed and another is picked, as in
|
|
||||||
Minecraft.
|
|
||||||
3. The start is skipped if a start of `exclusion_zone.other_set` is within `chunk_count` chunks.
|
|
||||||
|
|
||||||
**`concentric_rings`** (strongholds) comes later. Trek only uses it to change vanilla's strongholds.
|
|
||||||
|
|
||||||
### Data Features
|
|
||||||
|
|
||||||
Minecraft splits a feature into a configured feature (what) and a placed feature (where), and adds features to biomes in
|
|
||||||
the biome's own file (NeoForge adds biome modifiers so mods can add to biomes they don't own). bworld's biomes aren't
|
|
||||||
data, so a feature says where it goes itself, in one file:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"format_version": 1,
|
|
||||||
"feature": {
|
|
||||||
"id": "trek:monster_room/upper/default",
|
|
||||||
"type": "minecraft:fossil",
|
|
||||||
"config": {
|
|
||||||
"max_empty_corners_allowed": 4,
|
|
||||||
"fossil_structures": ["trek:monster_room/default"],
|
|
||||||
"overlay_structures": ["trek:monster_room/empty"],
|
|
||||||
"fossil_processors": "trek:monster_room/upper/default",
|
|
||||||
"overlay_processors": "minecraft:empty"
|
|
||||||
},
|
|
||||||
"placement": [
|
|
||||||
{ "type": "minecraft:count", "count": 10 },
|
|
||||||
{ "type": "minecraft:rarity_filter", "chance": 800 },
|
|
||||||
{ "type": "minecraft:in_square" },
|
|
||||||
{
|
|
||||||
"type": "minecraft:height_range",
|
|
||||||
"height": {
|
|
||||||
"type": "minecraft:very_biased_to_bottom",
|
|
||||||
"min_inclusive": { "absolute": 24 },
|
|
||||||
"max_inclusive": { "below_top": 0 },
|
|
||||||
"inner": 10
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"biomes": "#bworld:is_overworld",
|
|
||||||
"step": "underground_structures"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
That's Trek's `monster_room/upper/default`, its configured and placed feature joined, with `biomes` and `step` added.
|
|
||||||
|
|
||||||
- Height providers (in `height_range` and structures' `start_height`): `constant` (and a bare `{ "absolute": y }`),
|
|
||||||
`uniform`, `trapezoid`, `biased_to_bottom` and `very_biased_to_bottom`. Heights are `absolute`, `above_bottom` or
|
|
||||||
`below_top`.
|
|
||||||
- `type` and `config` are Minecraft's configured feature. `placement` is Minecraft's placed feature modifiers: `count`,
|
|
||||||
`rarity_filter`, `in_square`, `height_range`, `heightmap`, `biome`, `surface_relative_threshold_filter`,
|
|
||||||
`block_predicate_filter`.
|
|
||||||
- First feature types, from what Trek uses: `fossil` (a template, which covers Trek's monster rooms), `simple_block`,
|
|
||||||
`block_column`, `disk` and `spring_feature`, and `ore` and `random_patch` for the base game. Its trees stay code. The
|
|
||||||
format, `simple_block`, `block_column`, the first placement modifiers and `register_feature_type` are built already,
|
|
||||||
see [Data Features](docs/modding/worldgen/index.md#data-features).
|
|
||||||
- Worldgen scripts register more types with `register_feature_type(id, (chunk, config, origin) => ...)`, so a data
|
|
||||||
feature can use a type a mod wrote in code. `register_feature` stays for features that are only code.
|
|
||||||
- **Features that reach into other chunks are evaluated from each chunk they touch.** Where a feature starts is decided
|
|
||||||
from its own chunk's random numbers and heights, which neighbors can recompute. A template feature like a fossil then
|
|
||||||
writes its part in each chunk like a structure piece does. That lifts the "spills only fill air" limit for everything
|
|
||||||
placed from templates. Placement that needs to read a neighbor's blocks (not just heights) stays limited to its own
|
|
||||||
chunk.
|
|
||||||
|
|
||||||
### Biome Tags
|
|
||||||
|
|
||||||
`tags/biomes/<namespace>/<path>.json`, like block tags, with `"biomes"` as a tag registry in `ctx.tags`. The base game
|
|
||||||
ships tags for its biomes under Minecraft's names (`#bworld:is_forest`, `#bworld:is_ocean`,
|
|
||||||
`#bworld:has_structure/...`), and `remaps/minecraft.json` maps `#minecraft:is_forest` to them, so imported structures
|
|
||||||
that use vanilla's biome tags work. A biome id or tag in a structure that maps to nothing is reported, and that
|
|
||||||
structure never generates.
|
|
||||||
|
|
||||||
### Loot Tables
|
|
||||||
|
|
||||||
A subset of Minecraft's format: `pools` with `rolls` (a number or `{ min, max }`), entries of type `item`, `tag`,
|
|
||||||
`loot_table` and `empty` with `weight`, and the functions `set_count` and `set_damage`, enough for chest loot. Item ids
|
|
||||||
are remapped. Missing items are skipped and reported.
|
|
||||||
|
|
||||||
A chest placed from a template keeps `{ loot_table, loot_seed }` in its tile data. `bworld:storage` fills the container
|
|
||||||
the first time it's opened, then forgets the table, like Minecraft. The roll is seeded by `loot_seed`, so the same chest
|
|
||||||
always gets the same loot. The server API gets `ctx.loot.roll(id, seed)` for mods that want loot elsewhere.
|
|
||||||
|
|
||||||
## Engine
|
|
||||||
|
|
||||||
### Finding Starts
|
|
||||||
|
|
||||||
`common/structures/starts.ts`: for a chunk, every start whose structure could reach it. A structure's reach is
|
|
||||||
`max_distance_from_center` plus its largest template, capped at 128 blocks like Minecraft's jigsaw, so each set checks
|
|
||||||
the cells within 8 chunks. That's cheap: it's random numbers, plus biome and height lookups at the few candidate starts.
|
|
||||||
|
|
||||||
### Heights and Biomes Outside the Chunk
|
|
||||||
|
|
||||||
Assembly needs the surface at columns in chunks that don't exist yet: at the start, and for every `terrain_matching`
|
|
||||||
piece. Add `surface_at(x, z)` to the overworld, the exact surface the terrain pass would make, found by sampling the
|
|
||||||
column's 3D density downward from its rough height. Same for `ocean_floor_at`. Biomes come from `estimate_biome`, made
|
|
||||||
exact where it isn't. These need to be fast and must never disagree with the terrain pass. A test compares them against
|
|
||||||
generated chunks for many columns.
|
|
||||||
|
|
||||||
### Assembly
|
|
||||||
|
|
||||||
`common/structures/jigsaw.ts`, following Minecraft's `JigsawPlacement`. This is the part to compare most carefully
|
|
||||||
against Minecraft's source (decompiled through a NeoForge workspace; `ports/neoforge` only has patches):
|
|
||||||
|
|
||||||
1. Pick the start element from `start_pool` by weight, and a random rotation. Put it at the start chunk's corner, at
|
|
||||||
`start_height`, plus the surface at the middle of its box when `project_start_to_heightmap` is set.
|
|
||||||
2. Keep a queue of placed pieces with their depth, highest `placement_priority` first. For each piece, its jigsaw blocks
|
|
||||||
are shuffled, then sorted by `selection_priority`.
|
|
||||||
3. For a jigsaw block pointing out of its piece: the candidates are its pool's elements in weighted random order (or
|
|
||||||
only the `fallback` pool's at the last depth), each in its 4 rotations, in random order. An element connects when it
|
|
||||||
has a jigsaw that faces back towards this one, whose `name` is this one's `target`, and, for jigsaws facing up or
|
|
||||||
down with `aligned` joints, whose top points the same way.
|
|
||||||
4. The candidate's box must fit: inside the box `max_distance_from_center` around the start, and not overlapping placed
|
|
||||||
pieces. A jigsaw pointing into its own piece (like a house's door into its room) only has to fit inside that piece's
|
|
||||||
free space. `terrain_matching` candidates get the ground height at the jigsaw.
|
|
||||||
5. The first candidate that fits is placed and queued with depth + 1, if that's within `size`. An `empty` element ends
|
|
||||||
that jigsaw.
|
|
||||||
6. Jigsaw blocks become their `final_state` when placed.
|
|
||||||
|
|
||||||
Everything random comes from one generator seeded by the world's seed and the start's chunk, so a start assembles the
|
|
||||||
same in any chunk that asks. The result is a list of pieces: element, position, rotation, box. Starts are kept in an LRU
|
|
||||||
cache in the world, since every chunk a start reaches asks for it.
|
|
||||||
|
|
||||||
`use_expansion_hack` (Minecraft widening rigid villages' boxes for old templates) is read and ignored until something
|
|
||||||
looks wrong without it.
|
|
||||||
|
|
||||||
### Placing a Piece
|
|
||||||
|
|
||||||
`common/structures/place.ts`, for each piece box that overlaps the chunk:
|
|
||||||
|
|
||||||
1. Go through the template's blocks inside the chunk, turned by the piece's rotation (position and states, see
|
|
||||||
[Turning Blocks](#turning-blocks)).
|
|
||||||
2. Run the piece's processors. Air from `legacy_single_pool_element` pieces and unmapped blocks are skipped, and
|
|
||||||
`protected_blocks` blocks in the world are kept.
|
|
||||||
3. `terrain_matching` pieces move each column to the ground there.
|
|
||||||
4. Write it, overwriting whatever the terrain pass put there (unlike spills).
|
|
||||||
5. Block entities that matter become tile data. Entities are queued to spawn (see [Entities](#entities)).
|
|
||||||
|
|
||||||
Only the chunk's own blocks are written, so the result doesn't depend on which chunk generates first. That's the same
|
|
||||||
promise spills keep now, in a different way.
|
|
||||||
|
|
||||||
### Terrain Adaptation
|
|
||||||
|
|
||||||
Minecraft's `beard` options change the terrain's density near pieces. bworld's terrain is heights plus 3D density too,
|
|
||||||
so it's the same idea. The terrain pass gets the boxes of every piece in or near the chunk:
|
|
||||||
|
|
||||||
- **`beard_thin`:** under each rigid piece, fill solid down to the ground, fading out over about 8 blocks around the
|
|
||||||
box. Above its floor, inside its box, clear what the terrain put there.
|
|
||||||
- **`beard_box`:** the same, without fading at the edges.
|
|
||||||
- **`bury` and `encapsulate`:** fill around the piece instead. Trek doesn't use them, so they can come later.
|
|
||||||
- **Trees:** the base game's trees feature doesn't grow trees whose trunk is inside a piece's box (grown out a few
|
|
||||||
blocks), using `chunk.structures`, so villages don't get trees through their roofs. Trees still grow around them.
|
|
||||||
|
|
||||||
Like Minecraft, `terrain_matching` pieces (paths) don't adapt the terrain: they follow it.
|
|
||||||
|
|
||||||
### Entities
|
|
||||||
|
|
||||||
Generation only makes blocks now. Template entities and anything else generation spawns need "this chunk was generated
|
|
||||||
for the first time": the world keeps a set of chunks whose generation spawns already happened, saved with the world.
|
|
||||||
When a chunk is built and isn't in it, its structure entities are spawned and it's added. Mods' natural spawning can use
|
|
||||||
the same hook later.
|
|
||||||
|
|
||||||
### Determinism and Saves
|
|
||||||
|
|
||||||
- Starts and pieces are recomputed whenever needed and never saved: a chunk with a piece in it is saved with its blocks
|
|
||||||
like any other, and pieces reaching into chunks not generated yet need the same start.
|
|
||||||
- Adding or removing a mod with structures changes only chunks not generated yet, the same as features do now. Saved
|
|
||||||
chunks stay as they were, so there can be seams.
|
|
||||||
- Tests generate the same chunks in different orders and compare every block. A golden test records a few chunks with
|
|
||||||
structures in them, so changes to generation show up.
|
|
||||||
|
|
||||||
### Performance
|
|
||||||
|
|
||||||
Starts are cached. Templates are parsed once into typed arrays. A chunk only looks at pieces whose boxes overlap it.
|
|
||||||
Assembling a large village is the expensive part: a few milliseconds is fine, since it happens once per start and the
|
|
||||||
server only builds chunks for a limited time each tick. Profile with Trek's villages before optimizing.
|
|
||||||
|
|
||||||
### Script API
|
|
||||||
|
|
||||||
- **Worldgen:** `register_feature_type`, `register_processor` and `register_structure_type`, and `chunk.structures`: the
|
|
||||||
pieces overlapping the chunk, so a script feature can avoid them or decorate them.
|
|
||||||
- **Server:** `ctx.world.structures_at(x, y, z)` (which structures a position is in, for advancements and spawning) and
|
|
||||||
`ctx.world.find_structure(id, x, z, radius)`.
|
|
||||||
- **Commands:** `/locate structure <id>` and `/place structure <id>`, `/place template <id>` and `/place feature <id>`,
|
|
||||||
like Minecraft's `/place`. They're the fastest way to look at what an import made.
|
|
||||||
|
|
||||||
## The Importer
|
|
||||||
|
|
||||||
`deno task import-datapack ports/trek mods/trek` turns a datapack (or a mod's `data/` folder) into a bworld mod:
|
|
||||||
|
|
||||||
1. **Copy and wrap.** `<ns>/structure/**/*.nbt` goes to `structures/`. Each `worldgen/*` JSON gets bworld's wrapper, an
|
|
||||||
`id` from its path, and plural folders. Configured and placed features are joined into one data feature per placed
|
|
||||||
feature.
|
|
||||||
2. **Rename ids.** Ids in the pack's own namespace stay. `minecraft:` content ids (blocks, items, biomes, tags) are left
|
|
||||||
for the remaps to resolve when loading, so the import stays close to the original and updates easily. Types
|
|
||||||
(`minecraft:jigsaw`, `minecraft:rule`) are untouched.
|
|
||||||
3. **Heights.** Minecraft's world goes from -64 to 320 with the sea at 63. bworld's goes from 0 to 256 with the sea at
|
|
||||||
64. Heights relative to the surface (almost everything) need nothing. Absolute heights are moved: y 63 and up gets
|
|
||||||
+1, and -64 to 63 is squeezed into 1 to 64.
|
|
||||||
4. **Skip what can't work here.** Anything under a `minecraft/` folder that changes vanilla's own structures
|
|
||||||
(strongholds, mansions, end cities) and Nether and End content is left out, and listed.
|
|
||||||
5. **Report.** `IMPORT_REPORT.md` in the new mod:
|
|
||||||
- blocks, items, biomes and entities that don't map yet, with how many templates use each;
|
|
||||||
- references to content the pack doesn't include;
|
|
||||||
- structures that can't generate (no biome maps, or the start pool is missing).
|
|
||||||
|
|
||||||
Run it again after adding blocks: the report shrinks while the mod stays the same.
|
|
||||||
6. **Credits.** The pack's license and authors go into the mod's `CREDITS.md`. Trek is MIT.
|
|
||||||
|
|
||||||
The importer is the only code that knows datapacks' folder layout. The engine only reads bworld mods.
|
|
||||||
|
|
||||||
## Trek
|
|
||||||
|
|
||||||
Trek has 133 structures in 17 sets, 398 template pools, 45 processor lists, 777 templates (126 more change vanilla's
|
|
||||||
structures) and 32 configured features.
|
|
||||||
|
|
||||||
- **45 structures are always one piece:** their start templates have no jigsaw blocks. 42 are in the overworld, among
|
|
||||||
them `rocks`, `plains`, `ruins`, the ice spikes, `oasis`, `graveyard`, `stonehedge` and `pyramide_of_anubis`. These
|
|
||||||
need everything except assembly.
|
|
||||||
- **88 are assembled from pieces,** including every village. 699 templates contain jigsaw blocks (2,920 of them).
|
|
||||||
- **Terrain adaptation:** 75 structures use `beard_thin`, 5 use `beard_box` and 53 use `none`.
|
|
||||||
- **References outside the pack:** 20 templates and about 50 processor lists and fallback pools are vanilla's
|
|
||||||
(`minecraft:street_plains`, `minecraft:zombie_plains`, `minecraft:village/plains/terminators`), and 8 templates are
|
|
||||||
from the Waystones mod. Jigsaw blocks inside templates also name vanilla pools that aren't included, like
|
|
||||||
`minecraft:village/plains/villagers` and `minecraft:village/common/cats`. The mushroom village refers to
|
|
||||||
`minecraft:village/mushroom/houses`, which Trek doesn't define. Following Minecraft, a missing pool or processor list
|
|
||||||
is empty, so those spots stay plain. The base game can add bworld versions of the vanilla street processors later.
|
|
||||||
- **Not for bworld:** the 3 Nether structures, the End ones, and the `minecraft/` changes to vanilla's structures.
|
|
||||||
|
|
||||||
## Phases
|
|
||||||
|
|
||||||
Each phase ends with every test passing and something to look at in a world.
|
|
||||||
|
|
||||||
**Phase 1: blocks for templates.**
|
|
||||||
|
|
||||||
- Named state values, `values` in conditions, and turning states.
|
|
||||||
- `common/nbt.ts` and template loading.
|
|
||||||
- `remaps/` and `mods/bworld/remaps/minecraft.json` for the blocks bworld has.
|
|
||||||
- The importer's first version, which writes the report.
|
|
||||||
|
|
||||||
Check: `deno task import-datapack ports/trek mods/trek` makes a mod that passes `check-mods`. Every template loads, and
|
|
||||||
the report lists every unmapped block.
|
|
||||||
|
|
||||||
**Phase 2: single-piece structures.**
|
|
||||||
|
|
||||||
- Structures, structure sets (`random_spread`, frequency, exclusion zones), pools with single elements, processor lists,
|
|
||||||
and placing pieces per chunk.
|
|
||||||
- `surface_at` and `ocean_floor_at`.
|
|
||||||
- Biome tags and remapped biomes.
|
|
||||||
- `/place` and `/locate`.
|
|
||||||
|
|
||||||
Check: Trek's rocks, ruins and ice spikes generate in a world. The same chunks come out identical in any generation
|
|
||||||
order. `/locate structure trek:overworld/very_common/rocks` finds one.
|
|
||||||
|
|
||||||
**Phase 3: terrain adaptation and trees.** `beard_thin` and `beard_box`, and no trees inside pieces.
|
|
||||||
|
|
||||||
Check: `stonehedge` and `destroyed_house` sit on filled ground on slopes, with nothing growing through them.
|
|
||||||
|
|
||||||
**Phase 4: jigsaw.**
|
|
||||||
|
|
||||||
- Assembly, every pool element type, `terrain_matching`, fallbacks and priorities.
|
|
||||||
- The start cache.
|
|
||||||
|
|
||||||
Check: Trek's plains village generates with streets following the ground and no overlapping houses. Assembling the same
|
|
||||||
start twice gives the same pieces.
|
|
||||||
|
|
||||||
**Phase 5: what's inside.**
|
|
||||||
|
|
||||||
- Loot tables and chest tile data.
|
|
||||||
- Spawning template entities once per chunk.
|
|
||||||
- `structures_at`.
|
|
||||||
|
|
||||||
Check: a village chest has loot the first time it's opened and not the second.
|
|
||||||
|
|
||||||
**Phase 6: data features.**
|
|
||||||
|
|
||||||
- `worldgen/features/`: `fossil`, `simple_block`, `block_column`, `disk`, `spring_feature`.
|
|
||||||
- `register_feature_type`, and template features written per chunk.
|
|
||||||
|
|
||||||
Check: Trek's monster rooms generate underground.
|
|
||||||
|
|
||||||
**Phase 7: the rest, as it's needed.** `concentric_rings`, `bury` and `encapsulate`, `spawn_overrides`, mirroring,
|
|
||||||
structure types from scripts, and the base game's ores as data features. Meanwhile blocks keep being added, and each one
|
|
||||||
lets more of Trek's templates generate whole.
|
|
||||||
|
|
||||||
## Open Questions
|
|
||||||
|
|
||||||
- **Starts across mod updates.** Changing a pool's weights moves every structure assembled from it in existing worlds.
|
|
||||||
That's the same as features now, but structures are bigger. Should a world keep the starts it has seen (like Minecraft
|
|
||||||
saves them), so updating a mod only changes chunks that were never generated?
|
|
||||||
- **The `minecraft` namespace.** Packs that change vanilla content (`minecraft:village/plains/...`) could become changes
|
|
||||||
to the base game's own villages, once the base game has some. Until then they're skipped.
|
|
||||||
- **Mapping close enough.** Is a block that looks similar (`polished_andesite` → `andesite` → `stone`) better than
|
|
||||||
leaving the spot empty? Remaps can do either. Start with exact matches only, so the report stays honest.
|
|
||||||
- **Waterlogging.** Templates mark many blocks `waterlogged` (stairs and slabs under water). bworld has no waterlogging,
|
|
||||||
so underwater structures will have air pockets in them until it does.
|
|
||||||
|
|
||||||
## Blocks Trek Uses
|
|
||||||
|
|
||||||
<!-- generated from ports/trek: every template's palette, counting blocks that are placed -->
|
|
||||||
|
|
||||||
Counted over the 743 trek templates bworld could generate (overworld, villages, monster rooms; not Nether or End): 748
|
|
||||||
distinct blocks, 58 already in bworld.
|
|
||||||
|
|
||||||
### Already in bworld
|
|
||||||
|
|
||||||
`dirt`, `chest`, `spruce_trapdoor`, `grass_block` → `bworld:grass`, `spruce_fence`, `cobblestone`, `spruce_planks`,
|
|
||||||
`stone_bricks`, `water`, `oak_planks`, `oak_trapdoor`, `stone`, `dark_oak_fence`, `oak_log`, `oak_leaves`,
|
|
||||||
`dark_oak_planks`, `spruce_log`, `coal_ore`, `oak_fence`, `farmland` → `bworld:hoed_dirt`, `spruce_leaves`,
|
|
||||||
`birch_leaves`, `iron_ore`, `dark_oak_trapdoor`, `smooth_stone`, `dark_oak_log`, `furnace`, `jungle_fence`, `sand`,
|
|
||||||
`wheat`, `acacia_leaves`, `smithing_table`, `birch_planks`, `snow_block` → `bworld:snow`, `acacia_fence`,
|
|
||||||
`acacia_planks`, `cracked_stone_bricks`, `jungle_planks`, `cherry_fence`, `jungle_leaves`, `mossy_stone_bricks`,
|
|
||||||
`acacia_trapdoor`, `carrots`, `potatoes`, `acacia_log`, `cherry_log`, `jungle_trapdoor`, `cherry_trapdoor`,
|
|
||||||
`cherry_leaves`, `birch_log`, `birch_trapdoor`, `jungle_log`, `glass`, `dark_oak_leaves`, `cherry_planks`, `copper_ore`,
|
|
||||||
`birch_fence`, `gold_ore`
|
|
||||||
|
|
||||||
### Missing, used in 20 or more templates
|
|
||||||
|
|
||||||
Templates is how many templates use the block, placed is how many times it's placed across all of them. States are the
|
|
||||||
vanilla properties the templates use (`waterlogged` left out, bworld has no waterlogging).
|
|
||||||
|
|
||||||
| # | Block | Templates | Placed | States used |
|
|
||||||
| --: | -------------------------- | --------: | -----: | ---------------------------------------------- |
|
|
||||||
| 1 | `lantern` | 302 | 1610 | `hanging` |
|
|
||||||
| 2 | `spruce_slab` | 192 | 10415 | `type` |
|
|
||||||
| 3 | `spruce_stairs` | 189 | 11049 | `facing`, `half`, `shape` |
|
|
||||||
| 4 | `coarse_dirt` | 186 | 48024 | |
|
|
||||||
| 5 | `dirt_path` | 134 | 5495 | |
|
|
||||||
| 6 | `spruce_door` | 115 | 446 | `facing`, `half`, `hinge`, `open`, `powered` |
|
|
||||||
| 7 | `dark_oak_stairs` | 109 | 4487 | `facing`, `half`, `shape` |
|
|
||||||
| 8 | `cobblestone_wall` | 108 | 1620 | `east`, `north`, `south`, `up`, `west` |
|
|
||||||
| 9 | `dark_oak_slab` | 103 | 4302 | `type` |
|
|
||||||
| 10 | `spruce_fence_gate` | 103 | 1250 | `facing`, `in_wall`, `open`, `powered` |
|
|
||||||
| 11 | `ladder` | 97 | 1108 | `facing` |
|
|
||||||
| 12 | `stone_brick_stairs` | 93 | 2924 | `facing`, `half`, `shape` |
|
|
||||||
| 13 | `andesite` | 91 | 305242 | |
|
|
||||||
| 14 | `barrel` | 91 | 1249 | `facing`, `open` |
|
|
||||||
| 15 | `campfire` | 90 | 558 | `facing`, `lit`, `signal_fire` |
|
|
||||||
| 16 | `cobblestone_stairs` | 88 | 1609 | `facing`, `half`, `shape` |
|
|
||||||
| 17 | `oak_slab` | 88 | 2791 | `type` |
|
|
||||||
| 18 | `rooted_dirt` | 84 | 3547 | |
|
|
||||||
| 19 | `glass_pane` | 82 | 724 | `east`, `north`, `south`, `west` |
|
|
||||||
| 20 | `grass` | 80 | 8109 | |
|
|
||||||
| 21 | `oak_stairs` | 77 | 2840 | `facing`, `half`, `shape` |
|
|
||||||
| 22 | `chain` | 75 | 506 | `axis` |
|
|
||||||
| 23 | `stone_brick_slab` | 75 | 1556 | `type` |
|
|
||||||
| 24 | `stripped_spruce_log` | 71 | 5580 | `axis` |
|
|
||||||
| 25 | `cobblestone_slab` | 61 | 789 | `type` |
|
|
||||||
| 26 | `hay_block` | 58 | 992 | `axis` |
|
|
||||||
| 27 | `crafting_table` | 56 | 204 | |
|
|
||||||
| 28 | `soul_lantern` | 56 | 138 | `hanging` |
|
|
||||||
| 29 | `light_gray_wool` | 55 | 246768 | |
|
|
||||||
| 30 | `stone_brick_wall` | 53 | 682 | `east`, `north`, `south`, `up`, `west` |
|
|
||||||
| 31 | `dandelion` | 53 | 342 | |
|
|
||||||
| 32 | `player_head` | 51 | 418 | `rotation` |
|
|
||||||
| 33 | `tall_grass` | 51 | 3518 | `half` |
|
|
||||||
| 34 | `light_gray_concrete` | 51 | 260268 | |
|
|
||||||
| 35 | `vine` | 49 | 3759 | `east`, `north`, `south`, `up`, `west` |
|
|
||||||
| 36 | `iron_bars` | 49 | 1318 | `east`, `north`, `south`, `west` |
|
|
||||||
| 37 | `podzol` | 48 | 1362 | `snowy` |
|
|
||||||
| 38 | `oak_door` | 47 | 166 | `facing`, `half`, `hinge`, `open`, `powered` |
|
|
||||||
| 39 | `bookshelf` | 46 | 706 | |
|
|
||||||
| 40 | `white_wool` | 45 | 1711 | |
|
|
||||||
| 41 | `lime_terracotta` | 45 | 6981 | |
|
|
||||||
| 42 | `composter` | 44 | 174 | `level` |
|
|
||||||
| 43 | `rail` | 43 | 270 | `shape` |
|
|
||||||
| 44 | `stone_button` | 43 | 641 | `face`, `facing`, `powered` |
|
|
||||||
| 45 | `stone_slab` | 41 | 710 | `type` |
|
|
||||||
| 46 | `bell` | 41 | 50 | `attachment`, `facing`, `powered` |
|
|
||||||
| 47 | `grindstone` | 40 | 63 | `face`, `facing` |
|
|
||||||
| 48 | `mycelium` | 39 | 6911 | `snowy` |
|
|
||||||
| 49 | `water_cauldron` | 38 | 69 | `level` |
|
|
||||||
| 50 | `poppy` | 38 | 190 | |
|
|
||||||
| 51 | `dark_oak_fence_gate` | 37 | 457 | `facing`, `in_wall`, `open`, `powered` |
|
|
||||||
| 52 | `white_wall_banner` | 37 | 143 | `facing` |
|
|
||||||
| 53 | `mossy_cobblestone_slab` | 37 | 560 | `type` |
|
|
||||||
| 54 | `stripped_oak_log` | 37 | 1747 | `axis` |
|
|
||||||
| 55 | `smoker` | 36 | 60 | `facing`, `lit` |
|
|
||||||
| 56 | `blast_furnace` | 36 | 54 | `facing`, `lit` |
|
|
||||||
| 57 | `smooth_sandstone` | 36 | 2689 | |
|
|
||||||
| 58 | `spruce_pressure_plate` | 36 | 75 | `powered` |
|
|
||||||
| 59 | `stone_stairs` | 35 | 366 | `facing`, `half`, `shape` |
|
|
||||||
| 60 | `oak_wall_sign` | 35 | 353 | `facing` |
|
|
||||||
| 61 | `red_bed` | 35 | 170 | `facing`, `occupied`, `part` |
|
|
||||||
| 62 | `moss_block` | 35 | 8669 | |
|
|
||||||
| 63 | `candle` | 35 | 84 | `candles`, `lit` |
|
|
||||||
| 64 | `snow` | 34 | 2508 | `layers` |
|
|
||||||
| 65 | `spruce_wall_sign` | 34 | 532 | `facing` |
|
|
||||||
| 66 | `stripped_dark_oak_log` | 33 | 861 | `axis` |
|
|
||||||
| 67 | `diorite` | 33 | 4578 | |
|
|
||||||
| 68 | `calcite` | 32 | 2964 | |
|
|
||||||
| 69 | `birch_slab` | 32 | 630 | `type` |
|
|
||||||
| 70 | `jungle_stairs` | 32 | 426 | `facing`, `half`, `shape` |
|
|
||||||
| 71 | `smooth_sandstone_stairs` | 32 | 560 | `facing`, `half`, `shape` |
|
|
||||||
| 72 | `cut_sandstone` | 32 | 1722 | |
|
|
||||||
| 73 | `mossy_cobblestone` | 32 | 3850 | |
|
|
||||||
| 74 | `melon` | 32 | 686 | |
|
|
||||||
| 75 | `scaffolding` | 31 | 214 | `bottom`, `distance` |
|
|
||||||
| 76 | `birch_wood` | 31 | 356 | `axis` |
|
|
||||||
| 77 | `acacia_wood` | 30 | 1033 | `axis` |
|
|
||||||
| 78 | `polished_diorite` | 30 | 653 | |
|
|
||||||
| 79 | `flowering_azalea_leaves` | 30 | 531 | `distance`, `persistent` |
|
|
||||||
| 80 | `light_blue_bed` | 30 | 96 | `facing`, `occupied`, `part` |
|
|
||||||
| 81 | `wall_torch` | 29 | 221 | `facing` |
|
|
||||||
| 82 | `flower_pot` | 29 | 113 | |
|
|
||||||
| 83 | `terracotta` | 29 | 707 | |
|
|
||||||
| 84 | `red_mushroom_block` | 29 | 679 | `down`, `east`, `north`, `south`, `up`, `west` |
|
|
||||||
| 85 | `acacia_stairs` | 29 | 896 | `facing`, `half`, `shape` |
|
|
||||||
| 86 | `stripped_spruce_wood` | 28 | 3415 | `axis` |
|
|
||||||
| 87 | `potted_blue_orchid` | 28 | 43 | |
|
|
||||||
| 88 | `polished_andesite` | 27 | 1021 | |
|
|
||||||
| 89 | `mud_brick_wall` | 27 | 898 | `east`, `north`, `south`, `up`, `west` |
|
|
||||||
| 90 | `sandstone` | 27 | 10819 | |
|
|
||||||
| 91 | `end_rod` | 27 | 142 | `facing` |
|
|
||||||
| 92 | `green_bed` | 27 | 76 | `facing`, `occupied`, `part` |
|
|
||||||
| 93 | `decorated_pot` | 27 | 49 | `cracked`, `facing` |
|
|
||||||
| 94 | `cobweb` | 26 | 346 | |
|
|
||||||
| 95 | `spruce_wood` | 26 | 2521 | `axis` |
|
|
||||||
| 96 | `rose_bush` | 26 | 304 | `half` |
|
|
||||||
| 97 | `jungle_slab` | 26 | 778 | `type` |
|
|
||||||
| 98 | `deepslate_brick_stairs` | 26 | 1319 | `facing`, `half`, `shape` |
|
|
||||||
| 99 | `green_wool` | 25 | 3524 | |
|
|
||||||
| 100 | `cartography_table` | 25 | 29 | |
|
|
||||||
| 101 | `chiseled_stone_bricks` | 25 | 274 | |
|
|
||||||
| 102 | `loom` | 25 | 245 | `facing` |
|
|
||||||
| 103 | `white_carpet` | 24 | 112 | |
|
|
||||||
| 104 | `oak_fence_gate` | 24 | 466 | `facing`, `in_wall`, `open`, `powered` |
|
|
||||||
| 105 | `smooth_sandstone_slab` | 24 | 364 | `type` |
|
|
||||||
| 106 | `azalea_leaves` | 24 | 2186 | `distance`, `persistent` |
|
|
||||||
| 107 | `potted_fern` | 24 | 51 | |
|
|
||||||
| 108 | `deepslate_bricks` | 24 | 1356 | |
|
|
||||||
| 109 | `acacia_slab` | 24 | 1741 | `type` |
|
|
||||||
| 110 | `cauldron` | 23 | 47 | |
|
|
||||||
| 111 | `lectern` | 23 | 96 | `facing`, `has_book`, `powered` |
|
|
||||||
| 112 | `cornflower` | 23 | 46 | |
|
|
||||||
| 113 | `bamboo` | 23 | 608 | `age`, `leaves`, `stage` |
|
|
||||||
| 114 | `deepslate_brick_slab` | 23 | 1455 | `type` |
|
|
||||||
| 115 | `red_carpet` | 22 | 278 | |
|
|
||||||
| 116 | `blue_bed` | 22 | 66 | `facing`, `occupied`, `part` |
|
|
||||||
| 117 | `black_wall_banner` | 22 | 55 | `facing` |
|
|
||||||
| 118 | `crimson_roots` | 22 | 177 | |
|
|
||||||
| 119 | `andesite_stairs` | 21 | 169 | `facing`, `half`, `shape` |
|
|
||||||
| 120 | `mossy_stone_brick_stairs` | 21 | 119 | `facing`, `half`, `shape` |
|
|
||||||
| 121 | `smooth_quartz_stairs` | 21 | 372 | `facing`, `half`, `shape` |
|
|
||||||
| 122 | `green_concrete` | 21 | 3324 | |
|
|
||||||
| 123 | `fletching_table` | 21 | 41 | |
|
|
||||||
| 124 | `sea_pickle` | 21 | 84 | `pickles` |
|
|
||||||
| 125 | `potted_oak_sapling` | 21 | 32 | |
|
|
||||||
| 126 | `fern` | 21 | 139 | |
|
|
||||||
| 127 | `diorite_slab` | 21 | 318 | `type` |
|
|
||||||
| 128 | `jungle_door` | 21 | 70 | `facing`, `half`, `hinge`, `open`, `powered` |
|
|
||||||
| 129 | `dead_brain_coral_block` | 21 | 797 | |
|
|
||||||
| 130 | `hopper` | 20 | 53 | `enabled`, `facing` |
|
|
||||||
| 131 | `dark_oak_wood` | 20 | 1805 | `axis` |
|
|
||||||
| 132 | `potted_spruce_sapling` | 20 | 29 | |
|
|
||||||
| 133 | `brewing_stand` | 20 | 38 | `has_bottle_0`, `has_bottle_1`, `has_bottle_2` |
|
|
||||||
| 134 | `green_concrete_powder` | 20 | 530 | |
|
|
||||||
| 135 | `polished_diorite_slab` | 20 | 293 | `type` |
|
|
||||||
| 136 | `glow_lichen` | 20 | 346 | `down`, `east`, `north`, `south`, `up`, `west` |
|
|
||||||
| 137 | `spruce_wall_hanging_sign` | 20 | 58 | `facing` |
|
|
||||||
|
|
||||||
### Missing, used in 5 to 19 templates
|
|
||||||
|
|
||||||
- **19:** `dark_oak_wall_sign`, `andesite_wall`, `moss_carpet`, `granite`, `oak_wood`, `potted_dead_bush`,
|
|
||||||
`mossy_stone_brick_slab`, `cut_sandstone_slab`, `brown_mushroom`, `smooth_quartz_slab`
|
|
||||||
- **18:** `anvil`, `potted_dark_oak_sapling`, `oxeye_daisy`, `mossy_cobblestone_stairs`, `green_terracotta`,
|
|
||||||
`green_glazed_terracotta`
|
|
||||||
- **17:** `smooth_quartz`, `lever`, `sandstone_wall`, `sandstone_slab`, `stonecutter`, `tripwire_hook`, `pumpkin`,
|
|
||||||
`dried_kelp_block`, `mushroom_stem`, `green_stained_glass`, `pink_bed`
|
|
||||||
- **16:** `damaged_anvil`, `tuff`, `cyan_terracotta`, `red_wall_banner`, `cave_vines_plant`, `cave_vines`, `clay`,
|
|
||||||
`crimson_fungus`, `acacia_door`, `oak_pressure_plate`, `wet_sponge`
|
|
||||||
- **15:** `bricks`, `gravel`, `mossy_cobblestone_wall`, `brick_stairs`, `mossy_stone_brick_wall`, `glowstone`,
|
|
||||||
`potted_dandelion`, `note_block`, `obsidian`, `red_stained_glass_pane`, `orange_terracotta`, `deepslate_tile_slab`,
|
|
||||||
`potted_flowering_azalea_bush`
|
|
||||||
- **14:** `spruce_button`, `heavy_weighted_pressure_plate`, `jungle_wood`, `potted_red_tulip`, `azalea`, `white_bed`,
|
|
||||||
`potted_bamboo`, `weeping_vines`
|
|
||||||
- **13:** `andesite_slab`, `potted_lily_of_the_valley`, `potted_cactus`, `sandstone_stairs`, `blue_orchid`,
|
|
||||||
`flowering_azalea`, `amethyst_cluster`, `azure_bluet`, `large_fern`, `white_concrete`, `white_terracotta`,
|
|
||||||
`potted_azalea_bush`, `deepslate_tile_stairs`, `lime_stained_glass`, `dead_bubble_coral_block`, `cherry_door`
|
|
||||||
- **12:** `gray_carpet`, `diorite_wall`, `bone_block`, `tripwire`, `stone_pressure_plate`, `brown_carpet`,
|
|
||||||
`polished_andesite_stairs`, `crimson_slab`, `mangrove_trapdoor`, `weeping_vines_plant`, `red_candle`, `sponge`
|
|
||||||
- **11:** `stripped_dark_oak_wood`, `torch`, `orange_bed`, `quartz_stairs`, `quartz_slab`, `yellow_wool`,
|
|
||||||
`birch_stairs`, `gold_block`, `black_bed`, `carved_pumpkin`, `brown_wall_banner`, `potted_oxeye_daisy`,
|
|
||||||
`potted_pink_tulip`, `potted_cornflower`, `beetroots`, `dead_horn_coral_fan`, `orange_stained_glass_pane`,
|
|
||||||
`polished_andesite_slab`, `potted_poppy`, `smooth_stone_slab`, `mangrove_stairs`, `mud_bricks`, `jungle_fence_gate`,
|
|
||||||
`yellow_wall_banner`, `light_blue_terracotta`, `white_concrete_powder`, `yellow_terracotta`, `crimson_fence`,
|
|
||||||
`spruce_hanging_sign`, `potted_cherry_sapling`
|
|
||||||
- **10:** `peony`, `packed_ice`, `gray_wool`, `blue_ice`, `chiseled_sandstone`, `seagrass`, `white_candle`,
|
|
||||||
`large_amethyst_bud`, `dark_oak_door`, `spawner`, `crying_obsidian`, `red_sandstone`, `stripped_crimson_hyphae`,
|
|
||||||
`chiseled_bookshelf`, `lava_cauldron`, `bamboo_sapling`, `bamboo_fence`, `bamboo_trapdoor`
|
|
||||||
- **9:** `green_carpet`, `brick_slab`, `brick_wall`, `lilac`, `coal_block`, `polished_diorite_stairs`, `diorite_stairs`,
|
|
||||||
`potted_white_tulip`, `sweet_berry_bush`, `magma_block`, `redstone_wire`, `white_stained_glass_pane`,
|
|
||||||
`light_gray_carpet`, `allium`, `red_wool`, `netherrack`, `beehive`, `deepslate_brick_wall`, `yellow_carpet`,
|
|
||||||
`stripped_birch_wood`, `mud_brick_stairs`, `crimson_hyphae`, `crimson_trapdoor`, `bamboo_pressure_plate`
|
|
||||||
- **8:** `dark_oak_button`, `iron_trapdoor`, `blue_wool`, `deepslate`, `dead_bush`, `potted_acacia_sapling`,
|
|
||||||
`dark_oak_pressure_plate`, `lightning_rod`, `enchanting_table`, `light_gray_stained_glass_pane`, `ice`, `packed_mud`,
|
|
||||||
`mangrove_wood`, `deepslate_tiles`, `stripped_oak_wood`, `raw_iron_block`, `brown_mushroom_block`, `shroomlight`,
|
|
||||||
`acacia_fence_gate`, `birch_wall_sign`, `red_stained_glass`, `short_grass`, `cherry_stairs`
|
|
||||||
- **7:** `oak_button`, `skeleton_skull`, `hanging_roots`, `polished_deepslate_wall`, `cyan_wool`, `soul_campfire`,
|
|
||||||
`black_wool`, `quartz_block`, `stripped_jungle_log`, `mud_brick_slab`, `brown_bed`, `potted_crimson_fungus`,
|
|
||||||
`lily_of_the_valley`, `medium_amethyst_bud`, `jukebox`, `black_carpet`, `lily_pad`, `nether_brick_fence`,
|
|
||||||
`red_terracotta`, `potted_mangrove_propagule`, `mangrove_log`, `blue_terracotta`, `red_mushroom`, `potted_allium`,
|
|
||||||
`lava`, `dripstone_block`, `crimson_planks`, `jungle_wall_hanging_sign`
|
|
||||||
- **6:** `brown_terracotta`, `dead_brain_coral_fan`, `polished_deepslate`, `sugar_cane`, `potted_birch_sapling`,
|
|
||||||
`granite_stairs`, `polished_granite`, `attached_pumpkin_stem`, `stripped_birch_log`, `cobbled_deepslate`,
|
|
||||||
`purple_stained_glass`, `gray_bed`, `purple_carpet`, `tnt`, `nether_wart_block`, `potted_brown_mushroom`,
|
|
||||||
`yellow_bed`, `oak_wall_hanging_sign`, `jungle_pressure_plate`, `cherry_hanging_sign`
|
|
||||||
- **5:** `green_wall_banner`, `white_tulip`, `iron_block`, `polished_deepslate_stairs`, `cobbled_deepslate_slab`,
|
|
||||||
`tall_seagrass`, `cake`, `pumpkin_stem`, `attached_melon_stem`, `emerald_block`, `red_tulip`, `purple_wool`,
|
|
||||||
`nether_brick_slab`, `nether_brick_stairs`, `black_terracotta`, `gray_stained_glass_pane`, `blackstone_wall`,
|
|
||||||
`jungle_wall_sign`, `infested_chiseled_stone_bricks`, `piston`, `stripped_acacia_log`, `potted_azure_bluet`,
|
|
||||||
`lapis_ore`, `light_gray_terracotta`, `raw_gold_block`, `target`, `granite_wall`, `crimson_nylium`,
|
|
||||||
`twisting_vines_plant`, `twisting_vines`, `stripped_cherry_log`, `cherry_wall_hanging_sign`, `bamboo_stairs`,
|
|
||||||
`acacia_hanging_sign`, `acacia_wall_hanging_sign`, `acacia_pressure_plate`
|
|
||||||
|
|
||||||
The other 287 are in fewer than 5 templates each; the importer's unmapped report lists them.
|
|
||||||
|
|
||||||
### Missing, by family
|
|
||||||
|
|
||||||
Many missing blocks are one shape in many materials, so adding the shape once (a model, its states and its rules) and
|
|
||||||
then the materials is most of the work.
|
|
||||||
|
|
||||||
| Family | Missing blocks | In templates (sum) | Examples |
|
|
||||||
| ------------------------- | -------------: | -----------------: | ----------------------------------------------------------------------------------------------------------- |
|
|
||||||
| slabs | 45 | 971 | `spruce_slab`, `dark_oak_slab`, `oak_slab`, `stone_brick_slab`, ... |
|
|
||||||
| stairs | 47 | 964 | `spruce_stairs`, `dark_oak_stairs`, `stone_brick_stairs`, `cobblestone_stairs`, ... |
|
|
||||||
| flower pots | 33 | 353 | `potted_blue_orchid`, `potted_fern`, `potted_oak_sapling`, `potted_spruce_sapling`, ... |
|
|
||||||
| walls | 19 | 315 | `cobblestone_wall`, `stone_brick_wall`, `mud_brick_wall`, `andesite_wall`, ... |
|
|
||||||
| stripped logs and wood | 19 | 244 | `stripped_spruce_log`, `stripped_oak_log`, `stripped_dark_oak_log`, `stripped_spruce_wood`, ... |
|
|
||||||
| doors | 10 | 232 | `spruce_door`, `oak_door`, `jungle_door`, `acacia_door`, ... |
|
|
||||||
| terracotta | 27 | 209 | `lime_terracotta`, `green_terracotta`, `green_glazed_terracotta`, `cyan_terracotta`, ... |
|
|
||||||
| wool | 16 | 195 | `light_gray_wool`, `white_wool`, `green_wool`, `yellow_wool`, ... |
|
|
||||||
| beds | 15 | 194 | `red_bed`, `light_blue_bed`, `green_bed`, `blue_bed`, ... |
|
|
||||||
| fence gates | 8 | 190 | `spruce_fence_gate`, `dark_oak_fence_gate`, `oak_fence_gate`, `jungle_fence_gate`, ... |
|
|
||||||
| signs | 20 | 180 | `oak_wall_sign`, `spruce_wall_sign`, `spruce_wall_hanging_sign`, `dark_oak_wall_sign`, ... |
|
|
||||||
| wood (bark on every side) | 8 | 151 | `birch_wood`, `acacia_wood`, `spruce_wood`, `dark_oak_wood`, ... |
|
|
||||||
| carpets | 17 | 150 | `white_carpet`, `red_carpet`, `moss_carpet`, `gray_carpet`, ... |
|
|
||||||
| glass panes | 12 | 141 | `glass_pane`, `red_stained_glass_pane`, `orange_stained_glass_pane`, `white_stained_glass_pane`, ... |
|
|
||||||
| banners | 17 | 122 | `white_wall_banner`, `black_wall_banner`, `red_wall_banner`, `brown_wall_banner`, ... |
|
|
||||||
| pressure plates | 12 | 111 | `spruce_pressure_plate`, `oak_pressure_plate`, `heavy_weighted_pressure_plate`, `stone_pressure_plate`, ... |
|
|
||||||
| concrete | 12 | 100 | `light_gray_concrete`, `green_concrete`, `white_concrete`, `red_concrete`, ... |
|
|
||||||
| buttons | 9 | 81 | `stone_button`, `spruce_button`, `dark_oak_button`, `oak_button`, ... |
|
|
||||||
| stained glass | 9 | 57 | `green_stained_glass`, `lime_stained_glass`, `red_stained_glass`, `purple_stained_glass`, ... |
|
|
||||||
| trapdoors | 5 | 41 | `mangrove_trapdoor`, `bamboo_trapdoor`, `crimson_trapdoor`, `iron_trapdoor`, ... |
|
|
||||||
| candles | 9 | 34 | `red_candle`, `white_candle`, `light_gray_candle`, `pink_candle`, ... |
|
|
||||||
| fences | 5 | 31 | `crimson_fence`, `bamboo_fence`, `nether_brick_fence`, `mangrove_fence`, ... |
|
|
||||||
@@ -9,13 +9,13 @@ import { sha256 } from "./common/utils.ts";
|
|||||||
import { createCanvas, loadImage } from "@gfx/canvas-wasm";
|
import { createCanvas, loadImage } from "@gfx/canvas-wasm";
|
||||||
import { ENGINE_TEXTURE_DIR, load_and_check, load_order, LoadedMod } from "./tools/check_mods.ts";
|
import { ENGINE_TEXTURE_DIR, load_and_check, load_order, LoadedMod } from "./tools/check_mods.ts";
|
||||||
import { pack_mod } from "./tools/pack_mod.ts";
|
import { pack_mod } from "./tools/pack_mod.ts";
|
||||||
import { BMOD_EXTENSION } from "./common/bmod.ts";
|
import { MOD_EXTENSION } from "./common/mod.ts";
|
||||||
import { ENGINE_TEXTURES_INDEX } from "./server/host.ts";
|
import { ENGINE_TEXTURES_INDEX } from "./server/host.ts";
|
||||||
|
|
||||||
// all overridable so tests can build somewhere else
|
// all overridable so tests can build somewhere else
|
||||||
const BUILD_FOLDER = Deno.env.get("BUILD_DIR") ?? "build";
|
const BUILD_FOLDER = Deno.env.get("BUILD_DIR") ?? "build";
|
||||||
const MODS_FOLDER = Deno.env.get("MODS_DIR") ?? "mods";
|
const MODS_FOLDER = Deno.env.get("MODS_DIR") ?? "mods";
|
||||||
// where the server loads .bmod files from. the build puts every mod in mods/ there, next to any others
|
// where the server loads .cubi files from. the build puts every mod in mods/ there, next to any others
|
||||||
const SERVER_MODS_FOLDER = Deno.env.get("SERVER_MODS_DIR") ?? "server_mods";
|
const SERVER_MODS_FOLDER = Deno.env.get("SERVER_MODS_DIR") ?? "server_mods";
|
||||||
|
|
||||||
function clear_folder(folder: string) {
|
function clear_folder(folder: string) {
|
||||||
@@ -95,8 +95,8 @@ async function build_assets() {
|
|||||||
|
|
||||||
// every mod in mods/, checked and sorted so dependencies load first. a broken mod fails the whole build,
|
// every mod in mods/, checked and sorted so dependencies load first. a broken mod fails the whole build,
|
||||||
// the game never runs with some mods missing
|
// the game never runs with some mods missing
|
||||||
function load_mods(): LoadedMod[] {
|
async function load_mods(): Promise<LoadedMod[]> {
|
||||||
const mods = load_and_check(MODS_FOLDER);
|
const mods = await load_and_check(MODS_FOLDER);
|
||||||
const problems = mods.flatMap((mod) => mod.report.errors.map((error) => ` ${mod.id}: ${error}`));
|
const problems = mods.flatMap((mod) => mod.report.errors.map((error) => ` ${mod.id}: ${error}`));
|
||||||
if (problems.length > 0) {
|
if (problems.length > 0) {
|
||||||
throw new Error(`Mods have errors (deno task check-mods for details):\n${problems.join("\n")}`);
|
throw new Error(`Mods have errors (deno task check-mods for details):\n${problems.join("\n")}`);
|
||||||
@@ -104,17 +104,17 @@ function load_mods(): LoadedMod[] {
|
|||||||
return load_order(mods);
|
return load_order(mods);
|
||||||
}
|
}
|
||||||
|
|
||||||
// every mod in mods/ into server_mods/<id>.bmod. other .bmod files there are left alone, they're other people's mods
|
// every mod in mods/ into server_mods/<id>.cubi. other .cubi files there are left alone, they're other people's mods
|
||||||
async function build_mods(mods: LoadedMod[]) {
|
async function build_mods(mods: LoadedMod[]) {
|
||||||
Deno.mkdirSync(SERVER_MODS_FOLDER, { recursive: true });
|
Deno.mkdirSync(SERVER_MODS_FOLDER, { recursive: true });
|
||||||
remove_old_format();
|
remove_old_format();
|
||||||
for (const mod of mods) {
|
for (const mod of mods) {
|
||||||
Deno.writeFileSync(`${SERVER_MODS_FOLDER}/${mod.id}${BMOD_EXTENSION}`, await pack_mod(mod));
|
Deno.writeFileSync(`${SERVER_MODS_FOLDER}/${mod.id}${MOD_EXTENSION}`, await pack_mod(mod));
|
||||||
}
|
}
|
||||||
console.log(`Mods: ${mods.map((m) => m.id).join(", ") || "none"}`);
|
console.log(`Mods: ${mods.map((m) => m.id).join(", ") || "none"}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// builds before .bmod files put each mod's server script in a folder here with an index.json
|
// builds before .cubi files put each mod's server script in a folder here with an index.json
|
||||||
function remove_old_format() {
|
function remove_old_format() {
|
||||||
for (const entry of Deno.readDirSync(SERVER_MODS_FOLDER)) {
|
for (const entry of Deno.readDirSync(SERVER_MODS_FOLDER)) {
|
||||||
if (entry.isDirectory || entry.name === "index.json") {
|
if (entry.isDirectory || entry.name === "index.json") {
|
||||||
@@ -131,6 +131,14 @@ async function build_client() {
|
|||||||
minify: false,
|
minify: false,
|
||||||
keepNames: true,
|
keepNames: true,
|
||||||
});
|
});
|
||||||
|
// the desktop app's client, a deno worker next to main.js so it finds the same chunk worker, see client/native/
|
||||||
|
await Deno.bundle({
|
||||||
|
entrypoints: ["./client/native/main.ts"],
|
||||||
|
outputPath: `${BUILD_FOLDER}/client/native.js`,
|
||||||
|
platform: "deno",
|
||||||
|
minify: false,
|
||||||
|
keepNames: true,
|
||||||
|
});
|
||||||
await copy("./client/index.html", `${BUILD_FOLDER}/client/index.html`);
|
await copy("./client/index.html", `${BUILD_FOLDER}/client/index.html`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,8 +161,8 @@ async function build() {
|
|||||||
try {
|
try {
|
||||||
const now = performance.now();
|
const now = performance.now();
|
||||||
clear_folder(BUILD_FOLDER);
|
clear_folder(BUILD_FOLDER);
|
||||||
// checked first: a mod with errors stops the build before any .bmod is written
|
// checked first: a mod with errors stops the build before any .cubi is written
|
||||||
const mods = load_mods();
|
const mods = await load_mods();
|
||||||
await build_assets();
|
await build_assets();
|
||||||
await build_client();
|
await build_client();
|
||||||
await write_client_manifest(BUILD_FOLDER);
|
await write_client_manifest(BUILD_FOLDER);
|
||||||
|
|||||||
+12
-31
@@ -2,8 +2,10 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { load_texture, Texture } from "./renderer/mod.ts";
|
import { load_texture, Texture } from "./renderer/mod.ts";
|
||||||
|
import { decode_png } from "./png.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
type Asset = Texture | HTMLAudioElement | string | Record<string, unknown>;
|
type Asset = Texture | string | Record<string, unknown>;
|
||||||
|
|
||||||
export class AssetManager {
|
export class AssetManager {
|
||||||
static instance = new AssetManager();
|
static instance = new AssetManager();
|
||||||
@@ -18,45 +20,24 @@ export class AssetManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the client's own files are next to the page, see platform.page
|
||||||
|
const url = new URL(src, platform.page);
|
||||||
if (src.endsWith(".png")) {
|
if (src.endsWith(".png")) {
|
||||||
const img = new Image();
|
const promise = async () => {
|
||||||
const promise = new Promise<void>((resolve, reject) => {
|
const resp = await fetch(url);
|
||||||
img.onload = () => {
|
if (!resp.ok) throw new Error(`Failed to load image: ${src}`);
|
||||||
this.assets[key] = load_texture(img);
|
this.assets[key] = load_texture(decode_png(new Uint8Array(await resp.arrayBuffer())));
|
||||||
resolve();
|
|
||||||
};
|
};
|
||||||
img.onerror = () => reject(new Error(`Failed to load image: ${src}`));
|
this.loading_promises.push(promise());
|
||||||
});
|
|
||||||
img.src = src;
|
|
||||||
this.loading_promises.push(promise);
|
|
||||||
} else if (src.endsWith(".ogg")) {
|
|
||||||
const audio = new Audio();
|
|
||||||
const promise = new Promise<void>((resolve, reject) => {
|
|
||||||
audio.addEventListener(
|
|
||||||
"canplaythrough",
|
|
||||||
() => resolve(),
|
|
||||||
{ once: true },
|
|
||||||
);
|
|
||||||
audio.addEventListener(
|
|
||||||
"error",
|
|
||||||
() => reject(new Error(`Failed to load audio: ${src}`)),
|
|
||||||
{ once: true },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
audio.src = src;
|
|
||||||
audio.load();
|
|
||||||
this.assets[key] = audio;
|
|
||||||
this.loading_promises.push(promise);
|
|
||||||
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
|
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
|
||||||
const promise = async () => {
|
const promise = async () => {
|
||||||
const resp = await fetch(src);
|
const resp = await fetch(url);
|
||||||
this.assets[key] = await resp.text();
|
this.assets[key] = await resp.text();
|
||||||
};
|
};
|
||||||
this.loading_promises.push(promise());
|
this.loading_promises.push(promise());
|
||||||
} else if (src.endsWith(".json")) {
|
} else if (src.endsWith(".json")) {
|
||||||
const promise = async () => {
|
const promise = async () => {
|
||||||
const resp = await fetch(src);
|
const resp = await fetch(url);
|
||||||
this.assets[key] = await resp.json();
|
this.assets[key] = await resp.json();
|
||||||
};
|
};
|
||||||
this.loading_promises.push(promise());
|
this.loading_promises.push(promise());
|
||||||
|
|||||||
+50
-45
@@ -2,11 +2,13 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// the texture atlas: the engine's textures and every mod's in one image, built by the client when it joins a server
|
// the texture atlas: the engine's textures and every mod's in one image, built by the client when it joins a server
|
||||||
// from the textures in the server's .bmod files
|
// from the textures in the server's .cubi files
|
||||||
import { TEXTURE_SIZE } from "$/common/constants.ts";
|
import { TEXTURE_SIZE } from "@/common/constants.ts";
|
||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
import { type Animation, texture_animation, type TextureJson } from "$/common/texture_animation.ts";
|
import { type Animation, texture_animation, type TextureJson } from "@/common/texture_animation.ts";
|
||||||
import { AnimatedTexture } from "./texture_animations.ts";
|
import { AnimatedTexture } from "./texture_animations.ts";
|
||||||
|
import { decode_png, type Pixels } from "./png.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
export interface AtlasLayout {
|
export interface AtlasLayout {
|
||||||
// in pixels, a power of two
|
// in pixels, a power of two
|
||||||
@@ -67,17 +69,16 @@ function pack_shelves(entries: [string, TextureSize][], size: number) {
|
|||||||
// textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as
|
// textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as
|
||||||
// missing. an animated texture takes one frame's room, its first frame, and plays from animated (see
|
// missing. an animated texture takes one frame's room, its first frame, and plays from animated (see
|
||||||
// texture_animations.ts)
|
// texture_animations.ts)
|
||||||
export async function build_atlas(textures: Map<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
|
export function build_atlas(textures: Map<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
|
||||||
const images = new Map<string, ImageBitmap>();
|
const images = new Map<string, Pixels>();
|
||||||
await Promise.all([...textures].map(async ([id, png]) => {
|
for (const [id, png] of textures) {
|
||||||
|
if (id === "cubi:missing") continue;
|
||||||
try {
|
try {
|
||||||
images.set(id, await createImageBitmap(new Blob([png as Uint8Array<ArrayBuffer>], { type: "image/png" })));
|
images.set(id, decode_png(png));
|
||||||
} catch {
|
} catch {
|
||||||
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
|
console.warn(`Texture ${id} isn't a png that can be shown, it will show as missing`);
|
||||||
}
|
}
|
||||||
}));
|
}
|
||||||
images.get("cubi:missing")?.close();
|
|
||||||
images.delete("cubi:missing");
|
|
||||||
|
|
||||||
const animations = new Map<string, Animation>();
|
const animations = new Map<string, Animation>();
|
||||||
for (const [id, image] of images) {
|
for (const [id, image] of images) {
|
||||||
@@ -91,43 +92,36 @@ export async function build_atlas(textures: Map<string, Uint8Array>, texture_jso
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const { size, regions } = atlas_layout(sizes);
|
const { size, regions } = atlas_layout(sizes);
|
||||||
const canvas = new OffscreenCanvas(size, size);
|
const pixels = new Uint8ClampedArray(size * size * 4);
|
||||||
const ctx = canvas.getContext("2d")!;
|
const atlas = { width: size, height: size, data: pixels };
|
||||||
|
|
||||||
// magenta and black checker
|
// magenta and black checker
|
||||||
const missing = regions["cubi:missing"];
|
const missing = regions["cubi:missing"];
|
||||||
const half = TEXTURE_SIZE / 2;
|
const half = TEXTURE_SIZE / 2;
|
||||||
ctx.fillStyle = "magenta";
|
for (let py = 0; py < TEXTURE_SIZE; py++) {
|
||||||
ctx.fillRect(missing.x, missing.y, half, half);
|
for (let px = 0; px < TEXTURE_SIZE; px++) {
|
||||||
ctx.fillRect(missing.x + half, missing.y + half, half, half);
|
const i = ((missing.y + py) * size + missing.x + px) * 4;
|
||||||
ctx.fillStyle = "black";
|
const magenta = (px < half) === (py < half);
|
||||||
ctx.fillRect(missing.x + half, missing.y, half, half);
|
pixels.set(magenta ? [255, 0, 255, 255] : [0, 0, 0, 255], i);
|
||||||
ctx.fillRect(missing.x, missing.y + half, half, half);
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const animated: AnimatedTexture[] = [];
|
const animated: AnimatedTexture[] = [];
|
||||||
for (const [id, image] of images) {
|
for (const [id, image] of images) {
|
||||||
const animation = animations.get(id);
|
const animation = animations.get(id);
|
||||||
const { x, y, width, height } = regions[id];
|
const { x, y, width, height } = regions[id];
|
||||||
if (animation) {
|
const first = animation?.frames[0] ?? { x: 0, y: 0 };
|
||||||
const first = animation.frames[0];
|
copy_pixels(image, first.x, first.y, width, height, atlas, x, y);
|
||||||
ctx.drawImage(image, first.x, first.y, width, height, x, y, width, height);
|
if (animation) animated.push(new AnimatedTexture(regions[id], animation, image.data, image.width));
|
||||||
animated.push(new AnimatedTexture(regions[id], animation, image_pixels(image), image.width));
|
|
||||||
} else {
|
|
||||||
ctx.drawImage(image, x, y);
|
|
||||||
}
|
|
||||||
image.close();
|
|
||||||
}
|
}
|
||||||
for (const id of textures.keys()) {
|
for (const id of textures.keys()) {
|
||||||
regions[id] ??= missing;
|
regions[id] ??= missing;
|
||||||
}
|
}
|
||||||
|
|
||||||
const image_data = ctx.getImageData(0, 0, size, size);
|
|
||||||
const pixels = image_data.data;
|
|
||||||
extrude_borders(pixels, size, regions);
|
extrude_borders(pixels, size, regions);
|
||||||
ctx.putImageData(image_data, 0, 0);
|
|
||||||
|
|
||||||
// which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts)
|
// which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts)
|
||||||
built_atlas = image_data;
|
built_atlas = atlas;
|
||||||
opaque.clear();
|
opaque.clear();
|
||||||
for (const [id, region] of Object.entries(regions)) {
|
for (const [id, region] of Object.entries(regions)) {
|
||||||
const mask = new Uint8Array(region.width * region.height);
|
const mask = new Uint8Array(region.width * region.height);
|
||||||
@@ -140,7 +134,24 @@ export async function build_atlas(textures: Map<string, Uint8Array>, texture_jso
|
|||||||
opaque.set(id, { width: region.width, height: region.height, mask });
|
opaque.set(id, { width: region.width, height: region.height, mask });
|
||||||
}
|
}
|
||||||
|
|
||||||
return { image: canvas.transferToImageBitmap(), regions, animated };
|
return { image: atlas, regions, animated };
|
||||||
|
}
|
||||||
|
|
||||||
|
// a width × height part of from, starting at from_x from_y, into to at to_x to_y
|
||||||
|
function copy_pixels(
|
||||||
|
from: Pixels,
|
||||||
|
from_x: number,
|
||||||
|
from_y: number,
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
to: Pixels,
|
||||||
|
to_x: number,
|
||||||
|
to_y: number,
|
||||||
|
) {
|
||||||
|
for (let row = 0; row < height; row++) {
|
||||||
|
const start = ((from_y + row) * from.width + from_x) * 4;
|
||||||
|
to.data.set(from.data.subarray(start, start + width * 4), ((to_y + row) * to.width + to_x) * 4);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fills each region's border with copies of its edge pixels, the corners with its corners. pixels is a size × size
|
// fills each region's border with copies of its edge pixels, the corners with its corners. pixels is a size × size
|
||||||
@@ -169,13 +180,6 @@ export function extrude_borders(pixels: Uint8ClampedArray, size: number, regions
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// every frame of an animated texture stays in memory, to copy into the atlas when it's that frame's turn
|
|
||||||
function image_pixels(image: ImageBitmap) {
|
|
||||||
const ctx = new OffscreenCanvas(image.width, image.height).getContext("2d")!;
|
|
||||||
ctx.drawImage(image, 0, 0);
|
|
||||||
return ctx.getImageData(0, 0, image.width, image.height).data;
|
|
||||||
}
|
|
||||||
|
|
||||||
// a texture's pixels, 1 (can be seen) or 0, row by row from the top
|
// a texture's pixels, 1 (can be seen) or 0, row by row from the top
|
||||||
export interface OpaqueMask {
|
export interface OpaqueMask {
|
||||||
width: number;
|
width: number;
|
||||||
@@ -192,22 +196,23 @@ export function opaque_pixels(texture_id: string): OpaqueMask | undefined {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// the last atlas built, before any animated texture moved on from its first frame
|
// the last atlas built, before any animated texture moved on from its first frame
|
||||||
let built_atlas: ImageData | undefined;
|
let built_atlas: Pixels | undefined;
|
||||||
|
|
||||||
// the atlas as a png, undefined before one is built. for the f3 screen's copy button
|
// the atlas as a png, undefined before one is built or where there's no canvas to encode it (the desktop app). for
|
||||||
|
// the f3 screen's copy button
|
||||||
export function atlas_png(): Promise<Blob> | undefined {
|
export function atlas_png(): Promise<Blob> | undefined {
|
||||||
if (!built_atlas) return undefined;
|
if (!built_atlas || typeof document === "undefined") return undefined;
|
||||||
const canvas = new OffscreenCanvas(built_atlas.width, built_atlas.height);
|
const canvas = new OffscreenCanvas(built_atlas.width, built_atlas.height);
|
||||||
canvas.getContext("2d")!.putImageData(built_atlas, 0, 0);
|
canvas.getContext("2d")!.putImageData(new ImageData(built_atlas.data, built_atlas.width), 0, 0);
|
||||||
return canvas.convertToBlob({ type: "image/png" });
|
return canvas.convertToBlob({ type: "image/png" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// the engine's own textures, which come with the client instead of a mod. see build_engine_textures in build.ts
|
// the engine's own textures, which come with the client instead of a mod. see build_engine_textures in build.ts
|
||||||
export async function engine_textures(): Promise<Map<string, Uint8Array>> {
|
export async function engine_textures(): Promise<Map<string, Uint8Array>> {
|
||||||
const names: string[] = await (await fetch("/assets/textures/index.json")).json();
|
const names: string[] = await (await fetch(new URL("/assets/textures/index.json", platform.page))).json();
|
||||||
const textures = new Map<string, Uint8Array>();
|
const textures = new Map<string, Uint8Array>();
|
||||||
await Promise.all(names.map(async (name) => {
|
await Promise.all(names.map(async (name) => {
|
||||||
const response = await fetch(`/assets/textures/${name}.png`);
|
const response = await fetch(new URL(`/assets/textures/${name}.png`, platform.page));
|
||||||
textures.set(`cubi:${name}`, new Uint8Array(await response.arrayBuffer()));
|
textures.set(`cubi:${name}`, new Uint8Array(await response.arrayBuffer()));
|
||||||
}));
|
}));
|
||||||
return textures;
|
return textures;
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// plays what client/sounds.ts decides on with web audio: a gain per category under master, and a panner for each
|
||||||
|
// sound that comes from somewhere, fading linearly to nothing at its range
|
||||||
|
import { SOUND_CATEGORIES, type SoundCategory } from "@/common/mod_data.ts";
|
||||||
|
import type { Position } from "@/common/mod_api/shared.ts";
|
||||||
|
import type { SoundFile, SoundOutput, Voice, VoiceSettings, Volumes } from "./sounds.ts";
|
||||||
|
|
||||||
|
export class WebAudioOutput implements SoundOutput {
|
||||||
|
#context: AudioContext | undefined;
|
||||||
|
#master: GainNode | undefined;
|
||||||
|
#categories = new Map<SoundCategory, GainNode>();
|
||||||
|
// decoded once, the first time anything plays them. by the bytes, so another server's files never mix in
|
||||||
|
#buffers = new WeakMap<Uint8Array, Promise<AudioBuffer | undefined>>();
|
||||||
|
#volumes: Volumes | undefined;
|
||||||
|
|
||||||
|
// browsers keep audio off until the player clicks or presses a key, so it starts then. the desktop app's web audio
|
||||||
|
// (client/native/web_audio.ts) has no such rule and starts right away
|
||||||
|
constructor(wait_for_input = true) {
|
||||||
|
if (!wait_for_input) {
|
||||||
|
this.#unlock();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const unlock = () => {
|
||||||
|
this.#unlock();
|
||||||
|
if (this.#context?.state === "running") {
|
||||||
|
removeEventListener("pointerdown", unlock);
|
||||||
|
removeEventListener("keydown", unlock);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
addEventListener("pointerdown", unlock);
|
||||||
|
addEventListener("keydown", unlock);
|
||||||
|
}
|
||||||
|
|
||||||
|
#unlock() {
|
||||||
|
if (!this.#context) {
|
||||||
|
const context = new AudioContext();
|
||||||
|
this.#master = context.createGain();
|
||||||
|
this.#master.connect(context.destination);
|
||||||
|
for (const category of SOUND_CATEGORIES) {
|
||||||
|
const gain = context.createGain();
|
||||||
|
gain.connect(this.#master);
|
||||||
|
this.#categories.set(category, gain);
|
||||||
|
}
|
||||||
|
this.#context = context;
|
||||||
|
if (this.#volumes) this.set_volumes(this.#volumes);
|
||||||
|
}
|
||||||
|
if (this.#context.state === "suspended") this.#context.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
start(file: SoundFile, settings: VoiceSettings): Voice | undefined {
|
||||||
|
const context = this.#context;
|
||||||
|
// sounds played while it's suspended would all come at once when it resumes
|
||||||
|
if (!context || context.state !== "running") return undefined;
|
||||||
|
const out = settings.category ? this.#categories.get(settings.category)! : this.#master!;
|
||||||
|
return new WebVoice(context, this.#buffer(context, file), out, settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
#buffer(context: AudioContext, file: SoundFile) {
|
||||||
|
let buffer = this.#buffers.get(file.bytes);
|
||||||
|
if (!buffer) {
|
||||||
|
// decoding detaches what it's given
|
||||||
|
buffer = context.decodeAudioData(file.bytes.slice().buffer).catch((e) => {
|
||||||
|
console.error(`couldn't decode the sound file ${file.id}:`, e);
|
||||||
|
return undefined;
|
||||||
|
});
|
||||||
|
this.#buffers.set(file.bytes, buffer);
|
||||||
|
}
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
listen(x: number, y: number, z: number, yaw: number, pitch: number) {
|
||||||
|
const listener = this.#context?.listener;
|
||||||
|
if (!listener) return;
|
||||||
|
// the camera's forward and up, see ClientLevel's pick
|
||||||
|
const forward = [-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)];
|
||||||
|
const up = [Math.sin(yaw) * Math.sin(pitch), Math.cos(pitch), Math.cos(yaw) * Math.sin(pitch)];
|
||||||
|
// firefox only has the old setters
|
||||||
|
if (listener.positionX) {
|
||||||
|
listener.positionX.value = x;
|
||||||
|
listener.positionY.value = y;
|
||||||
|
listener.positionZ.value = z;
|
||||||
|
listener.forwardX.value = forward[0];
|
||||||
|
listener.forwardY.value = forward[1];
|
||||||
|
listener.forwardZ.value = forward[2];
|
||||||
|
listener.upX.value = up[0];
|
||||||
|
listener.upY.value = up[1];
|
||||||
|
listener.upZ.value = up[2];
|
||||||
|
} else {
|
||||||
|
listener.setPosition(x, y, z);
|
||||||
|
listener.setOrientation(forward[0], forward[1], forward[2], up[0], up[1], up[2]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
set_volumes(volumes: Volumes) {
|
||||||
|
this.#volumes = volumes;
|
||||||
|
if (!this.#master) return;
|
||||||
|
this.#master.gain.value = volumes.master;
|
||||||
|
for (const [category, gain] of this.#categories) gain.gain.value = volumes[category];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class WebVoice implements Voice {
|
||||||
|
ended = false;
|
||||||
|
#source: AudioBufferSourceNode | undefined;
|
||||||
|
#gain: GainNode;
|
||||||
|
#panner: PannerNode | undefined;
|
||||||
|
#stopped = false;
|
||||||
|
// set may come before the file is decoded
|
||||||
|
#pitch: number;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
context: AudioContext,
|
||||||
|
buffer: Promise<AudioBuffer | undefined>,
|
||||||
|
out: AudioNode,
|
||||||
|
settings: VoiceSettings,
|
||||||
|
) {
|
||||||
|
this.#pitch = settings.pitch;
|
||||||
|
this.#gain = new GainNode(context, { gain: Math.min(1, settings.volume) });
|
||||||
|
if (settings.at) {
|
||||||
|
this.#panner = new PannerNode(context, {
|
||||||
|
panningModel: "HRTF",
|
||||||
|
distanceModel: "linear",
|
||||||
|
refDistance: 1,
|
||||||
|
maxDistance: settings.range,
|
||||||
|
positionX: settings.at.x,
|
||||||
|
positionY: settings.at.y,
|
||||||
|
positionZ: settings.at.z,
|
||||||
|
});
|
||||||
|
this.#gain.connect(this.#panner).connect(out);
|
||||||
|
} else {
|
||||||
|
this.#gain.connect(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the first time a file plays it starts once it's decoded
|
||||||
|
buffer.then((buffer) => {
|
||||||
|
if (!buffer || this.#stopped) {
|
||||||
|
this.ended = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// played with an offset past its end, it would have finished already
|
||||||
|
if (!settings.loop && settings.offset >= buffer.duration) {
|
||||||
|
this.stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const source = new AudioBufferSourceNode(context, {
|
||||||
|
buffer,
|
||||||
|
loop: settings.loop,
|
||||||
|
playbackRate: this.#pitch,
|
||||||
|
});
|
||||||
|
source.connect(this.#gain);
|
||||||
|
source.onended = () => {
|
||||||
|
this.ended = true;
|
||||||
|
this.#disconnect();
|
||||||
|
};
|
||||||
|
source.start(0, settings.offset % buffer.duration);
|
||||||
|
this.#source = source;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
move(at: Position) {
|
||||||
|
if (!this.#panner) return;
|
||||||
|
this.#panner.positionX.value = at.x;
|
||||||
|
this.#panner.positionY.value = at.y;
|
||||||
|
this.#panner.positionZ.value = at.z;
|
||||||
|
}
|
||||||
|
|
||||||
|
set(volume: number, pitch: number, range: number) {
|
||||||
|
this.#gain.gain.value = Math.min(1, volume);
|
||||||
|
this.#pitch = pitch;
|
||||||
|
if (this.#source) this.#source.playbackRate.value = pitch;
|
||||||
|
if (this.#panner) this.#panner.maxDistance = range;
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.#stopped = true;
|
||||||
|
this.ended = true;
|
||||||
|
this.#source?.stop();
|
||||||
|
this.#disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
#disconnect() {
|
||||||
|
this.#source?.disconnect();
|
||||||
|
this.#gain.disconnect();
|
||||||
|
this.#panner?.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,19 +6,24 @@
|
|||||||
// entities, visuals and changing blocks. it's made of what the loaded mods' worldgen data makes the ground of, and other
|
// entities, visuals and changing blocks. it's made of what the loaded mods' worldgen data makes the ground of, and other
|
||||||
// blocks picked by what they are (a cutout plant, a translucent cube), not by their ids
|
// blocks picked by what they are (a cutout plant, a translucent cube), not by their ids
|
||||||
import { Alea } from "@paulaboks/rng";
|
import { Alea } from "@paulaboks/rng";
|
||||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts";
|
import { AIR, CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||||
import { DEFAULT_MODEL } from "$/common/block_models.ts";
|
import { ChunkColumn } from "@/common/section.ts";
|
||||||
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "$/common/worldgen/noise.ts";
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import { can_stand_on, default_block_value } from "$/common/utils.ts";
|
import { DEFAULT_MODEL } from "@/common/block_models.ts";
|
||||||
import type { Biome } from "$/common/worldgen/biomes.ts";
|
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "@/common/worldgen/noise.ts";
|
||||||
import type { NoiseSettingsJson } from "$/common/worldgen/data.ts";
|
import { can_stand_on, default_block_value } from "@/common/utils.ts";
|
||||||
|
import type { Biome } from "@/common/worldgen/biomes.ts";
|
||||||
|
import type { NoiseSettingsJson } from "@/common/worldgen/data.ts";
|
||||||
|
|
||||||
const SEED = "benchmark";
|
const SEED = "benchmark";
|
||||||
// chunks go from -LEVEL_RADIUS to LEVEL_RADIUS - 1 each way. the outermost ring is only there so the ones inside it
|
// chunks go from -LEVEL_RADIUS to LEVEL_RADIUS - 1 each way. the outermost ring is only there so the ones inside it
|
||||||
// can be meshed, see ClientLevel.can_mesh
|
// can be meshed, see ClientLevel.can_mesh
|
||||||
export const LEVEL_RADIUS = 13;
|
export const LEVEL_RADIUS = 13;
|
||||||
export const SEA_LEVEL = 62;
|
export const SEA_LEVEL = 62;
|
||||||
|
// 0 to 256 with sky light whatever the world's dimension is, so runs compare. y in its chunks counts from 0
|
||||||
|
export const LEVEL_SHAPE = DEFAULT_SHAPE;
|
||||||
|
const TOP = LEVEL_SHAPE.max_y;
|
||||||
|
|
||||||
// the lake, and flat ground for the scenes. the terrain eases into each over BLEND blocks
|
// the lake, and flat ground for the scenes. the terrain eases into each over BLEND blocks
|
||||||
export const ZONES = {
|
export const ZONES = {
|
||||||
@@ -89,11 +94,15 @@ export function bench_blocks(visual_blocks: ReadonlySet<number>): BenchBlocks {
|
|||||||
|
|
||||||
const solid = all.filter((b) => plain(b) && cube(b) && layer(b) === "solid" && b.block.has_collision);
|
const solid = all.filter((b) => plain(b) && cube(b) && layer(b) === "solid" && b.block.has_collision);
|
||||||
if (solid.length === 0) throw new Error("The benchmark needs a solid block to build its level with");
|
if (solid.length === 0) throw new Error("The benchmark needs a solid block to build its level with");
|
||||||
// what the world generator fills the ground with, and a biome with trees for its cover
|
// what the world generator fills the ground with, and a grassy biome for its cover
|
||||||
const by_key = ([a]: [string, unknown], [b]: [string, unknown]) => a.localeCompare(b);
|
const by_key = ([a]: [string, unknown], [b]: [string, unknown]) => a.localeCompare(b);
|
||||||
const settings = EverythingRegistry.entries<NoiseSettingsJson>("noise_settings").sort(by_key)[0]?.[1];
|
const settings = EverythingRegistry.entries<NoiseSettingsJson>("noise_settings").sort(by_key)[0]?.[1];
|
||||||
const biomes = EverythingRegistry.entries<Biome>("biomes").sort(by_key).map(([, biome]) => biome);
|
const biomes = EverythingRegistry.entries<Biome>("biomes").sort(by_key).map(([, biome]) => biome);
|
||||||
const biome = biomes.find((biome) => biome.trees) ?? biomes[0];
|
const grassy = (biome: Biome) => {
|
||||||
|
const top = by_id(biome.surface.top);
|
||||||
|
return top !== undefined && tinted(top, "grass");
|
||||||
|
};
|
||||||
|
const biome = biomes.find(grassy) ?? biomes[0];
|
||||||
const stone = by_id(settings?.default_block) ?? solid[0];
|
const stone = by_id(settings?.default_block) ?? solid[0];
|
||||||
const top = by_id(biome?.surface.top) ?? solid.find((b) => tinted(b, "grass")) ?? stone;
|
const top = by_id(biome?.surface.top) ?? solid.find((b) => tinted(b, "grass")) ?? stone;
|
||||||
const filler = by_id(biome?.surface.filler) ?? stone;
|
const filler = by_id(biome?.surface.filler) ?? stone;
|
||||||
@@ -143,12 +152,12 @@ export class BenchTerrain {
|
|||||||
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
|
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
|
||||||
height = zone.height + (height - zone.height) * t;
|
height = zone.height + (height - zone.height) * t;
|
||||||
}
|
}
|
||||||
return Math.min(CHUNK_HEIGHT - 32, Math.round(height));
|
return Math.min(TOP - 32, Math.round(height));
|
||||||
}
|
}
|
||||||
|
|
||||||
chunk(chunk_x: number, chunk_z: number): { blocks: Uint32Array; biomes: string[] } {
|
chunk(chunk_x: number, chunk_z: number): ChunkColumn {
|
||||||
const b = this.#blocks;
|
const b = this.#blocks;
|
||||||
const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
|
const blocks = new Uint32Array(LEVEL_SHAPE.volume);
|
||||||
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
|
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
|
||||||
const x0 = chunk_x * CHUNK_SIZE;
|
const x0 = chunk_x * CHUNK_SIZE;
|
||||||
const z0 = chunk_z * CHUNK_SIZE;
|
const z0 = chunk_z * CHUNK_SIZE;
|
||||||
@@ -156,7 +165,7 @@ export class BenchTerrain {
|
|||||||
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
|
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
|
||||||
const lx = x - x0;
|
const lx = x - x0;
|
||||||
const lz = z - z0;
|
const lz = z - z0;
|
||||||
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= CHUNK_HEIGHT) return;
|
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= TOP) return;
|
||||||
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
|
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
|
||||||
if (!only_air || blocks[index] === AIR) blocks[index] = value;
|
if (!only_air || blocks[index] === AIR) blocks[index] = value;
|
||||||
};
|
};
|
||||||
@@ -189,7 +198,7 @@ export class BenchTerrain {
|
|||||||
}
|
}
|
||||||
this.#trees(chunk_x, chunk_z, set);
|
this.#trees(chunk_x, chunk_z, set);
|
||||||
this.#features(set);
|
this.#features(set);
|
||||||
return { blocks, biomes: new Array(CHUNK_AREA).fill(b.biome) };
|
return ChunkColumn.from_flat(chunk_x, chunk_z, LEVEL_SHAPE, blocks, new Array(CHUNK_AREA).fill(b.biome));
|
||||||
}
|
}
|
||||||
|
|
||||||
#in_zone(x: number, z: number, margin: number) {
|
#in_zone(x: number, z: number, margin: number) {
|
||||||
|
|||||||
@@ -7,17 +7,18 @@
|
|||||||
// so what's around the player doesn't change the numbers. each scene is timed with frames paced by the display, then
|
// so what's around the player doesn't change the numbers. each scene is timed with frames paced by the display, then
|
||||||
// with frames back to back (see render_debug.uncapped), after a warmup. meshing the whole level is timed too, the
|
// with frames back to back (see render_debug.uncapped), after a warmup. meshing the whole level is timed too, the
|
||||||
// first time and again. the report says what the computer and the browser are, see report.ts
|
// first time and again. the report says what the computer and the browser are, see report.ts
|
||||||
import { Camera } from "$/client/camera.ts";
|
import { Camera } from "@/client/camera.ts";
|
||||||
import { ClientLevel } from "$/client/level/client_level.ts";
|
import { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
import type { GameRenderer } from "$/client/rendering/game_renderer.ts";
|
import type { GameRenderer } from "@/client/rendering/game_renderer.ts";
|
||||||
import { block_visuals } from "$/client/rendering/visuals.ts";
|
import { block_visuals } from "@/client/rendering/visuals.ts";
|
||||||
import { draw_item } from "$/client/rendering/render_utils.ts";
|
import { draw_item } from "@/client/rendering/render_utils.ts";
|
||||||
import { InputManager } from "$/client/input_manager.ts";
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
import { type FrameSample, profiler } from "$/client/profiler.ts";
|
import { platform } from "@/client/platform.ts";
|
||||||
import { RemotePlayer } from "$/client/entity/remote_player.ts";
|
import { type FrameSample, profiler } from "@/client/profiler.ts";
|
||||||
import { RemoteEntity } from "$/client/entity/remote_entity.ts";
|
import { RemotePlayer } from "@/client/entity/remote_player.ts";
|
||||||
import { ItemEntity } from "$/client/entity/item_entity.ts";
|
import { RemoteEntity } from "@/client/entity/remote_entity.ts";
|
||||||
import { tick_texture_animations } from "$/client/texture_animations.ts";
|
import { ItemEntity } from "@/client/entity/item_entity.ts";
|
||||||
|
import { tick_texture_animations } from "@/client/texture_animations.ts";
|
||||||
import {
|
import {
|
||||||
adapter_info,
|
adapter_info,
|
||||||
device,
|
device,
|
||||||
@@ -26,20 +27,21 @@ import {
|
|||||||
render_debug,
|
render_debug,
|
||||||
render_stats,
|
render_stats,
|
||||||
set_canvas_size,
|
set_canvas_size,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { ID_MASK, SLOT_SIZE, STATE_SHIFT } from "$/common/constants.ts";
|
import { ID_MASK, SLOT_SIZE, STATE_SHIFT } from "@/common/constants.ts";
|
||||||
import { AIR_ID } from "$/common/protocol.ts";
|
import { AIR_ID } from "@/common/protocol.ts";
|
||||||
import { TIMES_OF_DAY } from "$/common/time.ts";
|
import { TIMES_OF_DAY } from "@/common/time.ts";
|
||||||
import { type BlockRegistry, EverythingRegistry, RENDER_LAYERS } from "$/common/everything_registry.ts";
|
import { type BlockRegistry, EverythingRegistry, RENDER_LAYERS } from "@/common/everything_registry.ts";
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
import type { EntityJson } from "@/common/mod_data.ts";
|
||||||
import type { ModListing } from "$/common/mod_loader.ts";
|
import type { ModListing } from "@/common/mod_loader.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import { display_name } from "$/common/utils.ts";
|
import { display_name } from "@/common/utils.ts";
|
||||||
import {
|
import {
|
||||||
bench_blocks,
|
bench_blocks,
|
||||||
type BenchBlocks,
|
type BenchBlocks,
|
||||||
BenchTerrain,
|
BenchTerrain,
|
||||||
LEVEL_RADIUS,
|
LEVEL_RADIUS,
|
||||||
|
LEVEL_SHAPE,
|
||||||
SEA_LEVEL,
|
SEA_LEVEL,
|
||||||
UPDATE_WALL,
|
UPDATE_WALL,
|
||||||
ZONES,
|
ZONES,
|
||||||
@@ -128,8 +130,9 @@ export class RenderBenchmark {
|
|||||||
// a line of names for each row of the gui scene's slots
|
// a line of names for each row of the gui scene's slots
|
||||||
#gui_lines: string[];
|
#gui_lines: string[];
|
||||||
#system: SystemInfo;
|
#system: SystemInfo;
|
||||||
// the page was hidden, which stops frames
|
// the game was hidden, which held frames back
|
||||||
#hidden = false;
|
#hidden = false;
|
||||||
|
#stop_watching_shown: () => void;
|
||||||
#saved_debug = { ...render_debug };
|
#saved_debug = { ...render_debug };
|
||||||
#saved_draw: Record<string, boolean>;
|
#saved_draw: Record<string, boolean>;
|
||||||
|
|
||||||
@@ -145,7 +148,7 @@ export class RenderBenchmark {
|
|||||||
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
|
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
|
||||||
);
|
);
|
||||||
|
|
||||||
this.#level = new ClientLevel([], LEVEL_RADIUS);
|
this.#level = new ClientLevel([], LEVEL_SHAPE, LEVEL_RADIUS);
|
||||||
this.#level.time = TIMES_OF_DAY.noon;
|
this.#level.time = TIMES_OF_DAY.noon;
|
||||||
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
|
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
|
||||||
this.#system = system_info(this.#level.workers.size);
|
this.#system = system_info(this.#level.workers.size);
|
||||||
@@ -156,7 +159,7 @@ export class RenderBenchmark {
|
|||||||
for (const key of Object.keys(draw) as (keyof typeof draw)[]) draw[key] = true;
|
for (const key of Object.keys(draw) as (keyof typeof draw)[]) draw[key] = true;
|
||||||
Object.assign(render_debug, { msaa: false, split_passes: false, uncapped: false });
|
Object.assign(render_debug, { msaa: false, split_passes: false, uncapped: false });
|
||||||
set_canvas_size(RESOLUTION);
|
set_canvas_size(RESOLUTION);
|
||||||
document.addEventListener("visibilitychange", this.#on_visibility);
|
this.#stop_watching_shown = platform.on_shown(() => this.#hidden = true);
|
||||||
this.#flow = this.#run();
|
this.#flow = this.#run();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,7 +169,7 @@ export class RenderBenchmark {
|
|||||||
if (InputManager.is_key_pressed("Escape")) {
|
if (InputManager.is_key_pressed("Escape")) {
|
||||||
this.#end("The benchmark was stopped");
|
this.#end("The benchmark was stopped");
|
||||||
} else if (this.#hidden) {
|
} else if (this.#hidden) {
|
||||||
this.#end("The benchmark stopped since the page was hidden, which holds frames back");
|
this.#end("The benchmark stopped since the game was hidden, which holds frames back");
|
||||||
} else {
|
} else {
|
||||||
this.#flow.next();
|
this.#flow.next();
|
||||||
}
|
}
|
||||||
@@ -215,14 +218,10 @@ export class RenderBenchmark {
|
|||||||
set_canvas_size(undefined);
|
set_canvas_size(undefined);
|
||||||
profiler.samples = undefined;
|
profiler.samples = undefined;
|
||||||
if (gpu_timer) gpu_timer.samples = undefined;
|
if (gpu_timer) gpu_timer.samples = undefined;
|
||||||
document.removeEventListener("visibilitychange", this.#on_visibility);
|
this.#stop_watching_shown();
|
||||||
this.#on_end(result);
|
this.#on_end(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
#on_visibility = () => {
|
|
||||||
if (document.hidden) this.#hidden = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
// the whole benchmark, a frame at each yield
|
// the whole benchmark, a frame at each yield
|
||||||
*#run(): Generator<void, void> {
|
*#run(): Generator<void, void> {
|
||||||
yield* this.#build();
|
yield* this.#build();
|
||||||
@@ -242,6 +241,7 @@ export class RenderBenchmark {
|
|||||||
system: this.#system,
|
system: this.#system,
|
||||||
mods: this.#mods.map((mod) => `${mod.id} ${mod.version}`),
|
mods: this.#mods.map((mod) => `${mod.id} ${mod.version}`),
|
||||||
resolution: `${RESOLUTION.width}x${RESOLUTION.height}`,
|
resolution: `${RESOLUTION.width}x${RESOLUTION.height}`,
|
||||||
|
render_regions: render_debug.render_regions,
|
||||||
level: { chunks: this.#level.chunks.size, build_ms: this.#build_ms },
|
level: { chunks: this.#level.chunks.size, build_ms: this.#build_ms },
|
||||||
first_mesh,
|
first_mesh,
|
||||||
remesh,
|
remesh,
|
||||||
@@ -260,8 +260,7 @@ export class RenderBenchmark {
|
|||||||
const start = performance.now();
|
const start = performance.now();
|
||||||
while (built < chunks.length && performance.now() - start < BUILD_MS_PER_FRAME) {
|
while (built < chunks.length && performance.now() - start < BUILD_MS_PER_FRAME) {
|
||||||
const [x, z] = chunks[built++];
|
const [x, z] = chunks[built++];
|
||||||
const { blocks, biomes } = terrain.chunk(x, z);
|
this.#level.set_chunk(terrain.chunk(x, z));
|
||||||
this.#level.set_chunk(x, z, blocks, biomes);
|
|
||||||
}
|
}
|
||||||
this.#build_ms += performance.now() - start;
|
this.#build_ms += performance.now() - start;
|
||||||
this.status = `building the level, ${Math.floor(built / chunks.length * 100)}%`;
|
this.status = `building the level, ${Math.floor(built / chunks.length * 100)}%`;
|
||||||
@@ -334,7 +333,7 @@ export class RenderBenchmark {
|
|||||||
return {
|
return {
|
||||||
draw_calls,
|
draw_calls,
|
||||||
quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0),
|
quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0),
|
||||||
chunks_in_view: level_renderer.visible_chunks,
|
sections_in_view: level_renderer.visible_sections,
|
||||||
entities_in_view: level_renderer.drawn_entities,
|
entities_in_view: level_renderer.drawn_entities,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -558,8 +557,9 @@ function system_info(workers: number): SystemInfo {
|
|||||||
gpu_features: [...device.features].sort(),
|
gpu_features: [...device.features].sort(),
|
||||||
timestamps: gpu_timer?.supported ?? false,
|
timestamps: gpu_timer?.supported ?? false,
|
||||||
canvas_format: navigator.gpu.getPreferredCanvasFormat(),
|
canvas_format: navigator.gpu.getPreferredCanvasFormat(),
|
||||||
device_pixel_ratio: devicePixelRatio,
|
// the desktop app's window is drawn a pixel to a pixel
|
||||||
screen: `${screen.width}x${screen.height}`,
|
device_pixel_ratio: globalThis.devicePixelRatio ?? 1,
|
||||||
|
screen: globalThis.screen && `${screen.width}x${screen.height}`,
|
||||||
workers,
|
workers,
|
||||||
};
|
};
|
||||||
const hints = (navigator as { userAgentData?: UserAgentData }).userAgentData;
|
const hints = (navigator as { userAgentData?: UserAgentData }).userAgentData;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
// tools/compare_benchmarks.ts reads to put runs side by side
|
// tools/compare_benchmarks.ts reads to put runs side by side
|
||||||
|
|
||||||
// changes when the scenes or the level change, since runs of different versions don't compare
|
// changes when the scenes or the level change, since runs of different versions don't compare
|
||||||
export const BENCHMARK_VERSION = 1;
|
export const BENCHMARK_VERSION = 2;
|
||||||
|
|
||||||
// how fast and how smooth frames were, from the time between them. the lows are the fps of the frame that 99% (and
|
// how fast and how smooth frames were, from the time between them. the lows are the fps of the frame that 99% (and
|
||||||
// 99.9%) of the others were faster than
|
// 99.9%) of the others were faster than
|
||||||
@@ -36,7 +36,7 @@ export interface SceneResult {
|
|||||||
// what the first paced frame drew, which runs of the same version should about agree on
|
// what the first paced frame drew, which runs of the same version should about agree on
|
||||||
draw_calls: number;
|
draw_calls: number;
|
||||||
quads: number;
|
quads: number;
|
||||||
chunks_in_view: number;
|
sections_in_view: number;
|
||||||
entities_in_view: number;
|
entities_in_view: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,7 +62,8 @@ export interface SystemInfo {
|
|||||||
// the median fps where nothing is drawn, which is the display's refresh when the browser holds frames to it
|
// the median fps where nothing is drawn, which is the display's refresh when the browser holds frames to it
|
||||||
refresh_hz?: number;
|
refresh_hz?: number;
|
||||||
device_pixel_ratio: number;
|
device_pixel_ratio: number;
|
||||||
screen: string;
|
// the browser's, the desktop app doesn't know it
|
||||||
|
screen?: string;
|
||||||
// meshing workers, see ChunkWorkerPool
|
// meshing workers, see ChunkWorkerPool
|
||||||
workers: number;
|
workers: number;
|
||||||
}
|
}
|
||||||
@@ -74,6 +75,8 @@ export interface BenchmarkReport {
|
|||||||
// "id version"
|
// "id version"
|
||||||
mods: string[];
|
mods: string[];
|
||||||
resolution: string;
|
resolution: string;
|
||||||
|
// the f3 window's switch, see ClientLevel.use_render_regions
|
||||||
|
render_regions?: boolean;
|
||||||
level: { chunks: number; build_ms: number };
|
level: { chunks: number; build_ms: number };
|
||||||
first_mesh: MeshingResult;
|
first_mesh: MeshingResult;
|
||||||
remesh: MeshingResult;
|
remesh: MeshingResult;
|
||||||
@@ -116,11 +119,11 @@ export function format_report(report: BenchmarkReport): string {
|
|||||||
const memory = system.memory_gb ? `, ${system.memory_gb} GB` : "";
|
const memory = system.memory_gb ? `, ${system.memory_gb} GB` : "";
|
||||||
const refresh = system.refresh_hz ? `, ${system.refresh_hz} Hz` : "";
|
const refresh = system.refresh_hz ? `, ${system.refresh_hz} Hz` : "";
|
||||||
const lines = [
|
const lines = [
|
||||||
`## bworld render benchmark ${report.version}`,
|
`## cubi render benchmark ${report.version}`,
|
||||||
"",
|
"",
|
||||||
`${system.browser} on ${system.os}, ${system.gpu}`,
|
`${system.browser} on ${system.os}, ${system.gpu}`,
|
||||||
`${system.cpu_threads} threads${memory}${refresh}, drawn at ${report.resolution}, ${system.workers} mesh workers` +
|
`${system.cpu_threads} threads${memory}${refresh}, drawn at ${report.resolution}, ${system.workers} mesh workers` +
|
||||||
(system.timestamps ? "" : ", no gpu timestamps"),
|
(system.timestamps ? "" : ", no gpu timestamps") + (report.render_regions ? ", render regions" : ""),
|
||||||
`${report.date}, mods: ${report.mods.join(", ") || "none"}`,
|
`${report.date}, mods: ${report.mods.join(", ") || "none"}`,
|
||||||
"",
|
"",
|
||||||
"| scene | fps | 1% low | 0.1% low | uncapped fps | cpu ms | gpu ms | draw calls | quads |",
|
"| scene | fps | 1% low | 0.1% low | uncapped fps | cpu ms | gpu ms | draw calls | quads |",
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the page's keys and mouse for InputManager, and grabbing the mouse with the browser's pointer lock
|
||||||
|
import { InputManager } from "./input_manager.ts";
|
||||||
|
|
||||||
|
// the keys the game keeps in fullscreen, see "fullscreenchange". not every key: with all of them locked, chromium
|
||||||
|
// can keep alt+tab and the windows key from the os too
|
||||||
|
const FULLSCREEN_LOCKED_KEYS = ["Escape", "KeyW"];
|
||||||
|
|
||||||
|
// chromium's keyboard lock api, typescript's dom types don't have it yet
|
||||||
|
interface KeyboardLock {
|
||||||
|
lock(codes?: string[]): Promise<void>;
|
||||||
|
unlock(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let canvas: HTMLCanvasElement;
|
||||||
|
|
||||||
|
let pointer_lock_flag = false;
|
||||||
|
let mouse_ungrab_timer = 0;
|
||||||
|
let mouse_ungrab_timeout = -1;
|
||||||
|
let pointer_lock_waiting = false;
|
||||||
|
// chrome sometimes sends a huge movement with the first mouse event after the lock starts
|
||||||
|
let skip_look_event = false;
|
||||||
|
// the browser let go of the mouse while the game wanted it, like escape or switching windows
|
||||||
|
let lost_pointer_lock = false;
|
||||||
|
|
||||||
|
export function listen_to_page(page_canvas: HTMLCanvasElement) {
|
||||||
|
canvas = page_canvas;
|
||||||
|
|
||||||
|
self.addEventListener("keydown", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
InputManager.key_down(e.code, e.key, is_shortcut(e));
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("blur", () => InputManager.release_all());
|
||||||
|
|
||||||
|
self.addEventListener("keyup", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
InputManager.key_up(e.code);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("mousedown", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
if (!document.hasFocus() && document.pointerLockElement !== canvas) {
|
||||||
|
set_mouse_grabbed(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
InputManager.mouse_down(e.button);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener("mouseup", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
InputManager.mouse_up(e.button);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ctrl+scroll (and pinching a trackpad, which browsers send as that) would zoom the page. only a listener that
|
||||||
|
// isn't passive can stop it, and on the window they're passive unless told otherwise
|
||||||
|
self.addEventListener("wheel", (e) => {
|
||||||
|
if (e.ctrlKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
InputManager.scroll(e.deltaY);
|
||||||
|
}, { passive: false });
|
||||||
|
|
||||||
|
document.addEventListener("mousemove", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (document.pointerLockElement === canvas) {
|
||||||
|
if (skip_look_event) {
|
||||||
|
skip_look_event = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
InputManager.look(e.movementX, e.movementY);
|
||||||
|
} else {
|
||||||
|
const rect = canvas.getBoundingClientRect();
|
||||||
|
InputManager.move_cursor(e.clientX - rect.left, e.clientY - rect.top);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener("pointerlockchange", () => {
|
||||||
|
skip_look_event = document.pointerLockElement === canvas;
|
||||||
|
self.setTimeout(() => {
|
||||||
|
const grab = document.pointerLockElement === canvas;
|
||||||
|
if (!grab) {
|
||||||
|
if (pointer_lock_flag) {
|
||||||
|
mouse_ungrab_timer = performance.now();
|
||||||
|
lost_pointer_lock = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pointer_lock_flag = grab;
|
||||||
|
}, 60);
|
||||||
|
pointer_lock_waiting = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// in fullscreen, chromium's keyboard lock gives the game escape (holding it still leaves fullscreen) and ctrl+w,
|
||||||
|
// instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before
|
||||||
|
document.addEventListener("fullscreenchange", () => {
|
||||||
|
const keyboard = (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard;
|
||||||
|
if (!keyboard?.lock) return;
|
||||||
|
if (document.fullscreenElement) {
|
||||||
|
keyboard.lock(FULLSCREEN_LOCKED_KEYS).catch(() => {});
|
||||||
|
} else {
|
||||||
|
keyboard.unlock();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener("pointerlockerror", () => {
|
||||||
|
pointer_lock_waiting = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it
|
||||||
|
// isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl
|
||||||
|
function is_shortcut(e: KeyboardEvent) {
|
||||||
|
return e.metaKey || (e.ctrlKey && !e.altKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function set_mouse_grabbed(grab: boolean) {
|
||||||
|
pointer_lock_flag = grab;
|
||||||
|
// a retry to grab it again mustn't happen once it shouldn't be grabbed
|
||||||
|
if (!grab && mouse_ungrab_timeout !== -1) {
|
||||||
|
self.clearTimeout(mouse_ungrab_timeout);
|
||||||
|
mouse_ungrab_timeout = -1;
|
||||||
|
}
|
||||||
|
// already how it should be, the game calls this every frame
|
||||||
|
const locked = document.pointerLockElement === canvas;
|
||||||
|
if (grab ? locked : !locked && !pointer_lock_waiting) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const t = performance.now();
|
||||||
|
if (grab) {
|
||||||
|
InputManager.mouse_x = -1;
|
||||||
|
InputManager.mouse_y = -1;
|
||||||
|
pointer_lock_waiting = true;
|
||||||
|
try {
|
||||||
|
await canvas.requestPointerLock();
|
||||||
|
} catch (_) { /* */ }
|
||||||
|
if (mouse_ungrab_timeout !== -1) {
|
||||||
|
self.clearTimeout(mouse_ungrab_timeout);
|
||||||
|
}
|
||||||
|
mouse_ungrab_timeout = -1;
|
||||||
|
if (t - mouse_ungrab_timer < 3000) {
|
||||||
|
mouse_ungrab_timeout = self.setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await canvas.requestPointerLock();
|
||||||
|
} catch (_) { /* */ }
|
||||||
|
}, 3100 - (t - mouse_ungrab_timer));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!pointer_lock_waiting) {
|
||||||
|
document.exitPointerLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// whether the browser took the mouse away since the last call, it eats the escape that does it
|
||||||
|
export function take_lost_pointer_lock() {
|
||||||
|
const lost = lost_pointer_lock;
|
||||||
|
lost_pointer_lock = false;
|
||||||
|
return lost;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function is_mouse_grabbed() {
|
||||||
|
return document.hasFocus() && document.pointerLockElement === canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toggle_fullscreen() {
|
||||||
|
if (!document.fullscreenElement) {
|
||||||
|
canvas.requestFullscreen();
|
||||||
|
} else {
|
||||||
|
document.exitFullscreen();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the client in a browser page, see platform.ts
|
||||||
|
import type { Platform } from "./platform.ts";
|
||||||
|
import { render_debug } from "./renderer/mod.ts";
|
||||||
|
import { CreditsScreen } from "./gui/credits_screen.ts";
|
||||||
|
import { is_mouse_grabbed, set_mouse_grabbed, take_lost_pointer_lock, toggle_fullscreen } from "./browser_input.ts";
|
||||||
|
|
||||||
|
// with render_debug.uncapped, the most frames between two of the display's refreshes. it's the highest fps that shows,
|
||||||
|
// 960 on a 60 hz display, and what the gpu can be behind by
|
||||||
|
const UNCAPPED_FRAMES_PER_REFRESH = 16;
|
||||||
|
|
||||||
|
// with render_debug.uncapped: frames since the display last refreshed, and the frame waiting for the next one
|
||||||
|
let frames_this_refresh = 0;
|
||||||
|
let waiting_for_refresh: ((time: number) => void) | undefined;
|
||||||
|
let refresh_requested = false;
|
||||||
|
let next_task: MessageChannel | undefined;
|
||||||
|
let next_task_frame: ((time: number) => void) | undefined;
|
||||||
|
|
||||||
|
// with the display's refresh, or with render_debug.uncapped right away, so frames aren't held to vsync and show what
|
||||||
|
// they cost. up to UNCAPPED_FRAMES_PER_REFRESH, then it waits for the next refresh, which the browser holds back
|
||||||
|
// while the gpu is behind, so frames the gpu can't keep up with don't pile up. the browser saying a frame is done
|
||||||
|
// can't be waited on instead, firefox only says so every 100 ms when nothing else is sent to the gpu
|
||||||
|
function request_frame(frame: (time: number) => void) {
|
||||||
|
if (!render_debug.uncapped) {
|
||||||
|
requestAnimationFrame(frame);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!refresh_requested) {
|
||||||
|
refresh_requested = true;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
refresh_requested = false;
|
||||||
|
frames_this_refresh = 0;
|
||||||
|
const waiting = waiting_for_refresh;
|
||||||
|
waiting_for_refresh = undefined;
|
||||||
|
waiting?.(performance.now());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
frames_this_refresh += 1;
|
||||||
|
if (frames_this_refresh < UNCAPPED_FRAMES_PER_REFRESH) {
|
||||||
|
// a task of its own, so input and the workers' messages get handled in between
|
||||||
|
if (!next_task) {
|
||||||
|
next_task = new MessageChannel();
|
||||||
|
next_task.port1.onmessage = () => next_task_frame?.(performance.now());
|
||||||
|
}
|
||||||
|
next_task_frame = frame;
|
||||||
|
next_task.port2.postMessage(null);
|
||||||
|
} else {
|
||||||
|
waiting_for_refresh = frame;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pages that aren't https or localhost have no clipboard api, like a server on another computer, but the old way
|
||||||
|
// still copies from a click
|
||||||
|
function write_clipboard(text: string): Promise<void> {
|
||||||
|
if (navigator.clipboard) return navigator.clipboard.writeText(text);
|
||||||
|
const area = document.createElement("textarea");
|
||||||
|
area.value = text;
|
||||||
|
document.body.append(area);
|
||||||
|
area.select();
|
||||||
|
const copied = document.execCommand("copy");
|
||||||
|
area.remove();
|
||||||
|
return copied ? Promise.resolve() : Promise.reject(new Error("Couldn't copy"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function show_fatal_error(message: string) {
|
||||||
|
document.exitPointerLock?.();
|
||||||
|
|
||||||
|
const overlay = document.createElement("div");
|
||||||
|
overlay.style.cssText =
|
||||||
|
"position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;" +
|
||||||
|
"gap:12px;background:rgba(0,0,0,0.85);color:white;font:20px system-ui,sans-serif;text-align:center;";
|
||||||
|
const text = document.createElement("div");
|
||||||
|
text.textContent = message;
|
||||||
|
const hint = document.createElement("div");
|
||||||
|
hint.textContent = "Reload the page to try again.";
|
||||||
|
hint.style.cssText = "font-size:14px;opacity:0.7;";
|
||||||
|
overlay.append(text, hint);
|
||||||
|
document.body.append(overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const browser_platform: Platform = {
|
||||||
|
get page() {
|
||||||
|
return new URL(location.href);
|
||||||
|
},
|
||||||
|
restart(url) {
|
||||||
|
location.href = url.href;
|
||||||
|
},
|
||||||
|
request_frame,
|
||||||
|
get storage() {
|
||||||
|
return localStorage;
|
||||||
|
},
|
||||||
|
on_shown(shown) {
|
||||||
|
const listener = () => {
|
||||||
|
if (!document.hidden) shown();
|
||||||
|
};
|
||||||
|
document.addEventListener("visibilitychange", listener);
|
||||||
|
return () => document.removeEventListener("visibilitychange", listener);
|
||||||
|
},
|
||||||
|
// sprinting is ctrl and walking is w, and ctrl+w closes the tab without the page getting a say. in fullscreen
|
||||||
|
// the keyboard lock catches it instead (see browser_input.ts)
|
||||||
|
confirm_leaving(confirm) {
|
||||||
|
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
|
||||||
|
},
|
||||||
|
show_fatal_error,
|
||||||
|
credits_screen: (on_back) => new CreditsScreen(on_back),
|
||||||
|
read_clipboard: () =>
|
||||||
|
navigator.clipboard ? navigator.clipboard.readText() : Promise.reject(new Error("No clipboard")),
|
||||||
|
write_clipboard,
|
||||||
|
set_mouse_grabbed,
|
||||||
|
is_mouse_grabbed,
|
||||||
|
take_lost_mouse: take_lost_pointer_lock,
|
||||||
|
toggle_fullscreen,
|
||||||
|
};
|
||||||
+33
-11
@@ -22,13 +22,14 @@ import { InputManager } from "./input_manager.ts";
|
|||||||
import { Connection } from "./network.ts";
|
import { Connection } from "./network.ts";
|
||||||
import { PauseScreen } from "./gui/pause_screen.ts";
|
import { PauseScreen } from "./gui/pause_screen.ts";
|
||||||
import { back_to_title } from "./gui/title_screen.ts";
|
import { back_to_title } from "./gui/title_screen.ts";
|
||||||
import { TICK_DELTA } from "$/common/constants.ts";
|
import { TICK_DELTA } from "@/common/constants.ts";
|
||||||
import { Container } from "$/common/inventory.ts";
|
import { Container } from "@/common/inventory.ts";
|
||||||
import { PLAYER_MENU } from "$/common/protocol.ts";
|
import { PLAYER_MENU } from "@/common/protocol.ts";
|
||||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
import type { EntityJson } from "@/common/mod_data.ts";
|
||||||
import { tick_texture_animations } from "./texture_animations.ts";
|
import { tick_texture_animations } from "./texture_animations.ts";
|
||||||
import type { RenderBenchmark } from "./benchmark/benchmark.ts";
|
import type { RenderBenchmark } from "./benchmark/benchmark.ts";
|
||||||
|
import { sounds } from "./sounds.ts";
|
||||||
|
|
||||||
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
|
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
|
||||||
const USE_REPEAT_MS = 200;
|
const USE_REPEAT_MS = 200;
|
||||||
@@ -77,7 +78,7 @@ export class Client {
|
|||||||
this.connection = connection;
|
this.connection = connection;
|
||||||
this.#on_disconnect = on_disconnect;
|
this.#on_disconnect = on_disconnect;
|
||||||
|
|
||||||
this.level = new ClientLevel(connection.server_blocks, this.options.render_distance);
|
this.level = new ClientLevel(connection.server_blocks, connection.shape, this.options.render_distance);
|
||||||
this.level.time = connection.time;
|
this.level.time = connection.time;
|
||||||
this.#sent_view_distance = this.options.render_distance;
|
this.#sent_view_distance = this.options.render_distance;
|
||||||
|
|
||||||
@@ -136,12 +137,14 @@ export class Client {
|
|||||||
// leaving on purpose, from the pause screen
|
// leaving on purpose, from the pause screen
|
||||||
disconnect() {
|
disconnect() {
|
||||||
this.#stopped = true;
|
this.#stopped = true;
|
||||||
|
sounds.stop_all();
|
||||||
this.connection.close();
|
this.connection.close();
|
||||||
back_to_title();
|
back_to_title();
|
||||||
}
|
}
|
||||||
|
|
||||||
#stop() {
|
#stop() {
|
||||||
this.#stopped = true;
|
this.#stopped = true;
|
||||||
|
sounds.stop_all();
|
||||||
this.level.dispose();
|
this.level.dispose();
|
||||||
InputManager.set_mouse_grabbed(false);
|
InputManager.set_mouse_grabbed(false);
|
||||||
}
|
}
|
||||||
@@ -183,8 +186,18 @@ export class Client {
|
|||||||
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
|
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.benchmark) this.benchmark.render(this.#pending_time / TICK_DELTA);
|
const partial_tick = this.#pending_time / TICK_DELTA;
|
||||||
else this.game_renderer.render(this, this.#pending_time / TICK_DELTA);
|
if (this.benchmark) {
|
||||||
|
this.benchmark.render(partial_tick);
|
||||||
|
} else {
|
||||||
|
this.game_renderer.render(this, partial_tick);
|
||||||
|
// from where the camera was just put
|
||||||
|
sounds.frame(
|
||||||
|
this.camera,
|
||||||
|
(id) => this.level.entities.get(id)?.render_position(partial_tick),
|
||||||
|
this.options.volume,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// one step of the game: what the server sent (chunks included), breaking, then every entity
|
// one step of the game: what the server sent (chunks included), breaking, then every entity
|
||||||
@@ -305,7 +318,7 @@ export class Client {
|
|||||||
player.entity_interaction_range,
|
player.entity_interaction_range,
|
||||||
(entity) =>
|
(entity) =>
|
||||||
entity instanceof RemotePlayer ||
|
entity instanceof RemotePlayer ||
|
||||||
(entity instanceof RemoteEntity && !entity.dead && is_hittable(entity)),
|
(entity instanceof RemoteEntity && !entity.dead && is_pickable(entity)),
|
||||||
);
|
);
|
||||||
// a block in front of the entity hides it
|
// a block in front of the entity hides it
|
||||||
this.hit_result = this.level.pick(
|
this.hit_result = this.level.pick(
|
||||||
@@ -339,6 +352,12 @@ export class Client {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// middle click in creative gives the block under the crosshair, like minecraft's pick block
|
||||||
|
if (hit && this.player.creative && InputManager.is_mouse_pressed(1)) {
|
||||||
|
const block = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block);
|
||||||
|
if (block) this.connection.send({ type: "chat", text: `/give ${block.id}` });
|
||||||
|
}
|
||||||
|
|
||||||
// a click uses right away, holding it on blocks keeps using every USE_REPEAT_MS. not while it's using an item
|
// a click uses right away, holding it on blocks keeps using every USE_REPEAT_MS. not while it's using an item
|
||||||
const now = performance.now();
|
const now = performance.now();
|
||||||
const use_pressed = InputManager.is_mouse_pressed(2) && !this.player.using_item;
|
const use_pressed = InputManager.is_mouse_pressed(2) && !this.player.using_item;
|
||||||
@@ -364,6 +383,8 @@ export class Client {
|
|||||||
if (!attacking && using) {
|
if (!attacking && using) {
|
||||||
this.game_mode.use_item_on(hit);
|
this.game_mode.use_item_on(hit);
|
||||||
}
|
}
|
||||||
|
} else if (use_pressed && this.entity_hit) {
|
||||||
|
this.game_mode.interact(this.entity_hit);
|
||||||
} else if (use_pressed) {
|
} else if (use_pressed) {
|
||||||
this.game_mode.use_item();
|
this.game_mode.use_item();
|
||||||
} else if (!this.entity_hit && InputManager.is_mouse_pressed(0)) {
|
} else if (!this.entity_hit && InputManager.is_mouse_pressed(0)) {
|
||||||
@@ -400,7 +421,8 @@ export class Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// mobs can be hit, scripted entities like the fishing hook can't. kinds the client doesn't know are left to the server
|
// what the crosshair can be on: mobs and objects, not scripted entities like the fishing hook. kinds the client doesn't
|
||||||
function is_hittable(entity: RemoteEntity) {
|
// know are left to the server
|
||||||
|
function is_pickable(entity: RemoteEntity) {
|
||||||
return EverythingRegistry.get<EntityJson>("entities", entity.type)?.behavior !== "scripted";
|
return EverythingRegistry.get<EntityJson>("entities", entity.type)?.behavior !== "scripted";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,221 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { AssetManager } from "./assets.ts";
|
||||||
|
import { Client } from "./client.ts";
|
||||||
|
import { InputManager } from "./input_manager.ts";
|
||||||
|
import { Connection } from "./network.ts";
|
||||||
|
import { Options } from "./options.ts";
|
||||||
|
import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress, type Welcome } from "./handshake.ts";
|
||||||
|
import { build_atlas, engine_textures } from "./atlas.ts";
|
||||||
|
import { set_texture_animations } from "./texture_animations.ts";
|
||||||
|
import type { TextureJson } from "@/common/texture_animation.ts";
|
||||||
|
import { ModLoadError } from "@/common/mod_loader.ts";
|
||||||
|
import { begin_drawing, clear_background, device, end_drawing, init_font, load_texture } from "./renderer/mod.ts";
|
||||||
|
import { is_stopped } from "./fatal.ts";
|
||||||
|
import { download_mods, load_client_mods, set_mods_client } from "./mods.ts";
|
||||||
|
import type { GuiScreen } from "./gui/gui_screen.ts";
|
||||||
|
import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen.ts";
|
||||||
|
import { MainMenuScreen } from "./gui/main_menu.ts";
|
||||||
|
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
|
||||||
|
import { ConfirmModsScreen } from "./gui/confirm_mods_screen.ts";
|
||||||
|
import { profiler } from "./profiler.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
|
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
|
||||||
|
class ClientLoop {
|
||||||
|
running = false;
|
||||||
|
last_time = 0;
|
||||||
|
client: Client | undefined;
|
||||||
|
screen: GuiScreen | undefined;
|
||||||
|
// over the screen, it gets the input while it's there
|
||||||
|
overlay: GuiScreen | undefined;
|
||||||
|
|
||||||
|
frame_count = 0;
|
||||||
|
last_fps_time = 0;
|
||||||
|
|
||||||
|
start() {
|
||||||
|
platform.on_shown(() => {
|
||||||
|
this.last_time = performance.now();
|
||||||
|
});
|
||||||
|
|
||||||
|
this.running = true;
|
||||||
|
const now = performance.now();
|
||||||
|
this.last_time = now;
|
||||||
|
this.frame_count = 0;
|
||||||
|
this.last_fps_time = this.last_time;
|
||||||
|
platform.request_frame((time) => this.loop(time));
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.running = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
show_screen(screen: GuiScreen) {
|
||||||
|
this.screen?.on_close();
|
||||||
|
this.client = undefined;
|
||||||
|
platform.confirm_leaving(false);
|
||||||
|
this.screen = screen;
|
||||||
|
InputManager.set_mouse_grabbed(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// shown over whatever screen is joining, see ConfirmModsScreen
|
||||||
|
confirm_mods(address: ServerAddress, welcome: Welcome): Promise<boolean> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
this.overlay = new ConfirmModsScreen(address, welcome, (join) => {
|
||||||
|
this.overlay = undefined;
|
||||||
|
resolve(join);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
play(connection: Connection) {
|
||||||
|
const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message)));
|
||||||
|
set_mods_client(client);
|
||||||
|
client.chat.add("Connected to the server");
|
||||||
|
this.screen?.on_close();
|
||||||
|
this.screen = undefined;
|
||||||
|
this.client = client;
|
||||||
|
platform.confirm_leaving(true);
|
||||||
|
console.log("Game started");
|
||||||
|
}
|
||||||
|
|
||||||
|
loop(time: number) {
|
||||||
|
if (!this.running || is_stopped()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const delta = (time - this.last_time) / 1000;
|
||||||
|
|
||||||
|
profiler.begin_frame();
|
||||||
|
profiler.section("begin frame", begin_drawing);
|
||||||
|
clear_background(0.69, 0.8, 1, 1.0);
|
||||||
|
if (this.client) {
|
||||||
|
this.client.run_frame(delta);
|
||||||
|
} else if (this.screen) {
|
||||||
|
(this.overlay ?? this.screen).on_tick(delta);
|
||||||
|
this.screen.on_render();
|
||||||
|
this.overlay?.on_render();
|
||||||
|
}
|
||||||
|
profiler.section("submit", end_drawing);
|
||||||
|
profiler.end_frame();
|
||||||
|
|
||||||
|
this.frame_count += 1;
|
||||||
|
const now = performance.now();
|
||||||
|
if (now - this.last_fps_time >= 1000) {
|
||||||
|
const fps = (this.frame_count * 1000) / (now - this.last_fps_time);
|
||||||
|
console.log(`FPS: ${fps.toFixed(2)}`);
|
||||||
|
this.frame_count = 0;
|
||||||
|
this.last_fps_time = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
InputManager.update();
|
||||||
|
|
||||||
|
this.last_time = time;
|
||||||
|
platform.request_frame((time) => this.loop(time));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a server's blocks, items and scripts can't be taken back out once loaded, so a failure after that point
|
||||||
|
// can't go back to the title screen to try again, the page has to start over
|
||||||
|
class FailedAfterLoadingMods extends Error {}
|
||||||
|
|
||||||
|
// the game only runs against a server, it owns the world and everything in it. see docs/modding/networking/index.md
|
||||||
|
async function join_server(
|
||||||
|
address: ServerAddress,
|
||||||
|
name: string,
|
||||||
|
status: (text: string) => void,
|
||||||
|
confirm_mods: (address: ServerAddress, welcome: Welcome) => Promise<boolean>,
|
||||||
|
): Promise<Connection> {
|
||||||
|
const { socket, welcome } = await connect(address, name);
|
||||||
|
console.log(`Connected to ${address.ws_url}`);
|
||||||
|
|
||||||
|
let loaded_mods = false;
|
||||||
|
try {
|
||||||
|
if (address.cross_origin && !is_trusted(address, welcome)) {
|
||||||
|
status("Waiting for you to accept the server's mods...");
|
||||||
|
if (!await confirm_mods(address, welcome)) {
|
||||||
|
throw new HandshakeError(`You didn't join ${address.base.host}`);
|
||||||
|
}
|
||||||
|
remember_trust(address, welcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
// textures, blocks and items all come from the server's mods, so this happens before anything else
|
||||||
|
status("Downloading the server's mods...");
|
||||||
|
const mods = await download_mods(welcome.mods, address.base);
|
||||||
|
const textures = await engine_textures();
|
||||||
|
const texture_json = new Map<string, TextureJson>();
|
||||||
|
for (const mod of mods) {
|
||||||
|
for (const [id, png] of mod.textures) textures.set(id, png);
|
||||||
|
for (const [id, json] of mod.texture_json ?? []) texture_json.set(id, json);
|
||||||
|
}
|
||||||
|
const atlas = build_atlas(textures, texture_json);
|
||||||
|
loaded_mods = true;
|
||||||
|
const atlas_texture = load_texture(atlas.image);
|
||||||
|
set_texture_animations(atlas_texture.tex, device.queue, atlas.animated);
|
||||||
|
AssetManager.instance.assets["cubi:textures"] = atlas_texture;
|
||||||
|
AssetManager.instance.assets["cubi:textures_info"] = atlas.regions;
|
||||||
|
await load_client_mods(welcome.mods, mods);
|
||||||
|
console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`);
|
||||||
|
|
||||||
|
status("Joining...");
|
||||||
|
const joined = await join(socket, new Options().render_distance);
|
||||||
|
return new Connection(socket, welcome, joined);
|
||||||
|
} catch (e) {
|
||||||
|
socket.close();
|
||||||
|
const message = error_message(e);
|
||||||
|
throw loaded_mods ? new FailedAfterLoadingMods(message) : new HandshakeError(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function error_message(e: unknown) {
|
||||||
|
if (e instanceof HandshakeError) {
|
||||||
|
return e.message;
|
||||||
|
}
|
||||||
|
if (e instanceof ModLoadError) {
|
||||||
|
return `Couldn't load the server's mods: ${e.message}`;
|
||||||
|
}
|
||||||
|
return `Something went wrong joining the server: ${e instanceof Error ? e.message : e}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the title screen (the main menu in the desktop app), and the game once it joins a server. the platform is set, the
|
||||||
|
// window was set up with init_window, and input comes in
|
||||||
|
export async function start_client() {
|
||||||
|
AssetManager.instance.load("cubi:assets_text", "/assets/ASSETS.md");
|
||||||
|
|
||||||
|
AssetManager.instance.load("cubi:skin", "/assets/sprites/skin_template.png");
|
||||||
|
AssetManager.instance.load("cubi:gui", "/assets/sprites/gui.png");
|
||||||
|
|
||||||
|
AssetManager.instance.load("cubi:m6x11", "/assets/fonts/m6x11.png");
|
||||||
|
AssetManager.instance.load("cubi:m6x11_fnt", "/assets/fonts/m6x11.fnt");
|
||||||
|
|
||||||
|
await AssetManager.instance.load_all();
|
||||||
|
|
||||||
|
init_font();
|
||||||
|
|
||||||
|
const loop = new ClientLoop();
|
||||||
|
const join_game: JoinServer = async (address, name, status) => {
|
||||||
|
let connection: Connection;
|
||||||
|
try {
|
||||||
|
connection = await join_server(
|
||||||
|
address,
|
||||||
|
name,
|
||||||
|
status,
|
||||||
|
(address, welcome) => loop.confirm_mods(address, welcome),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof FailedAfterLoadingMods) {
|
||||||
|
loop.show_screen(new DisconnectedScreen(e.message));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
loop.play(connection);
|
||||||
|
};
|
||||||
|
loop.show_screen(
|
||||||
|
in_desktop_app()
|
||||||
|
? new MainMenuScreen((screen) => loop.show_screen(screen), join_game)
|
||||||
|
: new TitleScreen(join_game),
|
||||||
|
);
|
||||||
|
loop.start();
|
||||||
|
}
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
||||||
|
|
||||||
import type { ServerAddress, Welcome } from "./handshake.ts";
|
|
||||||
|
|
||||||
// asks before running a server's mods when the page came from somewhere else, see docs/modding/concepts/security.md.
|
|
||||||
// resolves with whether the player wants to join
|
|
||||||
export function confirm_mods(address: ServerAddress, welcome: Welcome): Promise<boolean> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
const overlay = document.createElement("div");
|
|
||||||
overlay.style.cssText =
|
|
||||||
"position:fixed;inset:0;display:flex;align-items:center;justify-content:center;padding:16px;" +
|
|
||||||
"background:rgba(0,0,0,0.85);color:white;font:16px system-ui,sans-serif;";
|
|
||||||
|
|
||||||
const panel = document.createElement("div");
|
|
||||||
panel.style.cssText = "max-width:480px;display:flex;flex-direction:column;gap:12px;";
|
|
||||||
|
|
||||||
const title = document.createElement("div");
|
|
||||||
title.style.cssText = "font-size:20px;";
|
|
||||||
title.textContent = `Join ${address.base.host}?`;
|
|
||||||
|
|
||||||
const warning = document.createElement("div");
|
|
||||||
warning.style.cssText = "opacity:0.8;";
|
|
||||||
warning.textContent = "This server runs these mods in your browser. They can do anything this page can, " +
|
|
||||||
"including reading what it saved. Only join servers you trust.";
|
|
||||||
|
|
||||||
const list = document.createElement("ul");
|
|
||||||
list.style.cssText = "margin:0;padding-left:20px;";
|
|
||||||
for (const mod of welcome.mods) {
|
|
||||||
const item = document.createElement("li");
|
|
||||||
// it can change anything about the game, not just add to it
|
|
||||||
const access = mod.engine_access ? ", changes the engine" : "";
|
|
||||||
item.textContent = `${mod.name} ${mod.version} (${mod.id}${access})`;
|
|
||||||
list.append(item);
|
|
||||||
}
|
|
||||||
|
|
||||||
const buttons = document.createElement("div");
|
|
||||||
buttons.style.cssText = "display:flex;gap:8px;justify-content:flex-end;";
|
|
||||||
const button = (label: string, answer: boolean) => {
|
|
||||||
const element = document.createElement("button");
|
|
||||||
element.textContent = label;
|
|
||||||
element.style.cssText = "font:inherit;padding:6px 16px;cursor:pointer;";
|
|
||||||
element.addEventListener("click", () => {
|
|
||||||
overlay.remove();
|
|
||||||
resolve(answer);
|
|
||||||
});
|
|
||||||
return element;
|
|
||||||
};
|
|
||||||
buttons.append(button("Cancel", false), button("Join", true));
|
|
||||||
|
|
||||||
panel.append(title, warning, list, buttons);
|
|
||||||
overlay.append(panel);
|
|
||||||
document.body.append(overlay);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
+3
-3
@@ -1,9 +1,9 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { point_inside_rec } from "$/common/utils.ts";
|
import { point_inside_rec } from "@/common/utils.ts";
|
||||||
import { InputManager } from "$/client/input_manager.ts";
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
import { TextInput } from "$/client/gui/widgets.ts";
|
import { TextInput } from "@/client/gui/widgets.ts";
|
||||||
import { begin_clip, draw_rect, draw_rect_stroke, draw_text, end_clip } from "./renderer/mod.ts";
|
import { begin_clip, draw_rect, draw_rect_stroke, draw_text, end_clip } from "./renderer/mod.ts";
|
||||||
|
|
||||||
const HEADER_HEIGHT = 24;
|
const HEADER_HEIGHT = 24;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// what engine access mods get as engine.client, in client scripts. see docs/modding/misc/engine.md
|
// what engine access mods get as engine.client, in client phases. see docs/modding/misc/engine.md
|
||||||
import { Client } from "./client.ts";
|
import { Client } from "./client.ts";
|
||||||
import { Entity } from "./entity/entity.ts";
|
import { Entity } from "./entity/entity.ts";
|
||||||
import { LocalPlayer } from "./entity/local_player.ts";
|
import { LocalPlayer } from "./entity/local_player.ts";
|
||||||
|
|||||||
+28
-1
@@ -1,8 +1,16 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { physics } from "$/common/physics.ts";
|
import { physics } from "@/common/physics.ts";
|
||||||
|
import { AIR } from "@/common/constants.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import type { ClientLevel } from "../level/client_level.ts";
|
import type { ClientLevel } from "../level/client_level.ts";
|
||||||
|
import { sounds } from "../sounds.ts";
|
||||||
|
|
||||||
|
// how far it walks between steps, in blocks
|
||||||
|
const STEP_DISTANCE = 1.6;
|
||||||
|
// a block's step under the block's other sounds, which are as loud as their definitions say
|
||||||
|
const BLOCK_STEP_VOLUME = 0.15;
|
||||||
|
|
||||||
// anything that exists in the level and moves, like minecraft's Entity. position is the middle of its feet.
|
// anything that exists in the level and moves, like minecraft's Entity. position is the middle of its feet.
|
||||||
// it's simulated in fixed ticks (common/constants.ts), frames draw it between its last two positions
|
// it's simulated in fixed ticks (common/constants.ts), frames draw it between its last two positions
|
||||||
@@ -44,6 +52,9 @@ export abstract class Entity {
|
|||||||
walk_speed = 0;
|
walk_speed = 0;
|
||||||
prev_walk_speed = 0;
|
prev_walk_speed = 0;
|
||||||
|
|
||||||
|
// how far it's walked since its last step
|
||||||
|
#walked = 0;
|
||||||
|
|
||||||
// which way it hit something on each axis in the last move: 1 or -1, 0 for nothing.
|
// which way it hit something on each axis in the last move: 1 or -1, 0 for nothing.
|
||||||
// 1 on y means it's standing on something
|
// 1 on y means it's standing on something
|
||||||
colliding_x = 0;
|
colliding_x = 0;
|
||||||
@@ -80,6 +91,22 @@ export abstract class Entity {
|
|||||||
this.walk_position += this.walk_speed;
|
this.walk_position += this.walk_speed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// after moving each tick: a step every STEP_DISTANCE it walks with a block under its feet, what own gives when it
|
||||||
|
// has its own step sound (see ENTITY_SOUNDS), the block's otherwise
|
||||||
|
play_steps(own?: () => string | undefined) {
|
||||||
|
const [x, y, z] = [Math.floor(this.x), Math.floor(this.y - 0.2), Math.floor(this.z)];
|
||||||
|
const nid = this.level.get_block(x, y, z);
|
||||||
|
const below = nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
|
||||||
|
if (!below) return;
|
||||||
|
this.#walked += Math.hypot(this.x - this.prev_x, this.z - this.prev_z);
|
||||||
|
if (this.#walked < STEP_DISTANCE) return;
|
||||||
|
this.#walked %= STEP_DISTANCE;
|
||||||
|
const at = { x: this.x, y: this.y, z: this.z };
|
||||||
|
const sound = own?.();
|
||||||
|
if (sound) sounds.play(sound, { at });
|
||||||
|
else sounds.play_of(below.sounds, "step", { at, volume: BLOCK_STEP_VOLUME });
|
||||||
|
}
|
||||||
|
|
||||||
walk_animation(partial_tick: number) {
|
walk_animation(partial_tick: number) {
|
||||||
return {
|
return {
|
||||||
position: this.walk_position - this.walk_speed * (1 - partial_tick),
|
position: this.walk_position - this.walk_speed * (1 - partial_tick),
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { EntityInfo } from "$/common/protocol.ts";
|
import type { EntityInfo } from "@/common/protocol.ts";
|
||||||
import type { ClientLevel } from "../level/client_level.ts";
|
import type { ClientLevel } from "../level/client_level.ts";
|
||||||
import { Entity } from "./entity.ts";
|
import { Entity } from "./entity.ts";
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_EYE_HEIGHT, TICK_DELTA } from "$/common/constants.ts";
|
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_EYE_HEIGHT, TICK_DELTA } from "@/common/constants.ts";
|
||||||
import { physics } from "$/common/physics.ts";
|
import { physics } from "@/common/physics.ts";
|
||||||
import type { Client } from "../client.ts";
|
import type { Client } from "../client.ts";
|
||||||
import { InputManager } from "../input_manager.ts";
|
import { InputManager } from "../input_manager.ts";
|
||||||
import { ClientInventories } from "../inventory.ts";
|
import { ClientInventories } from "../inventory.ts";
|
||||||
@@ -126,6 +126,8 @@ export class LocalPlayer extends Player {
|
|||||||
sprinting = false;
|
sprinting = false;
|
||||||
// what the server says, see /fly
|
// what the server says, see /fly
|
||||||
flying = false;
|
flying = false;
|
||||||
|
// what the server says, see /creative
|
||||||
|
creative = false;
|
||||||
#fov_scale = 1;
|
#fov_scale = 1;
|
||||||
#prev_fov_scale = 1;
|
#prev_fov_scale = 1;
|
||||||
#prev_eye_height = PLAYER_EYE_HEIGHT;
|
#prev_eye_height = PLAYER_EYE_HEIGHT;
|
||||||
@@ -196,6 +198,8 @@ export class LocalPlayer extends Player {
|
|||||||
if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0;
|
if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0;
|
||||||
if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0;
|
if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0;
|
||||||
this.update_swim_animation();
|
this.update_swim_animation();
|
||||||
|
// creeping and flying are quiet
|
||||||
|
if (this.on_ground && !this.sneaking) this.play_steps();
|
||||||
this.#send_position(
|
this.#send_position(
|
||||||
(this.on_ground && !was_on_ground) || this.swimming !== was_swimming ||
|
(this.on_ground && !was_on_ground) || this.swimming !== was_swimming ||
|
||||||
this.holding_sneak !== was_holding_sneak,
|
this.holding_sneak !== was_holding_sneak,
|
||||||
|
|||||||
+5
-12
@@ -1,8 +1,8 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
|
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT, PLAYER_WIDTH } from "@/common/constants.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { ClientLevel } from "../level/client_level.ts";
|
import type { ClientLevel } from "../level/client_level.ts";
|
||||||
import type { Texture } from "../renderer/mod.ts";
|
import type { Texture } from "../renderer/mod.ts";
|
||||||
import { decode_skin } from "../skins.ts";
|
import { decode_skin } from "../skins.ts";
|
||||||
@@ -36,7 +36,6 @@ export abstract class Player extends Entity {
|
|||||||
// which way the body lies while swimming, radians up from flat: the way they're going, or looking when still
|
// which way the body lies while swimming, radians up from flat: the way they're going, or looking when still
|
||||||
swim_pitch = 0;
|
swim_pitch = 0;
|
||||||
prev_swim_pitch = 0;
|
prev_swim_pitch = 0;
|
||||||
#skin_version = 0;
|
|
||||||
|
|
||||||
constructor(level: ClientLevel, id: string, name: string) {
|
constructor(level: ClientLevel, id: string, name: string) {
|
||||||
super(level, id, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_EYE_HEIGHT);
|
super(level, id, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_EYE_HEIGHT);
|
||||||
@@ -72,15 +71,9 @@ export abstract class Player extends Entity {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// a base64 png from the server, or undefined for the default. the old skin stays until the new one is decoded
|
// a base64 png from the server, or undefined for the default
|
||||||
async set_skin(skin: string | undefined, slim = false) {
|
set_skin(skin: string | undefined, slim = false) {
|
||||||
const version = ++this.#skin_version;
|
const texture = skin ? decode_skin(skin) : undefined;
|
||||||
const texture = skin ? await decode_skin(skin) : undefined;
|
|
||||||
if (version !== this.#skin_version) {
|
|
||||||
// a newer skin came while this one was decoding
|
|
||||||
texture?.tex.destroy();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.skin?.tex.destroy();
|
this.skin?.tex.destroy();
|
||||||
this.skin = texture;
|
this.skin = texture;
|
||||||
this.slim = slim;
|
this.slim = slim;
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { EntityData, EntityEvent, EntityInfo } from "$/common/protocol.ts";
|
import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts";
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
import { type EntityJson, sound_of } from "@/common/mod_data.ts";
|
||||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import { wrap_angle } from "$/common/utils.ts";
|
import { wrap_angle } from "@/common/utils.ts";
|
||||||
|
import { animation_for, type EntityAnimation } from "../rendering/entity_animators.ts";
|
||||||
import type { ClientLevel } from "../level/client_level.ts";
|
import type { ClientLevel } from "../level/client_level.ts";
|
||||||
import { Entity } from "./entity.ts";
|
import { Entity } from "./entity.ts";
|
||||||
|
import { sounds } from "../sounds.ts";
|
||||||
|
|
||||||
// how many ticks a server position takes to reach, like minecraft's lerpTo
|
// how many ticks a server position takes to reach, like minecraft's lerpTo
|
||||||
const LERP_TICKS = 3;
|
const LERP_TICKS = 3;
|
||||||
@@ -15,14 +17,20 @@ const HURT_TICKS = 10;
|
|||||||
const DEATH_TICKS = 20;
|
const DEATH_TICKS = 20;
|
||||||
// how long its attack swing takes, like minecraft's mobs
|
// how long its attack swing takes, like minecraft's mobs
|
||||||
const SWING_TICKS = 6;
|
const SWING_TICKS = 6;
|
||||||
|
// how long it goes between its ambient sounds, picked at random each time
|
||||||
|
const AMBIENT_TICKS = [80, 240];
|
||||||
|
|
||||||
// an entity the server simulates, like a mob. this only follows where it's told it is and keeps what it was told
|
// an entity the server simulates, like a mob. this only follows where it's told it is and keeps what it was told
|
||||||
// it looks like, for drawing it
|
// it looks like, for drawing it
|
||||||
export class RemoteEntity extends Entity {
|
export class RemoteEntity extends Entity {
|
||||||
// the entity type, like "cubi:item"
|
// the entity type, like "cubi:item"
|
||||||
readonly type: string;
|
readonly type: string;
|
||||||
// synced data, see EntityData
|
// synced data, see EntityData. set_data changes it
|
||||||
data: EntityData;
|
data: EntityData;
|
||||||
|
// ticks since this client got it
|
||||||
|
age = 0;
|
||||||
|
// its type's animator from a mod, see ClientRender.register_entity_animator
|
||||||
|
readonly animation: EntityAnimation | undefined;
|
||||||
head_yaw: number;
|
head_yaw: number;
|
||||||
// counting down after a hurt event, and up after a death one
|
// counting down after a hurt event, and up after a death one
|
||||||
hurt_time = 0;
|
hurt_time = 0;
|
||||||
@@ -35,6 +43,10 @@ export class RemoteEntity extends Entity {
|
|||||||
|
|
||||||
#target = { x: 0, y: 0, z: 0, yaw: 0, pitch: 0, head_yaw: 0 };
|
#target = { x: 0, y: 0, z: 0, yaw: 0, pitch: 0, head_yaw: 0 };
|
||||||
#lerp_ticks = 0;
|
#lerp_ticks = 0;
|
||||||
|
// what its sounds' ids start with, see ENTITY_SOUNDS
|
||||||
|
#sounds: string | undefined;
|
||||||
|
// until its next ambient sound
|
||||||
|
#ambient_ticks = random_ambient_ticks();
|
||||||
|
|
||||||
constructor(level: ClientLevel, info: Extract<EntityInfo, { kind: "entity" }>) {
|
constructor(level: ClientLevel, info: Extract<EntityInfo, { kind: "entity" }>) {
|
||||||
// the size of mods' entities, player sized for kinds the client doesn't know
|
// the size of mods' entities, player sized for kinds the client doesn't know
|
||||||
@@ -42,11 +54,19 @@ export class RemoteEntity extends Entity {
|
|||||||
super(level, info.id, json?.width ?? 0.6, json?.height ?? 1.8, json ? json.height * 0.85 : 1.62);
|
super(level, info.id, json?.width ?? 0.6, json?.height ?? 1.8, json ? json.height * 0.85 : 1.62);
|
||||||
this.type = info.type;
|
this.type = info.type;
|
||||||
this.data = info.data;
|
this.data = info.data;
|
||||||
|
this.#sounds = json?.sounds;
|
||||||
this.set_position(info.x, info.y, info.z);
|
this.set_position(info.x, info.y, info.z);
|
||||||
this.yaw = info.yaw;
|
this.yaw = info.yaw;
|
||||||
this.pitch = info.pitch;
|
this.pitch = info.pitch;
|
||||||
this.head_yaw = info.head_yaw ?? info.yaw;
|
this.head_yaw = info.head_yaw ?? info.yaw;
|
||||||
this.#target = { x: info.x, y: info.y, z: info.z, yaw: info.yaw, pitch: info.pitch, head_yaw: this.head_yaw };
|
this.#target = { x: info.x, y: info.y, z: info.z, yaw: info.yaw, pitch: info.pitch, head_yaw: this.head_yaw };
|
||||||
|
this.animation = animation_for(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
set_data(data: EntityData) {
|
||||||
|
const before = this.data;
|
||||||
|
this.data = data;
|
||||||
|
this.animation?.data_changed(before);
|
||||||
}
|
}
|
||||||
|
|
||||||
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number, head_yaw = yaw) {
|
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number, head_yaw = yaw) {
|
||||||
@@ -57,15 +77,19 @@ export class RemoteEntity extends Entity {
|
|||||||
on_event(event: EntityEvent) {
|
on_event(event: EntityEvent) {
|
||||||
if (event === "hurt") {
|
if (event === "hurt") {
|
||||||
this.hurt_time = HURT_TICKS;
|
this.hurt_time = HURT_TICKS;
|
||||||
|
sounds.play_of(this.#sounds, "hurt", { follow: this.id });
|
||||||
} else if (event === "swing") {
|
} else if (event === "swing") {
|
||||||
// swinging again halfway through doesn't restart it, like minecraft
|
// swinging again halfway through doesn't restart it, like minecraft
|
||||||
if (this.swing_ticks === undefined || this.swing_ticks >= SWING_TICKS / 2) this.swing_ticks = 0;
|
if (this.swing_ticks === undefined || this.swing_ticks >= SWING_TICKS / 2) this.swing_ticks = 0;
|
||||||
} else {
|
} else {
|
||||||
this.dead = true;
|
this.dead = true;
|
||||||
|
// where it died, it's gone soon after
|
||||||
|
sounds.play_of(this.#sounds, "death", { at: { x: this.x, y: this.y, z: this.z } });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tick() {
|
tick() {
|
||||||
|
this.age += 1;
|
||||||
if (this.hurt_time > 0) this.hurt_time -= 1;
|
if (this.hurt_time > 0) this.hurt_time -= 1;
|
||||||
if (this.dead) this.death_time = Math.min(DEATH_TICKS, this.death_time + 1);
|
if (this.dead) this.death_time = Math.min(DEATH_TICKS, this.death_time + 1);
|
||||||
|
|
||||||
@@ -82,6 +106,16 @@ export class RemoteEntity extends Entity {
|
|||||||
}
|
}
|
||||||
this.update_walk_animation();
|
this.update_walk_animation();
|
||||||
if (this.swing_ticks !== undefined && ++this.swing_ticks >= SWING_TICKS) this.swing_ticks = undefined;
|
if (this.swing_ticks !== undefined && ++this.swing_ticks >= SWING_TICKS) this.swing_ticks = undefined;
|
||||||
|
if (!this.dead) {
|
||||||
|
this.play_steps(() => {
|
||||||
|
const own = sound_of(this.#sounds, "step");
|
||||||
|
return this.animation ? this.animation.step_sound(own) : own;
|
||||||
|
});
|
||||||
|
if (--this.#ambient_ticks <= 0) {
|
||||||
|
this.#ambient_ticks = random_ambient_ticks();
|
||||||
|
sounds.play_of(this.#sounds, "ambient", { follow: this.id });
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// how far through its attack swing it is, 0 to 1, like minecraft's attackTime. 0 when it isn't swinging
|
// how far through its attack swing it is, 0 to 1, like minecraft's attackTime. 0 when it isn't swinging
|
||||||
@@ -89,3 +123,8 @@ export class RemoteEntity extends Entity {
|
|||||||
return this.swing_ticks === undefined ? 0 : Math.min(1, (this.swing_ticks + partial_tick) / SWING_TICKS);
|
return this.swing_ticks === undefined ? 0 : Math.min(1, (this.swing_ticks + partial_tick) / SWING_TICKS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function random_ambient_ticks() {
|
||||||
|
const [low, high] = AMBIENT_TICKS;
|
||||||
|
return low + Math.floor(Math.random() * (high - low));
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { EntityEvent, PlayerInfo } from "$/common/protocol.ts";
|
import type { EntityEvent, PlayerInfo } from "@/common/protocol.ts";
|
||||||
import { TICK_DELTA } from "$/common/constants.ts";
|
import { TICK_DELTA } from "@/common/constants.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { ClientLevel } from "../level/client_level.ts";
|
import type { ClientLevel } from "../level/client_level.ts";
|
||||||
import { Player } from "./player.ts";
|
import { Player } from "./player.ts";
|
||||||
|
|
||||||
@@ -58,5 +58,6 @@ export class RemotePlayer extends Player {
|
|||||||
this.z += (this.target_z - this.z) * t;
|
this.z += (this.target_z - this.z) * t;
|
||||||
this.update_walk_animation();
|
this.update_walk_animation();
|
||||||
this.update_swim_animation();
|
this.update_swim_animation();
|
||||||
|
this.play_steps();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-13
@@ -1,6 +1,8 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
let stopped = false;
|
let stopped = false;
|
||||||
|
|
||||||
// replaces the game with a message, for when it can't go on (no server, lost connection)
|
// replaces the game with a message, for when it can't go on (no server, lost connection)
|
||||||
@@ -9,19 +11,7 @@ export function show_fatal_error(message: string) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
stopped = true;
|
stopped = true;
|
||||||
document.exitPointerLock?.();
|
platform.show_fatal_error(message);
|
||||||
|
|
||||||
const overlay = document.createElement("div");
|
|
||||||
overlay.style.cssText =
|
|
||||||
"position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;" +
|
|
||||||
"gap:12px;background:rgba(0,0,0,0.85);color:white;font:20px system-ui,sans-serif;text-align:center;";
|
|
||||||
const text = document.createElement("div");
|
|
||||||
text.textContent = message;
|
|
||||||
const hint = document.createElement("div");
|
|
||||||
hint.textContent = "Reload the page to try again.";
|
|
||||||
hint.style.cssText = "font-size:14px;opacity:0.7;";
|
|
||||||
overlay.append(text, hint);
|
|
||||||
document.body.append(overlay);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function is_stopped() {
|
export function is_stopped() {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// the fluids' rules from the mods' shared scripts on this client, the same as the server's (see common/fluids.ts), for
|
// the fluids' rules from the mods' shared phases on this client, the same as the server's (see common/fluids.ts), for
|
||||||
// drawing fluids and naming them in tooltips. its own module so those don't import client/mods.ts, which loads the mods
|
// drawing fluids and naming them in tooltips. its own module so those don't import client/mods.ts, which loads the mods
|
||||||
// and makes it again for each server's
|
// and makes it again for each server's
|
||||||
import { FluidRules } from "$/common/fluids.ts";
|
import { FluidRules } from "@/common/fluids.ts";
|
||||||
|
|
||||||
export let fluid_rules = new FluidRules(() => undefined);
|
export let fluid_rules = new FluidRules(() => undefined);
|
||||||
|
|
||||||
|
|||||||
+50
-10
@@ -1,19 +1,28 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { AIR, FACE_OFFSETS, TICK_DELTA } from "$/common/constants.ts";
|
import { AIR, FACE_OFFSETS, TICK_DELTA } from "@/common/constants.ts";
|
||||||
import type { Client } from "./client.ts";
|
import type { Client } from "./client.ts";
|
||||||
import type { BlockHitResult } from "./level/client_level.ts";
|
import type { BlockHitResult } from "./level/client_level.ts";
|
||||||
import type { Container } from "$/common/inventory.ts";
|
import type { Container } from "@/common/inventory.ts";
|
||||||
import { AIR_ID } from "$/common/protocol.ts";
|
import { AIR_ID } from "@/common/protocol.ts";
|
||||||
import { box_overlaps_block, can_place, fluid_block, placement_target, waterlog_placement } from "$/common/utils.ts";
|
import { box_overlaps_block, can_place, fluid_block, placement_target, waterlog_placement } from "@/common/utils.ts";
|
||||||
import { block_rules, predict_neighbors } from "./mods.ts";
|
import { block_rules, predict_neighbors } from "./mods.ts";
|
||||||
import { collision_shape_at } from "$/common/block_shapes.ts";
|
import { collision_shape_at } from "@/common/block_shapes.ts";
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
import type { EntityJson } from "@/common/mod_data.ts";
|
||||||
import { RemoteEntity } from "./entity/remote_entity.ts";
|
import { RemoteEntity } from "./entity/remote_entity.ts";
|
||||||
import { Player } from "./entity/player.ts";
|
import { Player } from "./entity/player.ts";
|
||||||
import type { Entity } from "./entity/entity.ts";
|
import type { Entity } from "./entity/entity.ts";
|
||||||
|
import { sounds } from "./sounds.ts";
|
||||||
|
|
||||||
|
const CREATIVE_DESTROY_DELAY = 2;
|
||||||
|
// a block being broken makes its hit sound every this many ticks, under its other sounds
|
||||||
|
const HIT_SOUND_TICKS = 4;
|
||||||
|
const HIT_VOLUME = 0.25;
|
||||||
|
|
||||||
|
// the middle of the block at x y z, where its sounds come from
|
||||||
|
const middle = ({ x, y, z }: { x: number; y: number; z: number }) => ({ x: x + 0.5, y: y + 0.5, z: z + 0.5 });
|
||||||
|
|
||||||
// breaking and using blocks against a server, like minecraft's MultiPlayerGameMode. the client times breaking
|
// breaking and using blocks against a server, like minecraft's MultiPlayerGameMode. the client times breaking
|
||||||
// and guesses the results so they feel instant, the server decides what really happens
|
// and guesses the results so they feel instant, the server decides what really happens
|
||||||
@@ -24,6 +33,11 @@ export class MultiPlayerGameMode {
|
|||||||
destroy_pos: { x: number; y: number; z: number } | undefined;
|
destroy_pos: { x: number; y: number; z: number } | undefined;
|
||||||
destroy_progress = 0;
|
destroy_progress = 0;
|
||||||
destroy_time = 0;
|
destroy_time = 0;
|
||||||
|
// ticks spent breaking it, for its hit sound
|
||||||
|
#hit_ticks = 0;
|
||||||
|
// ticks left before creative can break another block while the button is held, so holding it doesn't clear a
|
||||||
|
// line of blocks every tick
|
||||||
|
destroy_delay = 0;
|
||||||
|
|
||||||
constructor(client: Client) {
|
constructor(client: Client) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
@@ -36,6 +50,10 @@ export class MultiPlayerGameMode {
|
|||||||
|
|
||||||
// called every tick the attack button is held on a block
|
// called every tick the attack button is held on a block
|
||||||
continue_destroy_block(hit: BlockHitResult) {
|
continue_destroy_block(hit: BlockHitResult) {
|
||||||
|
if (this.destroy_delay > 0) {
|
||||||
|
this.destroy_delay--;
|
||||||
|
return;
|
||||||
|
}
|
||||||
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
|
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
|
||||||
const tool = this.held_item()?.tool;
|
const tool = this.held_item()?.tool;
|
||||||
|
|
||||||
@@ -43,24 +61,34 @@ export class MultiPlayerGameMode {
|
|||||||
const pos = this.destroy_pos;
|
const pos = this.destroy_pos;
|
||||||
if (!pos || pos.x !== hit.x || pos.y !== hit.y || pos.z !== hit.z) {
|
if (!pos || pos.x !== hit.x || pos.y !== hit.y || pos.z !== hit.z) {
|
||||||
this.destroy_progress = 0;
|
this.destroy_progress = 0;
|
||||||
|
this.#hit_ticks = 0;
|
||||||
|
}
|
||||||
|
if (this.#hit_ticks++ % HIT_SOUND_TICKS === 0) {
|
||||||
|
sounds.play_of(block_info.sounds, "hit", { at: middle(hit), volume: HIT_VOLUME });
|
||||||
}
|
}
|
||||||
this.destroy_pos = { x: hit.x, y: hit.y, z: hit.z };
|
this.destroy_pos = { x: hit.x, y: hit.y, z: hit.z };
|
||||||
this.destroy_time = block_info.toughness ?? 9999;
|
// blocks without a toughness, like water, can only be broken in creative
|
||||||
|
this.destroy_time = this.client.player.creative ? 0 : block_info.toughness ?? 9999;
|
||||||
this.destroy_progress += TICK_DELTA * (tool && tool.type === block_info.tool_to_break ? tool.speed : 1);
|
this.destroy_progress += TICK_DELTA * (tool && tool.type === block_info.tool_to_break ? tool.speed : 1);
|
||||||
|
|
||||||
if (this.destroy_progress >= this.destroy_time) {
|
if (this.destroy_progress >= this.destroy_time) {
|
||||||
// show it right away, the server decides drops and corrects us if it disagrees
|
// show it right away, the server decides drops and corrects us if it disagrees
|
||||||
this.#predict((seq) => {
|
this.#predict((seq) => {
|
||||||
|
// the server sends it to everyone else, see GameServer.destroy_block
|
||||||
|
sounds.play_of(block_info.sounds, "break", { at: middle(hit) });
|
||||||
this.client.level.break_block(hit.x, hit.y, hit.z);
|
this.client.level.break_block(hit.x, hit.y, hit.z);
|
||||||
predict_neighbors(hit.x, hit.y, hit.z);
|
predict_neighbors(hit.x, hit.y, hit.z);
|
||||||
this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z, seq });
|
this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z, seq });
|
||||||
});
|
});
|
||||||
this.destroy_progress = 0;
|
this.destroy_progress = 0;
|
||||||
this.destroy_time = 0;
|
this.destroy_time = 0;
|
||||||
|
if (this.client.player.creative) this.destroy_delay = CREATIVE_DESTROY_DELAY;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// letting go also ends the delay, so clicking again breaks right away
|
||||||
stop_destroy_block() {
|
stop_destroy_block() {
|
||||||
|
this.destroy_delay = 0;
|
||||||
this.destroy_pos = undefined;
|
this.destroy_pos = undefined;
|
||||||
this.destroy_progress = 0;
|
this.destroy_progress = 0;
|
||||||
this.destroy_time = 0;
|
this.destroy_time = 0;
|
||||||
@@ -132,12 +160,16 @@ export class MultiPlayerGameMode {
|
|||||||
below_id,
|
below_id,
|
||||||
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, place_value!));
|
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, place_value!));
|
||||||
if ((!block_info.interactive || skips_block) && place_id && placeable) {
|
if ((!block_info.interactive || skips_block) && place_id && placeable) {
|
||||||
|
// the server sends it to everyone else, see GameServer.#use_block
|
||||||
|
sounds.play_of(place_block!.sounds, "place", { at: middle(target) });
|
||||||
level.add_block({ ...target, id: place_id }, place_value! >>> 16);
|
level.add_block({ ...target, id: place_id }, place_value! >>> 16);
|
||||||
predict_neighbors(target.x, target.y, target.z);
|
predict_neighbors(target.x, target.y, target.z);
|
||||||
|
if (!this.client.player.creative) {
|
||||||
const slot = this.#held_slot();
|
const slot = this.#held_slot();
|
||||||
slot.amount = slot.amount! - 1;
|
slot.amount = slot.amount! - 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// q on a slot: throws one, or the whole stack. the server spawns the item, this only takes it out right away
|
// q on a slot: throws one, or the whole stack. the server spawns the item, this only takes it out right away
|
||||||
// q on a menu's slot, whose item is in container at index on this client
|
// q on a menu's slot, whose item is in container at index on this client
|
||||||
@@ -164,20 +196,28 @@ export class MultiPlayerGameMode {
|
|||||||
this.client.player.last_attack = performance.now();
|
this.client.player.last_attack = performance.now();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// right click on an entity or another player, for mods' entity_interact. the server uses the held item when none
|
||||||
|
// of them stops it
|
||||||
|
interact(entity: Entity) {
|
||||||
|
this.client.player.send_position_now();
|
||||||
|
this.client.connection.send({ type: "interact_entity", id: entity.id });
|
||||||
|
}
|
||||||
|
|
||||||
// right click on nothing
|
// right click on nothing
|
||||||
use_item() {
|
use_item() {
|
||||||
this.client.connection.send({ type: "use_item" });
|
this.client.connection.send({ type: "use_item" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// whether a mob's or player's collision box overlaps the block, the server doesn't let solid blocks go there. mobs
|
// whether a mob's or player's collision box overlaps the block, the server doesn't let solid blocks go there. mobs
|
||||||
// are the mod entities that aren't scripted, players are this one and the others
|
// are the mod entities that aren't scripted or objects, players are this one and the others
|
||||||
#occupied(x: number, y: number, z: number, block: BlockRegistry, value: number) {
|
#occupied(x: number, y: number, z: number, block: BlockRegistry, value: number) {
|
||||||
const shape = collision_shape_at(block, value);
|
const shape = collision_shape_at(block, value);
|
||||||
for (const entity of this.client.level.entities.values()) {
|
for (const entity of this.client.level.entities.values()) {
|
||||||
const json = entity instanceof RemoteEntity
|
const json = entity instanceof RemoteEntity
|
||||||
? EverythingRegistry.get<EntityJson>("entities", entity.type)
|
? EverythingRegistry.get<EntityJson>("entities", entity.type)
|
||||||
: undefined;
|
: undefined;
|
||||||
const blocks = entity instanceof Player || (json !== undefined && json.behavior !== "scripted");
|
const blocks = entity instanceof Player ||
|
||||||
|
(json !== undefined && json.behavior !== "scripted" && json.behavior !== "object");
|
||||||
if (blocks && box_overlaps_block(entity, x, y, z, shape)) return true;
|
if (blocks && box_overlaps_block(entity, x, y, z, shape)) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { canvas, draw_rect, draw_text } from "$/client/renderer/mod.ts";
|
import { canvas, draw_rect, draw_text } from "@/client/renderer/mod.ts";
|
||||||
|
|
||||||
const LINE_HEIGHT = 24;
|
const LINE_HEIGHT = 24;
|
||||||
const VISIBLE_SECONDS = 10;
|
const VISIBLE_SECONDS = 10;
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
|
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||||
|
import type { ServerAddress, Welcome } from "@/client/handshake.ts";
|
||||||
|
import { GuiScreen } from "./gui_screen.ts";
|
||||||
|
import { Button, LIST_ROW_HEIGHT, ListBox, TEXT_HEIGHT, TEXT_SCALE, wrap_text } from "./widgets.ts";
|
||||||
|
|
||||||
|
const MAX_WIDTH = 720;
|
||||||
|
const MARGIN = 32;
|
||||||
|
const GAP = 20;
|
||||||
|
const BUTTON_HEIGHT = 48;
|
||||||
|
const TITLE_SCALE = 4;
|
||||||
|
const LINE_HEIGHT = TEXT_HEIGHT * TEXT_SCALE + 6;
|
||||||
|
const WARNING = "This server runs these mods in the game. They can do anything the game can, including reading what " +
|
||||||
|
"it saved. Only join servers you trust.";
|
||||||
|
|
||||||
|
// asks before running the mods of a server that isn't the page's own, see docs/modding/concepts/security.md. it's
|
||||||
|
// shown over the screen that's joining, and answer gets whether the player wants to join
|
||||||
|
export class ConfirmModsScreen extends GuiScreen {
|
||||||
|
#title: string;
|
||||||
|
#warning: string[] = [];
|
||||||
|
// what the warning was wrapped for
|
||||||
|
#wrapped_width = 0;
|
||||||
|
#list = new ListBox(0, 0, () => {});
|
||||||
|
#cancel: Button;
|
||||||
|
#join: Button;
|
||||||
|
|
||||||
|
constructor(address: ServerAddress, welcome: Welcome, answer: (join: boolean) => void) {
|
||||||
|
super();
|
||||||
|
this.#title = `Join ${address.base.host}?`;
|
||||||
|
this.#list.rows = welcome.mods.map((mod) => {
|
||||||
|
// it can change anything about the game, not just add to it
|
||||||
|
const access = mod.engine_access ? ", changes the engine" : "";
|
||||||
|
return { text: `${mod.name} ${mod.version} (${mod.id}${access})` };
|
||||||
|
});
|
||||||
|
this.#cancel = new Button("Cancel", 0, BUTTON_HEIGHT, () => answer(false));
|
||||||
|
this.#join = new Button("Join", 0, BUTTON_HEIGHT, () => answer(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
on_tick(_delta: number): void {
|
||||||
|
const width = Math.min(MAX_WIDTH, canvas.width - MARGIN * 2);
|
||||||
|
if (width !== this.#wrapped_width) {
|
||||||
|
this.#wrapped_width = width;
|
||||||
|
this.#warning = wrap_text(WARNING, width);
|
||||||
|
}
|
||||||
|
// the list gets what room the title, the warning and the buttons leave
|
||||||
|
const above = this.#warning_y + this.#warning.length * LINE_HEIGHT + GAP;
|
||||||
|
const room = canvas.height - MARGIN * 2 - above - GAP - BUTTON_HEIGHT;
|
||||||
|
const list = this.#list;
|
||||||
|
list.width = width;
|
||||||
|
list.height = Math.max(LIST_ROW_HEIGHT, Math.min(list.rows.length * LIST_ROW_HEIGHT, room));
|
||||||
|
this.x = (canvas.width - width) / 2;
|
||||||
|
this.y = Math.max(MARGIN, (canvas.height - above - list.height - GAP - BUTTON_HEIGHT) / 2);
|
||||||
|
list.x = this.x;
|
||||||
|
list.y = this.y + above;
|
||||||
|
const half = (width - GAP) / 2;
|
||||||
|
for (const [i, button] of [this.#cancel, this.#join].entries()) {
|
||||||
|
button.width = half;
|
||||||
|
button.x = this.x + i * (half + GAP);
|
||||||
|
button.y = list.y + list.height + GAP;
|
||||||
|
}
|
||||||
|
|
||||||
|
// only a click joins, never a key pressed for something else, like the enter that joined the server
|
||||||
|
if (InputManager.is_key_pressed("Escape")) return this.#cancel.on_press();
|
||||||
|
list.handle_input();
|
||||||
|
this.#cancel.handle_input();
|
||||||
|
this.#join.handle_input();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_render(): void {
|
||||||
|
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.85]);
|
||||||
|
draw_text(this.#title, (canvas.width - measure_text(this.#title, TITLE_SCALE)) / 2, this.y, TITLE_SCALE);
|
||||||
|
for (const [i, line] of this.#warning.entries()) {
|
||||||
|
draw_text(line, this.x, this.y + this.#warning_y + i * LINE_HEIGHT, TEXT_SCALE, [0.85, 0.85, 0.85, 1]);
|
||||||
|
}
|
||||||
|
this.#list.render();
|
||||||
|
this.#cancel.render();
|
||||||
|
this.#join.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_close(): void {}
|
||||||
|
|
||||||
|
// below the title, from the screen's top
|
||||||
|
get #warning_y() {
|
||||||
|
return TEXT_HEIGHT * TITLE_SCALE + GAP;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,9 +2,9 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { Marked } from "marked";
|
import { Marked } from "marked";
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import { mod_credits } from "$/client/mods.ts";
|
import { mod_credits } from "@/client/mods.ts";
|
||||||
import { canvas, draw_rect } from "$/client/renderer/mod.ts";
|
import { canvas, draw_rect } from "@/client/renderer/mod.ts";
|
||||||
import { GuiScreen } from "./gui_screen.ts";
|
import { GuiScreen } from "./gui_screen.ts";
|
||||||
|
|
||||||
// credits come from servers' mods, so markdown only: raw html is shown as text and links can't run code
|
// credits come from servers' mods, so markdown only: raw html is shown as text and links can't run code
|
||||||
@@ -55,7 +55,7 @@ export class CreditsScreen extends GuiScreen {
|
|||||||
|
|
||||||
const content = document.createElement("div");
|
const content = document.createElement("div");
|
||||||
content.style.cssText = "overflow-y:auto;flex:1;min-height:0;padding-right:8px;";
|
content.style.cssText = "overflow-y:auto;flex:1;min-height:0;padding-right:8px;";
|
||||||
content.innerHTML = this.#sections().map(({ heading, text }) =>
|
content.innerHTML = credit_sections().map(({ heading, text }) =>
|
||||||
`<section><h2 style="border-bottom:1px solid #374151;padding-bottom:4px">${escape_html(heading)}</h2>` +
|
`<section><h2 style="border-bottom:1px solid #374151;padding-bottom:4px">${escape_html(heading)}</h2>` +
|
||||||
`${markdown.parse(text, { async: false })}</section>`
|
`${markdown.parse(text, { async: false })}</section>`
|
||||||
).join("");
|
).join("");
|
||||||
@@ -72,14 +72,6 @@ export class CreditsScreen extends GuiScreen {
|
|||||||
document.body.append(this.#overlay);
|
document.body.append(this.#overlay);
|
||||||
}
|
}
|
||||||
|
|
||||||
#sections() {
|
|
||||||
const sections = [{ heading: "bworld", text: AssetManager.instance.get<string>("bworld:assets_text") ?? "" }];
|
|
||||||
for (const mod of mod_credits) {
|
|
||||||
sections.push({ heading: `${mod.name} ${mod.version}`, text: mod.text });
|
|
||||||
}
|
|
||||||
return sections;
|
|
||||||
}
|
|
||||||
|
|
||||||
on_tick(_delta: number): void {}
|
on_tick(_delta: number): void {}
|
||||||
|
|
||||||
on_render(): void {
|
on_render(): void {
|
||||||
@@ -91,6 +83,15 @@ export class CreditsScreen extends GuiScreen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the engine's assets/ASSETS.md, then each loaded mod's credits file, as markdown
|
||||||
|
export function credit_sections(): { heading: string; text: string }[] {
|
||||||
|
const sections = [{ heading: "cubi", text: AssetManager.instance.get<string>("cubi:assets_text") ?? "" }];
|
||||||
|
for (const mod of mod_credits) {
|
||||||
|
sections.push({ heading: `${mod.name} ${mod.version}`, text: mod.text });
|
||||||
|
}
|
||||||
|
return sections;
|
||||||
|
}
|
||||||
|
|
||||||
function escape_html(text: string) {
|
function escape_html(text: string) {
|
||||||
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-29
@@ -1,15 +1,16 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { Client } from "$/client/client.ts";
|
import type { Client } from "@/client/client.ts";
|
||||||
import { DebugUI } from "$/client/debug_ui.ts";
|
import { DebugUI } from "@/client/debug_ui.ts";
|
||||||
import { format_clock } from "$/common/time.ts";
|
import { format_clock } from "@/common/time.ts";
|
||||||
import { profiler, type SectionStats } from "$/client/profiler.ts";
|
import { profiler, type SectionStats } from "@/client/profiler.ts";
|
||||||
import { canvas, gpu_timer, render_debug, render_stats } from "$/client/renderer/mod.ts";
|
import { canvas, gpu_timer, render_debug, render_stats } from "@/client/renderer/mod.ts";
|
||||||
import { RENDER_LAYERS } from "$/common/everything_registry.ts";
|
import { RENDER_LAYERS } from "@/common/everything_registry.ts";
|
||||||
import { atlas_png } from "$/client/atlas.ts";
|
import { atlas_png } from "@/client/atlas.ts";
|
||||||
import { RenderBenchmark } from "$/client/benchmark/benchmark.ts";
|
import { RenderBenchmark } from "@/client/benchmark/benchmark.ts";
|
||||||
import { format_report } from "$/client/benchmark/report.ts";
|
import { format_report } from "@/client/benchmark/report.ts";
|
||||||
|
import { platform } from "@/client/platform.ts";
|
||||||
|
|
||||||
// how often the totals that go through every chunk are worked out again, so the overlay doesn't slow the frames it's
|
// how often the totals that go through every chunk are worked out again, so the overlay doesn't slow the frames it's
|
||||||
// measuring
|
// measuring
|
||||||
@@ -98,8 +99,9 @@ export class DebugOverlay {
|
|||||||
const level = client.level;
|
const level = client.level;
|
||||||
const level_renderer = client.game_renderer.level_renderer;
|
const level_renderer = client.game_renderer.level_renderer;
|
||||||
const { meshed, bytes } = this.#count_chunks(client);
|
const { meshed, bytes } = this.#count_chunks(client);
|
||||||
text(`chunks: ${level.chunks.size} loaded, ${meshed} meshed, ${level_renderer.visible_chunks} in view`);
|
text(`chunks: ${level.chunks.size} loaded`);
|
||||||
text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} meshing`);
|
text(` sections: ${meshed} with meshes, ${level_renderer.visible_sections} in view`);
|
||||||
|
text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} requests meshing`);
|
||||||
text(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`);
|
text(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`);
|
||||||
text(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`);
|
text(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`);
|
||||||
separator();
|
separator();
|
||||||
@@ -112,7 +114,7 @@ export class DebugOverlay {
|
|||||||
if (copy) {
|
if (copy) {
|
||||||
const switches = { ...render_debug, ...level_renderer.draw };
|
const switches = { ...render_debug, ...level_renderer.draw };
|
||||||
lines.push(Object.entries(switches).map(([key, on]) => ` ${key}: ${on}`).join("\n"));
|
lines.push(Object.entries(switches).map(([key, on]) => ` ${key}: ${on}`).join("\n"));
|
||||||
copy_text(lines.join("\n")).catch(() => {});
|
platform.write_clipboard(lines.join("\n")).catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,13 +138,13 @@ export class DebugOverlay {
|
|||||||
|
|
||||||
// right after the benchmark, firefox and safari only let the page copy from a click
|
// right after the benchmark, firefox and safari only let the page copy from a click
|
||||||
#copy_benchmark() {
|
#copy_benchmark() {
|
||||||
copy_text(this.#benchmark_report!).then(
|
platform.write_clipboard(this.#benchmark_report!).then(
|
||||||
() => this.#benchmark_status = "The benchmark's results are on the clipboard",
|
() => this.#benchmark_status = "The benchmark's results are on the clipboard",
|
||||||
() => this.#benchmark_status = "Click above to copy the benchmark's results",
|
() => this.#benchmark_status = "Click above to copy the benchmark's results",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// meshed chunks and what their meshes take on the gpu, once a second
|
// sections with meshes and what their meshes take on the gpu, once a second
|
||||||
#count_chunks(client: Client) {
|
#count_chunks(client: Client) {
|
||||||
const now = performance.now();
|
const now = performance.now();
|
||||||
if (now - this.#chunk_stats_time < CHUNK_STATS_MS) return this.#chunk_stats;
|
if (now - this.#chunk_stats_time < CHUNK_STATS_MS) return this.#chunk_stats;
|
||||||
@@ -150,9 +152,15 @@ export class DebugOverlay {
|
|||||||
let meshed = 0;
|
let meshed = 0;
|
||||||
let bytes = 0;
|
let bytes = 0;
|
||||||
for (const chunk of client.level.chunks.values()) {
|
for (const chunk of client.level.chunks.values()) {
|
||||||
const meshes = Object.values(chunk.meshes);
|
for (const section of chunk.sections) {
|
||||||
|
const meshes = Object.values(section.meshes);
|
||||||
if (meshes.length > 0) meshed += 1;
|
if (meshes.length > 0) meshed += 1;
|
||||||
for (const mesh of meshes) bytes += mesh.vertex_buffer.size + (mesh.index_buffer?.size ?? 0);
|
for (const mesh of meshes) bytes += (mesh.vertex_buffer?.size ?? 0) + (mesh.index_buffer?.size ?? 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// solid and cutout quads are in their regions' buffers
|
||||||
|
for (const region of client.level.regions.values()) {
|
||||||
|
for (const { buffer } of Object.values(region.layers)) bytes += buffer?.size ?? 0;
|
||||||
}
|
}
|
||||||
this.#chunk_stats = { meshed, bytes };
|
this.#chunk_stats = { meshed, bytes };
|
||||||
return this.#chunk_stats;
|
return this.#chunk_stats;
|
||||||
@@ -180,16 +188,3 @@ export class DebugOverlay {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// pages that aren't https or localhost have no clipboard api, like a server on another computer, but the old way
|
|
||||||
// still copies from a click
|
|
||||||
function copy_text(text: string): Promise<void> {
|
|
||||||
if (navigator.clipboard) return navigator.clipboard.writeText(text);
|
|
||||||
const area = document.createElement("textarea");
|
|
||||||
area.value = text;
|
|
||||||
document.body.append(area);
|
|
||||||
area.select();
|
|
||||||
const copied = document.execCommand("copy");
|
|
||||||
area.remove();
|
|
||||||
return copied ? Promise.resolve() : Promise.reject(new Error("Couldn't copy"));
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||||
import { GuiScreen } from "./gui_screen.ts";
|
import { GuiScreen } from "./gui_screen.ts";
|
||||||
import { back_to_title } from "./title_screen.ts";
|
import { back_to_title } from "./title_screen.ts";
|
||||||
import { Button, TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
|
import { Button, TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { GuiScreen } from "./gui_screen.ts";
|
import { GuiScreen } from "./gui_screen.ts";
|
||||||
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||||
import { InputManager } from "../input_manager.ts";
|
import { InputManager } from "../input_manager.ts";
|
||||||
import type { Client } from "../client.ts";
|
import type { Client } from "../client.ts";
|
||||||
import { MAX_CHAT_LENGTH, type ServerMessage } from "$/common/protocol.ts";
|
import { MAX_CHAT_LENGTH, type ServerMessage } from "@/common/protocol.ts";
|
||||||
import type { Suggestion } from "$/common/commands.ts";
|
import type { Suggestion } from "@/common/commands.ts";
|
||||||
import { TEXT_HEIGHT, TextInput } from "./widgets.ts";
|
import { TEXT_HEIGHT, TextInput } from "./widgets.ts";
|
||||||
|
|
||||||
const SCALE = 2;
|
const SCALE = 2;
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// screens mods' client scripts make, see docs/modding/gui/index.md: the screens of their menus, and screens with no
|
// screens mods' client phases make, see docs/modding/gui/index.md: the screens of their menus, and screens with no
|
||||||
// menu. a mod's screen that throws is closed, with the error in the console
|
// menu. a mod's screen that throws is closed, with the error in the console
|
||||||
import { TICK_DELTA } from "$/common/constants.ts";
|
import { TICK_DELTA } from "@/common/constants.ts";
|
||||||
import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "$/common/mod_api/client.ts";
|
import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "@/common/mod_api/client.ts";
|
||||||
import { canvas } from "../renderer/mod.ts";
|
import { canvas } from "../renderer/mod.ts";
|
||||||
import type { Client } from "../client.ts";
|
import type { Client } from "../client.ts";
|
||||||
import type { ClientMenu } from "../menu.ts";
|
import type { ClientMenu } from "../menu.ts";
|
||||||
@@ -98,7 +98,7 @@ export class GuiModMenuScreen extends GuiMenuScreen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// a screen with no menu, opened by a client script
|
// a screen with no menu, opened by a mod's client phase
|
||||||
export class GuiModScreen extends GuiScreen {
|
export class GuiModScreen extends GuiScreen {
|
||||||
#mod: string;
|
#mod: string;
|
||||||
#screen: Screen;
|
#screen: Screen;
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
|
|
||||||
import { GuiMenuScreen } from "./gui_screen.ts";
|
import { GuiMenuScreen } from "./gui_screen.ts";
|
||||||
import type { LocalPlayer } from "../entity/local_player.ts";
|
import type { LocalPlayer } from "../entity/local_player.ts";
|
||||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import type { EffectJson } from "$/common/mod_data.ts";
|
import type { EffectJson } from "@/common/mod_data.ts";
|
||||||
import { TICKS_PER_SECOND } from "$/common/constants.ts";
|
import { TICKS_PER_SECOND } from "@/common/constants.ts";
|
||||||
import { display_name } from "$/common/utils.ts";
|
import { display_name } from "@/common/utils.ts";
|
||||||
import { ClientMessage, PLAYER_MENU_EXTRA } from "$/common/protocol.ts";
|
import { ClientMessage, PLAYER_MENU_EXTRA } from "@/common/protocol.ts";
|
||||||
import { player_menu } from "../menu.ts";
|
import { player_menu } from "../menu.ts";
|
||||||
import type { ModGraphics } from "./mod_graphics.ts";
|
import type { ModGraphics } from "./mod_graphics.ts";
|
||||||
import { draw_gui_player } from "../rendering/gui_player.ts";
|
import { draw_gui_player } from "../rendering/gui_player.ts";
|
||||||
@@ -64,7 +64,7 @@ export class GuiPlayerInventory extends GuiMenuScreen {
|
|||||||
#render_player(g: ModGraphics) {
|
#render_player(g: ModGraphics) {
|
||||||
const { x, y, size } = PLAYER_BOX;
|
const { x, y, size } = PLAYER_BOX;
|
||||||
g.rect(x, y, size, size, PLAYER_BOX_COLOR);
|
g.rect(x, y, size, size, PLAYER_BOX_COLOR);
|
||||||
const skin = this.#player.skin ?? AssetManager.instance.get<Texture>("bworld:skin");
|
const skin = this.#player.skin ?? AssetManager.instance.get<Texture>("cubi:skin");
|
||||||
const mouse = InputManager.get_mouse_position();
|
const mouse = InputManager.get_mouse_position();
|
||||||
draw_gui_player(
|
draw_gui_player(
|
||||||
skin,
|
skin,
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
import { SLOT_SIZE } from "@/common/constants.ts";
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
||||||
import { click_slot } from "$/common/inventory.ts";
|
import { click_slot } from "@/common/inventory.ts";
|
||||||
import { ClientMessage, CRAFTING_RESULT_SLOT, PLAYER_MENU } from "$/common/protocol.ts";
|
import { ClientMessage, CRAFTING_RESULT_SLOT, PLAYER_MENU } from "@/common/protocol.ts";
|
||||||
import { point_inside_rec } from "../../common/utils.ts";
|
import { point_inside_rec } from "../../common/utils.ts";
|
||||||
import { InputManager } from "../input_manager.ts";
|
import { InputManager } from "../input_manager.ts";
|
||||||
import { ClientInventories } from "../inventory.ts";
|
import { ClientInventories } from "../inventory.ts";
|
||||||
@@ -167,7 +167,7 @@ export abstract class GuiMenuScreen extends GuiScreen {
|
|||||||
} else if (slot.icon) {
|
} else if (slot.icon) {
|
||||||
// where an item's sprite would be
|
// where an item's sprite would be
|
||||||
const icon = get_sprite_region(slot.icon);
|
const icon = get_sprite_region(slot.icon);
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
const [x, y, size] = [this.#slot_x(slot) + 3, this.#slot_y(slot) + 3, SLOT_SIZE - 6];
|
const [x, y, size] = [this.#slot_x(slot) + 3, this.#slot_y(slot) + 3, SLOT_SIZE - 6];
|
||||||
draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size);
|
draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import type { Texture } from "$/client/renderer/mod.ts";
|
import type { Texture } from "@/client/renderer/mod.ts";
|
||||||
import { draw_nine_slice } from "$/client/rendering/render_utils.ts";
|
import { draw_nine_slice } from "@/client/rendering/render_utils.ts";
|
||||||
import { GUI_ATLAS, type GuiSprite } from "./gui_atlas.ts";
|
import { GUI_ATLAS, type GuiSprite } from "./gui_atlas.ts";
|
||||||
|
|
||||||
// gui sprites are drawn 3 times bigger, like minecraft at gui scale 3. SLOT_SIZE is its 18 pixel slot at this scale
|
// gui sprites are drawn 3 times bigger, like minecraft at gui scale 3. SLOT_SIZE is its 18 pixel slot at this scale
|
||||||
@@ -19,7 +19,7 @@ export function draw_gui_sprite(
|
|||||||
height?: number,
|
height?: number,
|
||||||
color = [1, 1, 1, 1],
|
color = [1, 1, 1, 1],
|
||||||
) {
|
) {
|
||||||
const texture = AssetManager.instance.get<Texture>("bworld:gui");
|
const texture = AssetManager.instance.get<Texture>("cubi:gui");
|
||||||
const sprite = GUI_ATLAS[name];
|
const sprite = GUI_ATLAS[name];
|
||||||
const [left, top, right, bottom] = sprite.border;
|
const [left, top, right, bottom] = sprite.border;
|
||||||
draw_nine_slice(
|
draw_nine_slice(
|
||||||
|
|||||||
+16
-253
@@ -1,263 +1,26 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { Client } from "$/client/client.ts";
|
import type { Client } from "@/client/client.ts";
|
||||||
import type { LocalPlayer } from "$/client/entity/local_player.ts";
|
import { render_hud_layers } from "@/client/mods.ts";
|
||||||
import type { ClientInventories } from "$/client/inventory.ts";
|
import { canvas } from "@/client/renderer/mod.ts";
|
||||||
import { draw_item } from "$/client/rendering/render_utils.ts";
|
import type { HudSpace } from "@/common/mod_api/client.ts";
|
||||||
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
import { ModGraphics } from "./mod_graphics.ts";
|
||||||
import { display_name } from "$/common/utils.ts";
|
import { GUI_SCALE } from "./gui_sprites.ts";
|
||||||
import { clock } from "$/common/time.ts";
|
|
||||||
import { biome_season } from "$/common/worldgen/biomes.ts";
|
|
||||||
import { TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
|
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
|
||||||
|
|
||||||
// sizes and gaps in minecraft's gui pixels, drawn GUI_SCALE times bigger
|
// between the top of the hud and the bottom of chat, in gui pixels
|
||||||
const HOTBAR_WIDTH = 182;
|
const CHAT_GAP = 4;
|
||||||
const HOTBAR_HEIGHT = 22;
|
|
||||||
// each slot is 20 across, the item sits 3 in from its corner and the selection 1 out
|
|
||||||
const HOTBAR_CELL = 20;
|
|
||||||
const HOTBAR_ITEM_INSET = 3;
|
|
||||||
// hearts and hunger: 10 icons each, 8 apart, above the hotbar's top. more max health stacks more rows of hearts above,
|
|
||||||
// 10 apart, closer together when there are many, like minecraft
|
|
||||||
const ICON_SIZE = 9;
|
|
||||||
const ICON_SPACING = 8;
|
|
||||||
const ICONS_ABOVE_HOTBAR = 17;
|
|
||||||
const ICONS_PER_ROW = 10;
|
|
||||||
const HEART_ROW_SPACING = 10;
|
|
||||||
const MIN_HEART_ROW_SPACING = 3;
|
|
||||||
// air: 10 bubbles above the hunger, like minecraft, from when the head goes under water until it's full again
|
|
||||||
const MAX_AIR = 20;
|
|
||||||
const AIR_ROW_SPACING = 10;
|
|
||||||
// how long the held item's name shows above the hotbar after it changes, and the last part of that it fades out in
|
|
||||||
const HELD_NAME_MS = 2000;
|
|
||||||
const HELD_NAME_FADE_MS = 500;
|
|
||||||
const HELD_NAME_GAP = 12;
|
|
||||||
// a server's overlay message, see MessageOptions.overlay: above the held item's name, for as long as minecraft's
|
|
||||||
const OVERLAY_MS = 3000;
|
|
||||||
const OVERLAY_FADE_MS = 500;
|
|
||||||
const OVERLAY_GAP = 4;
|
|
||||||
const CROSSHAIR_SIZE = 15;
|
|
||||||
// under the crosshair so it shows on bright sky and snow, minecraft inverts the colors behind it instead
|
|
||||||
const CROSSHAIR_SHADOW: [number, number, number, number] = [0, 0, 0, 0.4];
|
|
||||||
// the attack indicator, like minecraft's: a bar under the crosshair filling up while the attack cooldown runs
|
|
||||||
const ATTACK_BAR_WIDTH = 16;
|
|
||||||
const ATTACK_BAR_HEIGHT = 2;
|
|
||||||
const ATTACK_BAR_GAP = 2;
|
|
||||||
const ATTACK_BAR_BACK: [number, number, number, number] = [0, 0, 0, 0.4];
|
|
||||||
const ATTACK_BAR_FILL: [number, number, number, number] = [1, 1, 1, 0.9];
|
|
||||||
// the day, time, biome and season in the top left, on a dark box so it reads over the sky
|
|
||||||
const INFO_MARGIN = 4;
|
|
||||||
const INFO_PADDING = 3;
|
|
||||||
const INFO_LINE_GAP = 1;
|
|
||||||
const INFO_BACK: [number, number, number, number] = [0, 0, 0, 0.4];
|
|
||||||
|
|
||||||
// what's drawn over the world while playing, like minecraft's Gui: hotbar, crosshair and chat
|
// what's drawn over the world while playing, like minecraft's Gui: mods' layers (ctx.hud), then chat above them
|
||||||
export class Hud {
|
export class Hud {
|
||||||
// what was held last frame, as slot and item id, and when the held item last changed
|
#graphics = new ModGraphics();
|
||||||
#held = "";
|
|
||||||
#held_since = -Infinity;
|
|
||||||
#overlay = "";
|
|
||||||
#overlay_since = -Infinity;
|
|
||||||
|
|
||||||
// shows text above the hotbar for a moment, see MessageOptions.overlay
|
|
||||||
show_overlay(text: string) {
|
|
||||||
this.#overlay = text;
|
|
||||||
this.#overlay_since = performance.now();
|
|
||||||
}
|
|
||||||
|
|
||||||
render(client: Client) {
|
render(client: Client) {
|
||||||
this.#render_hotbar(client.player.inventories);
|
const space: HudSpace = { left_height: 0, right_height: 0 };
|
||||||
this.#render_vitals(client);
|
this.#graphics.begin();
|
||||||
const top = Math.min(icons_y() - heart_rows_height(client.player.max_health), air_y(client.player));
|
render_hud_layers(this.#graphics, space);
|
||||||
this.#render_held_name(client.player.inventories, top);
|
this.#graphics.end();
|
||||||
this.#render_overlay(top);
|
const top = Math.max(space.left_height, space.right_height) + CHAT_GAP;
|
||||||
this.#render_crosshair(client);
|
client.chat.render(false, canvas.height - top * GUI_SCALE);
|
||||||
this.#render_info(client);
|
|
||||||
client.chat.render(false, top - HELD_NAME_GAP);
|
|
||||||
}
|
|
||||||
|
|
||||||
#render_hotbar(inventories: ClientInventories) {
|
|
||||||
const { x, y } = hotbar_position();
|
|
||||||
draw_gui_sprite("hotbar", x, y);
|
|
||||||
|
|
||||||
const selected_x = x + (inventories.hotbar_selected * HOTBAR_CELL - 1) * GUI_SCALE;
|
|
||||||
draw_gui_sprite("hotbar_selection", selected_x, y - GUI_SCALE);
|
|
||||||
|
|
||||||
for (let index = 0; index < 9; index += 1) {
|
|
||||||
const item = inventories.inventory.get_item(index);
|
|
||||||
if (item) {
|
|
||||||
// draw_item takes a slot's corner, which is a pixel out from the item
|
|
||||||
const item_x = x + (index * HOTBAR_CELL + HOTBAR_ITEM_INSET - 1) * GUI_SCALE;
|
|
||||||
draw_item(item, item_x, y + (HOTBAR_ITEM_INSET - 1) * GUI_SCALE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// like minecraft: switching slots, or a different item ending up in the selected one, shows its name for a bit
|
|
||||||
// top is the top of the hearts
|
|
||||||
#render_held_name(inventories: ClientInventories, top: number) {
|
|
||||||
const item = inventories.inventory.get_item(inventories.hotbar_selected);
|
|
||||||
const held = item ? `${inventories.hotbar_selected} ${item.type_id}` : "";
|
|
||||||
const now = performance.now();
|
|
||||||
if (held !== this.#held) {
|
|
||||||
this.#held = held;
|
|
||||||
this.#held_since = item ? now : -Infinity;
|
|
||||||
}
|
|
||||||
|
|
||||||
const shown_for = now - this.#held_since;
|
|
||||||
if (!item || shown_for > HELD_NAME_MS) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const alpha = Math.min(1, (HELD_NAME_MS - shown_for) / HELD_NAME_FADE_MS);
|
|
||||||
draw_centered(display_name(item.type_id), top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE, alpha);
|
|
||||||
}
|
|
||||||
|
|
||||||
// top is the top of the hearts, like for the held item's name, which it goes above
|
|
||||||
#render_overlay(top: number) {
|
|
||||||
const shown_for = performance.now() - this.#overlay_since;
|
|
||||||
if (shown_for > OVERLAY_MS) return;
|
|
||||||
const alpha = Math.min(1, (OVERLAY_MS - shown_for) / OVERLAY_FADE_MS);
|
|
||||||
const y = top - HELD_NAME_GAP - OVERLAY_GAP * GUI_SCALE - TEXT_HEIGHT * TEXT_SCALE * 2;
|
|
||||||
draw_centered(this.#overlay, y, alpha);
|
|
||||||
}
|
|
||||||
|
|
||||||
// hearts on the left and hunger on the right like minecraft, each icon 2 points. saturation is appleskin's outline
|
|
||||||
// over the hunger icons, it's never more than the hunger. air's bubbles go above the hunger, see shows_air
|
|
||||||
#render_vitals(client: Client) {
|
|
||||||
const player = client.player;
|
|
||||||
const { x: left } = hotbar_position();
|
|
||||||
const right = left + HOTBAR_WIDTH * GUI_SCALE;
|
|
||||||
const y = icons_y();
|
|
||||||
const health = Math.ceil(player.health);
|
|
||||||
const food = Math.ceil(player.food);
|
|
||||||
const saturation = Math.min(player.saturation, player.food);
|
|
||||||
|
|
||||||
const hearts = Math.ceil(player.max_health / 2);
|
|
||||||
const row_spacing = heart_row_spacing(player.max_health) * GUI_SCALE;
|
|
||||||
for (let i = 0; i < hearts; i++) {
|
|
||||||
const heart_x = left + (i % ICONS_PER_ROW) * ICON_SPACING * GUI_SCALE;
|
|
||||||
const heart_y = y - Math.floor(i / ICONS_PER_ROW) * row_spacing;
|
|
||||||
draw_gui_sprite("heart_container", heart_x, heart_y);
|
|
||||||
const heart = icon_fill(health, i);
|
|
||||||
if (heart) {
|
|
||||||
draw_gui_sprite(heart === "full" ? "heart_full" : "heart_half", heart_x, heart_y);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = 0; i < ICONS_PER_ROW; i++) {
|
|
||||||
// hunger goes right to left
|
|
||||||
const food_x = right - (i * ICON_SPACING + ICON_SIZE) * GUI_SCALE;
|
|
||||||
draw_gui_sprite("food_empty", food_x, y);
|
|
||||||
const fill = icon_fill(food, i);
|
|
||||||
if (fill) {
|
|
||||||
draw_gui_sprite(fill === "full" ? "food_full" : "food_half", food_x, y);
|
|
||||||
}
|
|
||||||
const saturated = Math.max(0, Math.min(1, (saturation - i * 2) / 2));
|
|
||||||
if (saturated > 0) {
|
|
||||||
const quarters = saturated >= 1 ? 4 : saturated > 0.5 ? 3 : saturated > 0.25 ? 2 : 1;
|
|
||||||
draw_gui_sprite(`saturation_${quarters}`, food_x, y);
|
|
||||||
}
|
|
||||||
if (shows_air(player)) {
|
|
||||||
const air_y = y - AIR_ROW_SPACING * GUI_SCALE;
|
|
||||||
draw_gui_sprite("air_empty", food_x, air_y);
|
|
||||||
const bubble = icon_fill(player.air, i);
|
|
||||||
if (bubble) draw_gui_sprite(bubble === "full" ? "air_full" : "air_half", food_x, air_y);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#render_info(client: Client) {
|
|
||||||
const { day, hour, minute } = clock(client.level.time);
|
|
||||||
const { x, z } = client.player;
|
|
||||||
const biome = client.level.biome_at(Math.floor(x), Math.floor(z));
|
|
||||||
const lines = [
|
|
||||||
`Day ${day}`,
|
|
||||||
`${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`,
|
|
||||||
biome === undefined ? "Unknown" : display_name(biome),
|
|
||||||
biome === undefined ? "Unknown" : capitalize(biome_season(biome, client.level.time)),
|
|
||||||
];
|
|
||||||
|
|
||||||
const padding = INFO_PADDING * GUI_SCALE;
|
|
||||||
const line_height = (TEXT_HEIGHT + INFO_LINE_GAP) * TEXT_SCALE;
|
|
||||||
const width = Math.max(...lines.map((line) => measure_text(line, TEXT_SCALE))) + padding * 2;
|
|
||||||
const height = lines.length * line_height - INFO_LINE_GAP * TEXT_SCALE + padding * 2;
|
|
||||||
const left = INFO_MARGIN * GUI_SCALE;
|
|
||||||
const top = INFO_MARGIN * GUI_SCALE;
|
|
||||||
draw_rect(left, top, width, height, INFO_BACK);
|
|
||||||
lines.forEach((line, i) => {
|
|
||||||
const text_y = top + padding + i * line_height;
|
|
||||||
draw_text(line, left + padding + TEXT_SCALE, text_y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, 1]);
|
|
||||||
draw_text(line, left + padding, text_y, TEXT_SCALE, [1, 1, 1, 1]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#render_crosshair(client: Client) {
|
|
||||||
const size = CROSSHAIR_SIZE * GUI_SCALE;
|
|
||||||
const x = Math.round((canvas.width - size) / 2);
|
|
||||||
const y = Math.round((canvas.height - size) / 2);
|
|
||||||
draw_gui_sprite("crosshair", x + GUI_SCALE, y + GUI_SCALE, undefined, undefined, CROSSHAIR_SHADOW);
|
|
||||||
draw_gui_sprite("crosshair", x, y);
|
|
||||||
|
|
||||||
// only while it's charging, like minecraft
|
|
||||||
const strength = client.player.attack_strength();
|
|
||||||
if (strength >= 1) return;
|
|
||||||
const width = ATTACK_BAR_WIDTH * GUI_SCALE;
|
|
||||||
const bar_x = Math.round((canvas.width - width) / 2);
|
|
||||||
const bar_y = y + size + ATTACK_BAR_GAP * GUI_SCALE;
|
|
||||||
draw_rect(bar_x, bar_y, width, ATTACK_BAR_HEIGHT * GUI_SCALE, ATTACK_BAR_BACK);
|
|
||||||
draw_rect(bar_x, bar_y, Math.round(width * strength), ATTACK_BAR_HEIGHT * GUI_SCALE, ATTACK_BAR_FILL);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// text across the middle of the screen at y, with a shadow so it reads over bright sky and snow
|
|
||||||
function draw_centered(text: string, y: number, alpha: number) {
|
|
||||||
const x = (canvas.width - measure_text(text, TEXT_SCALE)) / 2;
|
|
||||||
draw_text(text, x + TEXT_SCALE, y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, alpha]);
|
|
||||||
draw_text(text, x, y, TEXT_SCALE, [1, 1, 1, alpha]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function hotbar_position() {
|
|
||||||
return {
|
|
||||||
x: Math.round((canvas.width - HOTBAR_WIDTH * GUI_SCALE) / 2),
|
|
||||||
y: canvas.height - HOTBAR_HEIGHT * GUI_SCALE,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// the top of the hearts and hunger
|
|
||||||
function icons_y() {
|
|
||||||
return hotbar_position().y - ICONS_ABOVE_HOTBAR * GUI_SCALE;
|
|
||||||
}
|
|
||||||
|
|
||||||
// as soon as the head is under, so it shows full before it starts going down, and while it fills back up after
|
|
||||||
function shows_air(player: LocalPlayer) {
|
|
||||||
return player.eyes_in_water || player.air < MAX_AIR;
|
|
||||||
}
|
|
||||||
|
|
||||||
// the top of the bubbles while they show, the hearts' otherwise
|
|
||||||
function air_y(player: LocalPlayer) {
|
|
||||||
return icons_y() - (shows_air(player) ? AIR_ROW_SPACING * GUI_SCALE : 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// how far apart rows of hearts are, in gui pixels
|
|
||||||
function heart_row_spacing(max_health: number) {
|
|
||||||
const rows = Math.ceil(max_health / 2 / ICONS_PER_ROW);
|
|
||||||
return Math.max(HEART_ROW_SPACING - (rows - 2), MIN_HEART_ROW_SPACING);
|
|
||||||
}
|
|
||||||
|
|
||||||
// how much higher the rows of hearts past the first go, on the canvas
|
|
||||||
function heart_rows_height(max_health: number) {
|
|
||||||
const rows = Math.ceil(max_health / 2 / ICONS_PER_ROW);
|
|
||||||
return Math.max(0, rows - 1) * heart_row_spacing(max_health) * GUI_SCALE;
|
|
||||||
}
|
|
||||||
|
|
||||||
function capitalize(word: string) {
|
|
||||||
return word[0].toUpperCase() + word.slice(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// whether icon i of a value, 2 points an icon, is full, half or empty
|
|
||||||
function icon_fill(value: number, i: number): "full" | "half" | undefined {
|
|
||||||
if (value >= i * 2 + 2) return "full";
|
|
||||||
if (value === i * 2 + 1) return "half";
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the desktop app's title screen, a main menu like luanti's. singleplayer lists the worlds in the app's data folder,
|
||||||
|
// to play one, make one or pick its mods. the app does the files and runs the world's server, see desktop/main.ts
|
||||||
|
import type { ModEntry, WorldEntry } from "@/desktop/saves.ts";
|
||||||
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
|
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||||
|
import { server_address } from "@/client/handshake.ts";
|
||||||
|
import { GuiScreen } from "./gui_screen.ts";
|
||||||
|
import { platform } from "../platform.ts";
|
||||||
|
import type { JoinServer } from "./title_screen.ts";
|
||||||
|
import { Button, EditBox, ListBox, TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
|
||||||
|
|
||||||
|
const WIDTH = 440;
|
||||||
|
const ROW_HEIGHT = 48;
|
||||||
|
const GAP = 20;
|
||||||
|
const LIST_WIDTH = 640;
|
||||||
|
const HALF_WIDTH = (LIST_WIDTH - GAP) / 2;
|
||||||
|
const TOP = 100;
|
||||||
|
// the name players have in singleplayer worlds, which what they carry is saved under
|
||||||
|
const SINGLEPLAYER_NAME = "singleplayer";
|
||||||
|
|
||||||
|
type Show = (screen: GuiScreen) => void;
|
||||||
|
|
||||||
|
export class MainMenuScreen extends GuiScreen {
|
||||||
|
#buttons: Button[];
|
||||||
|
|
||||||
|
constructor(show: Show, join: JoinServer) {
|
||||||
|
super();
|
||||||
|
const back = () => show(new MainMenuScreen(show, join));
|
||||||
|
// there's nothing behind these yet
|
||||||
|
const multiplayer = new Button("Multiplayer", WIDTH, ROW_HEIGHT, () => {});
|
||||||
|
const mods = new Button("Mods", WIDTH, ROW_HEIGHT, () => {});
|
||||||
|
multiplayer.active = mods.active = false;
|
||||||
|
this.#buttons = [
|
||||||
|
new Button("Singleplayer", WIDTH, ROW_HEIGHT, () => show(new WorldListScreen(show, join))),
|
||||||
|
multiplayer,
|
||||||
|
mods,
|
||||||
|
new Button("Credits", WIDTH, ROW_HEIGHT, () => show(platform.credits_screen(back))),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
on_tick(_delta: number): void {
|
||||||
|
let y = (canvas.height - this.#buttons.length * (ROW_HEIGHT + GAP)) / 2 + 40;
|
||||||
|
for (const button of this.#buttons) {
|
||||||
|
button.x = (canvas.width - WIDTH) / 2;
|
||||||
|
button.y = y;
|
||||||
|
y += ROW_HEIGHT + GAP;
|
||||||
|
button.handle_input();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
on_render(): void {
|
||||||
|
draw_centered("Cubi", this.#buttons[0].y - 140, 8);
|
||||||
|
for (const button of this.#buttons) button.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_close(): void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the worlds in the app's saves folder
|
||||||
|
class WorldListScreen extends GuiScreen {
|
||||||
|
#show: Show;
|
||||||
|
#join: JoinServer;
|
||||||
|
#worlds: WorldEntry[] = [];
|
||||||
|
#mods: ModEntry[] = [];
|
||||||
|
#list = new ListBox(LIST_WIDTH, 0, (row, double) => {
|
||||||
|
this.#list.selected = row;
|
||||||
|
if (double) this.#play();
|
||||||
|
});
|
||||||
|
#play_button = new Button("Play", HALF_WIDTH, ROW_HEIGHT, () => this.#play());
|
||||||
|
#new_button = new Button("New world", HALF_WIDTH, ROW_HEIGHT, () => this.#edit());
|
||||||
|
#mods_button = new Button("Mods", HALF_WIDTH, ROW_HEIGHT, () => this.#edit(this.#selected));
|
||||||
|
#back_button = new Button("Back", HALF_WIDTH, ROW_HEIGHT, () => this.#back());
|
||||||
|
#status = new Status();
|
||||||
|
#busy = true;
|
||||||
|
|
||||||
|
// select is the world selected at first, like one that was just made
|
||||||
|
constructor(show: Show, join: JoinServer, select?: string) {
|
||||||
|
super();
|
||||||
|
this.#show = show;
|
||||||
|
this.#join = join;
|
||||||
|
this.#status.set("Loading worlds...");
|
||||||
|
desktop("singleplayer").then((response) => response.json()).then(
|
||||||
|
({ worlds, mods }: { worlds: WorldEntry[]; mods: ModEntry[] }) => {
|
||||||
|
this.#worlds = worlds;
|
||||||
|
this.#mods = mods;
|
||||||
|
this.#list.rows = worlds.map((world) => ({ text: world.name }));
|
||||||
|
this.#list.selected = Math.max(0, worlds.findIndex((world) => world.name === select));
|
||||||
|
this.#status.set(worlds.length === 0 ? "There are no worlds yet, make one with New world" : "");
|
||||||
|
this.#busy = false;
|
||||||
|
},
|
||||||
|
(e) => this.#status.fail(e),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
get #selected(): WorldEntry | undefined {
|
||||||
|
return this.#worlds[this.#list.selected];
|
||||||
|
}
|
||||||
|
|
||||||
|
on_tick(_delta: number): void {
|
||||||
|
const buttons = [this.#play_button, this.#new_button, this.#mods_button, this.#back_button];
|
||||||
|
const x = (canvas.width - LIST_WIDTH) / 2;
|
||||||
|
this.#list.x = x;
|
||||||
|
this.#list.y = TOP;
|
||||||
|
this.#list.height = canvas.height - TOP - 2 * (ROW_HEIGHT + GAP) - 120;
|
||||||
|
for (const [i, button] of buttons.entries()) {
|
||||||
|
button.x = x + (i % 2) * (HALF_WIDTH + GAP);
|
||||||
|
button.y = TOP + this.#list.height + GAP + Math.floor(i / 2) * (ROW_HEIGHT + GAP);
|
||||||
|
}
|
||||||
|
this.#play_button.active = this.#mods_button.active = !this.#busy && this.#selected !== undefined;
|
||||||
|
this.#new_button.active = !this.#busy;
|
||||||
|
|
||||||
|
if (InputManager.is_key_pressed("Escape")) return this.#back();
|
||||||
|
if (InputManager.is_key_pressed("Enter")) this.#play();
|
||||||
|
if (!this.#busy) this.#list.handle_input();
|
||||||
|
for (const button of buttons) button.handle_input();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_render(): void {
|
||||||
|
draw_centered("Singleplayer", TOP / 2, 4);
|
||||||
|
this.#list.render();
|
||||||
|
for (const button of [this.#play_button, this.#new_button, this.#mods_button, this.#back_button]) {
|
||||||
|
button.render();
|
||||||
|
}
|
||||||
|
this.#status.render(this.#back_button.y + ROW_HEIGHT + GAP);
|
||||||
|
}
|
||||||
|
|
||||||
|
on_close(): void {}
|
||||||
|
|
||||||
|
#back() {
|
||||||
|
if (!this.#busy || this.#status.error) this.#show(new MainMenuScreen(this.#show, this.#join));
|
||||||
|
}
|
||||||
|
|
||||||
|
// a new world, or the mods of one there is
|
||||||
|
#edit(world?: WorldEntry) {
|
||||||
|
this.#show(new WorldModsScreen(this.#show, this.#join, this.#mods, world));
|
||||||
|
}
|
||||||
|
|
||||||
|
async #play() {
|
||||||
|
const world = this.#selected;
|
||||||
|
if (!world || this.#busy) return;
|
||||||
|
this.#busy = true;
|
||||||
|
this.#status.set(`Starting ${world.name}...`);
|
||||||
|
try {
|
||||||
|
await desktop("play", { world: world.name });
|
||||||
|
await this.#join(server_address(platform.page.host), SINGLEPLAYER_NAME, (text) => this.#status.set(text));
|
||||||
|
} catch (e) {
|
||||||
|
this.#status.fail(e);
|
||||||
|
this.#busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a new world's name and mods, or the mods of one there is. turning a mod on turns on the mods it needs, and turning
|
||||||
|
// one off turns off the mods that need it
|
||||||
|
class WorldModsScreen extends GuiScreen {
|
||||||
|
#show: Show;
|
||||||
|
#join: JoinServer;
|
||||||
|
#mods: ModEntry[];
|
||||||
|
#world: WorldEntry | undefined;
|
||||||
|
#enabled: Set<string>;
|
||||||
|
#name = new EditBox(LIST_WIDTH, ROW_HEIGHT, new TextInput("", 32), "World name");
|
||||||
|
#list = new ListBox(LIST_WIDTH, 0, (row) => this.#toggle(this.#mods[row].id));
|
||||||
|
#save_button: Button;
|
||||||
|
#cancel_button: Button;
|
||||||
|
#status = new Status();
|
||||||
|
#busy = false;
|
||||||
|
|
||||||
|
constructor(show: Show, join: JoinServer, mods: ModEntry[], world?: WorldEntry) {
|
||||||
|
super();
|
||||||
|
this.#show = show;
|
||||||
|
this.#join = join;
|
||||||
|
this.#mods = mods;
|
||||||
|
this.#world = world;
|
||||||
|
// a new world starts with every mod. a world's mods that aren't in the folder anymore are dropped when it's saved
|
||||||
|
this.#enabled = new Set(mods.map(({ id }) => id).filter((id) => !world || world.mods.includes(id)));
|
||||||
|
this.#name.focused = !world;
|
||||||
|
this.#save_button = new Button(world ? "Save" : "Create", HALF_WIDTH, ROW_HEIGHT, () => this.#save());
|
||||||
|
this.#cancel_button = new Button("Cancel", HALF_WIDTH, ROW_HEIGHT, () => this.#back(world?.name));
|
||||||
|
this.#update_rows();
|
||||||
|
if (mods.length === 0) this.#status.set("There are no mods in the mods folder");
|
||||||
|
}
|
||||||
|
|
||||||
|
on_tick(_delta: number): void {
|
||||||
|
const x = (canvas.width - LIST_WIDTH) / 2;
|
||||||
|
let y = TOP;
|
||||||
|
if (!this.#world) {
|
||||||
|
this.#name.x = x;
|
||||||
|
this.#name.y = y;
|
||||||
|
y += ROW_HEIGHT + GAP;
|
||||||
|
}
|
||||||
|
this.#list.x = x;
|
||||||
|
this.#list.y = y;
|
||||||
|
this.#list.height = canvas.height - y - ROW_HEIGHT - GAP - 120;
|
||||||
|
this.#save_button.x = x;
|
||||||
|
this.#cancel_button.x = x + HALF_WIDTH + GAP;
|
||||||
|
this.#save_button.y = this.#cancel_button.y = y + this.#list.height + GAP;
|
||||||
|
this.#save_button.active = this.#name.active = !this.#busy;
|
||||||
|
|
||||||
|
if (InputManager.is_key_pressed("Escape")) return this.#back(this.#world?.name);
|
||||||
|
if (InputManager.is_key_pressed("Enter")) this.#save();
|
||||||
|
this.#name.handle_input();
|
||||||
|
this.#list.handle_input();
|
||||||
|
this.#save_button.handle_input();
|
||||||
|
this.#cancel_button.handle_input();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_render(): void {
|
||||||
|
draw_centered(this.#world ? `${this.#world.name}'s mods` : "New world", TOP / 2, 4);
|
||||||
|
if (!this.#world) this.#name.render();
|
||||||
|
this.#list.render();
|
||||||
|
this.#save_button.render();
|
||||||
|
this.#cancel_button.render();
|
||||||
|
this.#status.render(this.#save_button.y + ROW_HEIGHT + GAP);
|
||||||
|
}
|
||||||
|
|
||||||
|
on_close(): void {}
|
||||||
|
|
||||||
|
#toggle(id: string) {
|
||||||
|
const by_id = new Map(this.#mods.map((mod) => [mod.id, mod]));
|
||||||
|
const on = (id: string) => {
|
||||||
|
this.#enabled.add(id);
|
||||||
|
for (const dependency of by_id.get(id)?.dependencies ?? []) {
|
||||||
|
if (by_id.has(dependency) && !this.#enabled.has(dependency)) on(dependency);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const off = (id: string) => {
|
||||||
|
this.#enabled.delete(id);
|
||||||
|
for (const mod of this.#mods) {
|
||||||
|
if (mod.dependencies.includes(id) && this.#enabled.has(mod.id)) off(mod.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(this.#enabled.has(id) ? off : on)(id);
|
||||||
|
this.#update_rows();
|
||||||
|
}
|
||||||
|
|
||||||
|
#update_rows() {
|
||||||
|
this.#list.rows = this.#mods.map((mod) => ({
|
||||||
|
text: `${mod.name} ${mod.version}`,
|
||||||
|
checked: this.#enabled.has(mod.id),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async #save() {
|
||||||
|
if (this.#busy) return;
|
||||||
|
this.#busy = true;
|
||||||
|
const world = this.#world?.name ?? this.#name.value.trim();
|
||||||
|
try {
|
||||||
|
await desktop(this.#world ? "world_mods" : "create_world", { world, mods: [...this.#enabled] });
|
||||||
|
this.#back(world);
|
||||||
|
} catch (e) {
|
||||||
|
this.#status.fail(e);
|
||||||
|
this.#busy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#back(select?: string) {
|
||||||
|
this.#show(new WorldListScreen(this.#show, this.#join, select));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// what's happening, or what went wrong, under a screen's buttons. a line each for messages that have several, like
|
||||||
|
// a world's mods' problems
|
||||||
|
class Status {
|
||||||
|
text = "";
|
||||||
|
error = false;
|
||||||
|
|
||||||
|
set(text: string) {
|
||||||
|
this.text = text;
|
||||||
|
this.error = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
fail(e: unknown) {
|
||||||
|
this.text = e instanceof Error ? e.message : String(e);
|
||||||
|
this.error = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
render(y: number) {
|
||||||
|
for (const line of this.text.split("\n").filter((line) => line !== "")) {
|
||||||
|
const width = measure_text(line, TEXT_SCALE);
|
||||||
|
const x = (canvas.width - width) / 2;
|
||||||
|
draw_rect(x - 8, y - 4, width + 16, TEXT_HEIGHT * TEXT_SCALE + 8, [0, 0, 0, 0.5]);
|
||||||
|
draw_text(line, x, y, TEXT_SCALE, this.error ? [1, 0.45, 0.45, 1] : [1, 1, 1, 1]);
|
||||||
|
y += TEXT_HEIGHT * TEXT_SCALE + 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw_centered(text: string, y: number, scale: number) {
|
||||||
|
draw_text(text, (canvas.width - measure_text(text, scale)) / 2, y - (TEXT_HEIGHT * scale) / 2, scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// asks the desktop app, see desktop/main.ts. throws with what the app said went wrong
|
||||||
|
async function desktop(path: string, body: unknown = {}): Promise<Response> {
|
||||||
|
const response = await fetch(new URL(`/desktop/${path}`, platform.page), {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(await response.text());
|
||||||
|
return response;
|
||||||
|
}
|
||||||
+54
-34
@@ -1,16 +1,16 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer.
|
// the immediate mode drawing mods' client phases get (Graphics in common/mod_api/client.ts), on top of the renderer.
|
||||||
// one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas
|
// one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas
|
||||||
// pixels each
|
// pixels each
|
||||||
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { Color, Graphics } from "$/common/mod_api/client.ts";
|
import type { Color, Graphics, TooltipLine } from "@/common/mod_api/client.ts";
|
||||||
import type { FluidVariant, KeyCode } from "$/common/mod_api/shared.ts";
|
import type { FluidVariant, ItemStack as ApiItemStack, KeyCode } from "@/common/mod_api/shared.ts";
|
||||||
import { point_inside_rec } from "$/common/utils.ts";
|
import { point_inside_rec } from "@/common/utils.ts";
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import { InputManager, type KeyCode as InputKey } from "$/client/input_manager.ts";
|
import { InputManager, type KeyCode as InputKey } from "@/client/input_manager.ts";
|
||||||
import {
|
import {
|
||||||
begin_clip,
|
begin_clip,
|
||||||
canvas,
|
canvas,
|
||||||
@@ -20,16 +20,24 @@ import {
|
|||||||
end_clip,
|
end_clip,
|
||||||
measure_text,
|
measure_text,
|
||||||
Texture,
|
Texture,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { draw_fluid, draw_item } from "$/client/rendering/render_utils.ts";
|
import { draw_fluid, draw_item } from "@/client/rendering/render_utils.ts";
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { draw_tooltip, item_tooltip, type TooltipLine } from "./tooltip.ts";
|
import { draw_tooltip, item_tooltip } from "./tooltip.ts";
|
||||||
import { TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
|
import { TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
|
||||||
import { GUI_ATLAS } from "./gui_atlas.ts";
|
import { GUI_ATLAS, type GuiSprite } from "./gui_atlas.ts";
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
||||||
|
|
||||||
const WHITE: Color = [1, 1, 1, 1];
|
const WHITE: Color = [1, 1, 1, 1];
|
||||||
const GREY: Color = [0.66, 0.66, 0.66, 1];
|
const GREY: Color = [0.66, 0.66, 0.66, 1];
|
||||||
|
// text's shadow, see Graphics.text
|
||||||
|
const SHADOW = [0.15, 0.15, 0.15];
|
||||||
|
|
||||||
|
// a script's tooltip line, copied so it can't change after, in color when it doesn't say
|
||||||
|
function tooltip_line(line: string | TooltipLine, color: Color): TooltipLine {
|
||||||
|
if (typeof line === "string") return { text: line, color };
|
||||||
|
return { text: String(line.text), color: line.color ?? color, icon: line.icon, priority: line.priority };
|
||||||
|
}
|
||||||
const INPUT_HEIGHT = 32;
|
const INPUT_HEIGHT = 32;
|
||||||
const FIELD_BORDER = GUI_ATLAS.text_field.border[0] * GUI_SCALE;
|
const FIELD_BORDER = GUI_ATLAS.text_field.border[0] * GUI_SCALE;
|
||||||
|
|
||||||
@@ -112,8 +120,13 @@ export class ModGraphics implements Graphics {
|
|||||||
draw_gui_sprite("panel", this.#x(x), this.#y(y), w * S, h * S);
|
draw_gui_sprite("panel", this.#x(x), this.#y(y), w * S, h * S);
|
||||||
}
|
}
|
||||||
|
|
||||||
text(text: string, x: number, y: number, options: { scale?: number; color?: Color } = {}) {
|
text(text: string, x: number, y: number, options: { scale?: number; color?: Color; shadow?: boolean } = {}) {
|
||||||
draw_text(text, this.#x(x), this.#y(y), TEXT_SCALE * (options.scale ?? 1), options.color ?? WHITE);
|
const scale = TEXT_SCALE * (options.scale ?? 1);
|
||||||
|
const color = options.color ?? WHITE;
|
||||||
|
if (options.shadow) {
|
||||||
|
draw_text(text, this.#x(x) + scale, this.#y(y) + scale, scale, [...SHADOW, color[3]]);
|
||||||
|
}
|
||||||
|
draw_text(text, this.#x(x), this.#y(y), scale, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
measure_text(text: string, scale = 1) {
|
measure_text(text: string, scale = 1) {
|
||||||
@@ -121,7 +134,7 @@ export class ModGraphics implements Graphics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
texture(id: string, x: number, y: number, w: number, h: number, part = [0, 0, 1, 1]) {
|
texture(id: string, x: number, y: number, w: number, h: number, part = [0, 0, 1, 1]) {
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
const region = get_sprite_region(id);
|
const region = get_sprite_region(id);
|
||||||
const [u, v, pw, ph] = part;
|
const [u, v, pw, ph] = part;
|
||||||
draw_texture_region(
|
draw_texture_region(
|
||||||
@@ -157,8 +170,28 @@ export class ModGraphics implements Graphics {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
item(id: string, x: number, y: number, count = 1) {
|
sprite(id: string, x: number, y: number, options: { width?: number; height?: number; color?: Color } = {}) {
|
||||||
|
const name = id.startsWith("cubi:") ? id.slice("cubi:".length) : undefined;
|
||||||
|
if (!name || !Object.hasOwn(GUI_ATLAS, name)) throw new Error(`unknown gui sprite ${id}`);
|
||||||
|
const { width, height, color } = options;
|
||||||
|
draw_gui_sprite(
|
||||||
|
name as GuiSprite,
|
||||||
|
this.#x(x),
|
||||||
|
this.#y(y),
|
||||||
|
width === undefined ? undefined : width * S,
|
||||||
|
height === undefined ? undefined : height * S,
|
||||||
|
color,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
item(item: string | ApiItemStack, x: number, y: number, count = 1) {
|
||||||
|
const id = typeof item === "string" ? item : item.id;
|
||||||
if (!EverythingRegistry.get<ItemRegistry>("items", id)) throw new Error(`unknown item ${id}`);
|
if (!EverythingRegistry.get<ItemRegistry>("items", id)) throw new Error(`unknown item ${id}`);
|
||||||
|
if (typeof item !== "string") {
|
||||||
|
// like a slot
|
||||||
|
draw_item(ItemStack.from_data(structuredClone(item)), this.#x(x), this.#y(y));
|
||||||
|
return;
|
||||||
|
}
|
||||||
const stack = new ItemStack(id, count);
|
const stack = new ItemStack(id, count);
|
||||||
// the count only shows when it's more than one
|
// the count only shows when it's more than one
|
||||||
draw_item(stack, this.#x(x), this.#y(y), count !== 1 && stack.max_amount !== 1);
|
draw_item(stack, this.#x(x), this.#y(y), count !== 1 && stack.max_amount !== 1);
|
||||||
@@ -245,25 +278,12 @@ export class ModGraphics implements Graphics {
|
|||||||
return !this.typing && InputManager.is_key_pressed(key as InputKey);
|
return !this.typing && InputManager.is_key_pressed(key as InputKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number) {
|
tooltip(lines: (string | TooltipLine)[], x: number, y: number) {
|
||||||
this.#tooltip = {
|
this.#tooltip = { lines: lines.map((line) => tooltip_line(line, WHITE)), x: this.#x(x), y: this.#y(y) };
|
||||||
lines: lines.map((line) =>
|
|
||||||
typeof line === "string"
|
|
||||||
? { text: line, color: WHITE }
|
|
||||||
: { text: line.text, color: line.color ?? WHITE }
|
|
||||||
),
|
|
||||||
x: this.#x(x),
|
|
||||||
y: this.#y(y),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
item_tooltip(id: string, x: number, y: number, extra: (string | { text: string; color?: Color })[] = []) {
|
item_tooltip(id: string, x: number, y: number, extra: (string | TooltipLine)[] = []) {
|
||||||
const lines = [
|
const lines = item_tooltip(new ItemStack(id, 1), extra.map((line) => tooltip_line(line, GREY)));
|
||||||
...item_tooltip(new ItemStack(id, 1)),
|
|
||||||
...extra.map((line) =>
|
|
||||||
typeof line === "string" ? { text: line, color: GREY } : { text: line.text, color: line.color ?? GREY }
|
|
||||||
),
|
|
||||||
];
|
|
||||||
this.#tooltip = { lines, x: this.#x(x), y: this.#y(y) };
|
this.#tooltip = { lines, x: this.#x(x), y: this.#y(y) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { Client } from "$/client/client.ts";
|
import type { Client } from "@/client/client.ts";
|
||||||
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||||
import { GuiScreen } from "./gui_screen.ts";
|
import { GuiScreen } from "./gui_screen.ts";
|
||||||
import { Button, TEXT_HEIGHT } from "./widgets.ts";
|
import { Button, TEXT_HEIGHT } from "./widgets.ts";
|
||||||
import { CreditsScreen } from "./credits_screen.ts";
|
import { platform } from "../platform.ts";
|
||||||
|
|
||||||
const BUTTON_WIDTH = 440;
|
const BUTTON_WIDTH = 440;
|
||||||
const BUTTON_HEIGHT = 48;
|
const BUTTON_HEIGHT = 48;
|
||||||
@@ -20,7 +20,7 @@ export class PauseScreen extends GuiScreen {
|
|||||||
this.buttons = [
|
this.buttons = [
|
||||||
new Button("Back to game", BUTTON_WIDTH, BUTTON_HEIGHT, () => client.pop_screen()),
|
new Button("Back to game", BUTTON_WIDTH, BUTTON_HEIGHT, () => client.pop_screen()),
|
||||||
new Button("Credits", BUTTON_WIDTH, BUTTON_HEIGHT, () => {
|
new Button("Credits", BUTTON_WIDTH, BUTTON_HEIGHT, () => {
|
||||||
client.push_screen(new CreditsScreen(() => client.pop_screen()));
|
client.push_screen(platform.credits_screen(() => client.pop_screen()));
|
||||||
}),
|
}),
|
||||||
new Button("Disconnect", BUTTON_WIDTH, BUTTON_HEIGHT, () => client.disconnect()),
|
new Button("Disconnect", BUTTON_WIDTH, BUTTON_HEIGHT, () => client.disconnect()),
|
||||||
];
|
];
|
||||||
|
|||||||
+38
-67
@@ -1,17 +1,17 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { MAX_NAME_LENGTH } from "$/common/protocol.ts";
|
import { MAX_NAME_LENGTH } from "@/common/protocol.ts";
|
||||||
import { InputManager } from "$/client/input_manager.ts";
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||||
import { default_server, HandshakeError, server_address, ServerAddress } from "$/client/handshake.ts";
|
import { default_server, HandshakeError, server_address, ServerAddress } from "@/client/handshake.ts";
|
||||||
import { default_player_name } from "$/client/network.ts";
|
import { default_player_name } from "@/client/network.ts";
|
||||||
import { GuiScreen } from "./gui_screen.ts";
|
import { GuiScreen } from "./gui_screen.ts";
|
||||||
import { CreditsScreen } from "./credits_screen.ts";
|
import { platform } from "../platform.ts";
|
||||||
import { Button, EditBox, TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
|
import { Button, EditBox, TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
|
||||||
|
|
||||||
const LAST_SERVER_KEY = "bworld:last_server";
|
const LAST_SERVER_KEY = "cubi:last_server";
|
||||||
const LAST_NAME_KEY = "bworld:last_name";
|
const LAST_NAME_KEY = "cubi:last_name";
|
||||||
|
|
||||||
const WIDTH = 440;
|
const WIDTH = 440;
|
||||||
const ROW_HEIGHT = 48;
|
const ROW_HEIGHT = 48;
|
||||||
@@ -23,8 +23,8 @@ const TITLE_SCALE = 8;
|
|||||||
// for the player when it fails
|
// for the player when it fails
|
||||||
export type JoinServer = (address: ServerAddress, name: string, status: (text: string) => void) => Promise<void>;
|
export type JoinServer = (address: ServerAddress, name: string, status: (text: string) => void) => Promise<void>;
|
||||||
|
|
||||||
// the first thing players see, like minecraft's title and multiplayer screens rolled into one: a name, a server,
|
// the first thing players see in the browser, like minecraft's title and multiplayer screens rolled into one: a
|
||||||
// and a button to join it. in the desktop app there's also singleplayer, which joins the app's own server
|
// name, a server, and a button to join it. the desktop app has a main menu instead, see main_menu.ts
|
||||||
export class TitleScreen extends GuiScreen {
|
export class TitleScreen extends GuiScreen {
|
||||||
#join_server: JoinServer;
|
#join_server: JoinServer;
|
||||||
|
|
||||||
@@ -36,17 +36,11 @@ export class TitleScreen extends GuiScreen {
|
|||||||
);
|
);
|
||||||
server = new EditBox(WIDTH, ROW_HEIGHT, new TextInput(initial_server(), 256, (char) => char !== " "), "host:port");
|
server = new EditBox(WIDTH, ROW_HEIGHT, new TextInput(initial_server(), 256, (char) => char !== " "), "host:port");
|
||||||
join_button = new Button("Join server", WIDTH, ROW_HEIGHT, () => this.#join());
|
join_button = new Button("Join server", WIDTH, ROW_HEIGHT, () => this.#join());
|
||||||
// the page was served by a game server of its own to play on alone, see desktop/main.ts
|
|
||||||
singleplayer_button = has_singleplayer()
|
|
||||||
? new Button("Singleplayer", WIDTH, ROW_HEIGHT, () => this.#join_singleplayer())
|
|
||||||
: undefined;
|
|
||||||
credits_button = new Button("Credits", WIDTH, ROW_HEIGHT, () => this.#open_credits());
|
credits_button = new Button("Credits", WIDTH, ROW_HEIGHT, () => this.#open_credits());
|
||||||
// in the browser, the desktop app for this computer's os
|
// the desktop app for this computer's os
|
||||||
download_button = has_singleplayer()
|
download_button = new Button(`Download for ${download_os().name}`, WIDTH, ROW_HEIGHT, download_desktop_app);
|
||||||
? undefined
|
|
||||||
: new Button(`Download for ${download_os().name}`, WIDTH, ROW_HEIGHT, download_desktop_app);
|
|
||||||
// open over the title screen, it gets the input while it's there
|
// open over the title screen, it gets the input while it's there
|
||||||
#credits: CreditsScreen | undefined;
|
#credits: GuiScreen | undefined;
|
||||||
|
|
||||||
status = "";
|
status = "";
|
||||||
status_is_error = false;
|
status_is_error = false;
|
||||||
@@ -86,14 +80,13 @@ export class TitleScreen extends GuiScreen {
|
|||||||
if (InputManager.is_key_pressed("Enter")) {
|
if (InputManager.is_key_pressed("Enter")) {
|
||||||
this.#join();
|
this.#join();
|
||||||
}
|
}
|
||||||
this.singleplayer_button?.handle_input();
|
|
||||||
this.join_button.handle_input();
|
this.join_button.handle_input();
|
||||||
this.credits_button.handle_input();
|
this.credits_button.handle_input();
|
||||||
this.download_button?.handle_input();
|
this.download_button.handle_input();
|
||||||
}
|
}
|
||||||
|
|
||||||
on_render(): void {
|
on_render(): void {
|
||||||
const title = "bworld";
|
const title = "Cubi";
|
||||||
const title_width = measure_text(title, TITLE_SCALE);
|
const title_width = measure_text(title, TITLE_SCALE);
|
||||||
draw_text(
|
draw_text(
|
||||||
title,
|
title,
|
||||||
@@ -105,16 +98,15 @@ export class TitleScreen extends GuiScreen {
|
|||||||
this.#label("Name", this.name);
|
this.#label("Name", this.name);
|
||||||
this.#label("Server", this.server);
|
this.#label("Server", this.server);
|
||||||
this.name.render();
|
this.name.render();
|
||||||
this.singleplayer_button?.render();
|
|
||||||
this.server.render();
|
this.server.render();
|
||||||
this.join_button.render();
|
this.join_button.render();
|
||||||
this.credits_button.render();
|
this.credits_button.render();
|
||||||
this.download_button?.render();
|
this.download_button.render();
|
||||||
|
|
||||||
if (this.status) {
|
if (this.status) {
|
||||||
const width = measure_text(this.status, TEXT_SCALE);
|
const width = measure_text(this.status, TEXT_SCALE);
|
||||||
const x = (canvas.width - width) / 2;
|
const x = (canvas.width - width) / 2;
|
||||||
const y = (this.download_button ?? this.credits_button).y + ROW_HEIGHT + GAP;
|
const y = this.download_button.y + ROW_HEIGHT + GAP;
|
||||||
draw_rect(x - 8, y - 4, width + 16, TEXT_HEIGHT * TEXT_SCALE + 8, [0, 0, 0, 0.5]);
|
draw_rect(x - 8, y - 4, width + 16, TEXT_HEIGHT * TEXT_SCALE + 8, [0, 0, 0, 0.5]);
|
||||||
draw_text(this.status, x, y, TEXT_SCALE, this.status_is_error ? [1, 0.45, 0.45, 1] : [1, 1, 1, 1]);
|
draw_text(this.status, x, y, TEXT_SCALE, this.status_is_error ? [1, 0.45, 0.45, 1] : [1, 1, 1, 1]);
|
||||||
}
|
}
|
||||||
@@ -126,7 +118,7 @@ export class TitleScreen extends GuiScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#open_credits() {
|
#open_credits() {
|
||||||
this.#credits ??= new CreditsScreen(() => this.#close_credits());
|
this.#credits ??= platform.credits_screen(() => this.#close_credits());
|
||||||
}
|
}
|
||||||
|
|
||||||
#close_credits() {
|
#close_credits() {
|
||||||
@@ -136,28 +128,17 @@ export class TitleScreen extends GuiScreen {
|
|||||||
|
|
||||||
#layout() {
|
#layout() {
|
||||||
const x = (canvas.width - WIDTH) / 2;
|
const x = (canvas.width - WIDTH) / 2;
|
||||||
const singleplayer_height = this.singleplayer_button ? ROW_HEIGHT + GAP : 0;
|
const total = 2 * (LABEL_GAP + ROW_HEIGHT + GAP) + 3 * ROW_HEIGHT + 2 * GAP;
|
||||||
const download_height = this.download_button ? ROW_HEIGHT + GAP : 0;
|
|
||||||
const total = 2 * (LABEL_GAP + ROW_HEIGHT + GAP) + singleplayer_height + 2 * ROW_HEIGHT + GAP +
|
|
||||||
download_height;
|
|
||||||
let y = (canvas.height - total) / 2 + 40;
|
let y = (canvas.height - total) / 2 + 40;
|
||||||
for (const field of [this.name, this.server]) {
|
for (const field of [this.name, this.server]) {
|
||||||
field.x = x;
|
field.x = x;
|
||||||
field.y = y + LABEL_GAP;
|
field.y = y + LABEL_GAP;
|
||||||
y += LABEL_GAP + ROW_HEIGHT + GAP;
|
y += LABEL_GAP + ROW_HEIGHT + GAP;
|
||||||
if (field === this.name && this.singleplayer_button) {
|
|
||||||
this.singleplayer_button.x = x;
|
|
||||||
this.singleplayer_button.y = y;
|
|
||||||
y += singleplayer_height;
|
|
||||||
}
|
}
|
||||||
}
|
for (const button of [this.join_button, this.credits_button, this.download_button]) {
|
||||||
this.join_button.x = x;
|
button.x = x;
|
||||||
this.join_button.y = y;
|
button.y = y;
|
||||||
this.credits_button.x = x;
|
y += ROW_HEIGHT + GAP;
|
||||||
this.credits_button.y = y + ROW_HEIGHT + GAP;
|
|
||||||
if (this.download_button) {
|
|
||||||
this.download_button.x = x;
|
|
||||||
this.download_button.y = this.credits_button.y + ROW_HEIGHT + GAP;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,18 +162,10 @@ export class TitleScreen extends GuiScreen {
|
|||||||
await this.#connect(address);
|
await this.#connect(address);
|
||||||
}
|
}
|
||||||
|
|
||||||
// the server that served this page
|
async #connect(address: ServerAddress) {
|
||||||
async #join_singleplayer() {
|
|
||||||
if (this.#joining) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await this.#connect(server_address(location.host), "Starting singleplayer...");
|
|
||||||
}
|
|
||||||
|
|
||||||
async #connect(address: ServerAddress, status = `Connecting to ${address.base.host}...`) {
|
|
||||||
remember(LAST_NAME_KEY, this.name.value);
|
remember(LAST_NAME_KEY, this.name.value);
|
||||||
this.#set_joining(true);
|
this.#set_joining(true);
|
||||||
this.status = status;
|
this.status = `Connecting to ${address.base.host}...`;
|
||||||
this.status_is_error = false;
|
this.status_is_error = false;
|
||||||
try {
|
try {
|
||||||
await this.#join_server(address, this.name.value, (text) => this.status = text);
|
await this.#join_server(address, this.name.value, (text) => this.status = text);
|
||||||
@@ -205,9 +178,6 @@ export class TitleScreen extends GuiScreen {
|
|||||||
#set_joining(joining: boolean) {
|
#set_joining(joining: boolean) {
|
||||||
this.#joining = joining;
|
this.#joining = joining;
|
||||||
this.name.active = this.server.active = this.join_button.active = !joining;
|
this.name.active = this.server.active = this.join_button.active = !joining;
|
||||||
if (this.singleplayer_button) {
|
|
||||||
this.singleplayer_button.active = !joining;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#show_error(message: string) {
|
#show_error(message: string) {
|
||||||
@@ -218,18 +188,18 @@ export class TitleScreen extends GuiScreen {
|
|||||||
|
|
||||||
// what was typed last time, unless the page was opened with ?server= or ?name=
|
// what was typed last time, unless the page was opened with ?server= or ?name=
|
||||||
function initial_server() {
|
function initial_server() {
|
||||||
const page = new URL(location.href);
|
const page = platform.page;
|
||||||
return page.searchParams.has("server") ? default_server(page) : recall(LAST_SERVER_KEY) ?? default_server(page);
|
return page.searchParams.has("server") ? default_server(page) : recall(LAST_SERVER_KEY) ?? default_server(page);
|
||||||
}
|
}
|
||||||
|
|
||||||
function initial_name() {
|
function initial_name() {
|
||||||
const page = new URL(location.href);
|
const page = platform.page;
|
||||||
return page.searchParams.has("name") ? default_player_name() : recall(LAST_NAME_KEY) ?? "";
|
return page.searchParams.has("name") ? default_player_name() : recall(LAST_NAME_KEY) ?? "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function recall(key: string): string | undefined {
|
function recall(key: string): string | undefined {
|
||||||
try {
|
try {
|
||||||
return localStorage.getItem(key) ?? undefined;
|
return platform.storage.getItem(key) ?? undefined;
|
||||||
} catch {
|
} catch {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -237,14 +207,15 @@ function recall(key: string): string | undefined {
|
|||||||
|
|
||||||
function remember(key: string, value: string) {
|
function remember(key: string, value: string) {
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(key, value);
|
platform.storage.setItem(key, value);
|
||||||
} catch {
|
} catch {
|
||||||
// private windows and blocked storage just start empty next time
|
// private windows and blocked storage just start empty next time
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function has_singleplayer() {
|
// the page is the desktop app's, see desktop/main.ts
|
||||||
return new URL(location.href).searchParams.has("singleplayer");
|
export function in_desktop_app() {
|
||||||
|
return platform.page.searchParams.has("singleplayer");
|
||||||
}
|
}
|
||||||
|
|
||||||
// the desktop app's build for the os the browser is on, which the server has in /dist/, see DESKTOP_DOWNLOADS. everything that isn't windows
|
// the desktop app's build for the os the browser is on, which the server has in /dist/, see DESKTOP_DOWNLOADS. everything that isn't windows
|
||||||
@@ -263,14 +234,14 @@ function download_desktop_app() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// a server's mods can't be unloaded, so going back to the title screen starts the page over. without ?server=
|
// a server's mods can't be unloaded, so going back to the title screen starts the page over. without ?server=
|
||||||
// or ?name=, so the fields show what was used last. the desktop app keeps its ?singleplayer and ?server=, its saved
|
// or ?name=, so the fields show what was used last. the desktop app keeps its ?singleplayer and ?server=, for its
|
||||||
// fields don't last between launches and the page's own address isn't a server to join
|
// main menu
|
||||||
export function back_to_title() {
|
export function back_to_title() {
|
||||||
const page = new URL(location.href);
|
const page = platform.page;
|
||||||
const next = new URL(location.pathname, location.href);
|
const next = new URL(page.pathname, page);
|
||||||
if (has_singleplayer()) {
|
if (in_desktop_app()) {
|
||||||
next.searchParams.set("server", page.searchParams.get("server") ?? "");
|
next.searchParams.set("server", page.searchParams.get("server") ?? "");
|
||||||
next.searchParams.set("singleplayer", "");
|
next.searchParams.set("singleplayer", "");
|
||||||
}
|
}
|
||||||
location.href = next.href;
|
platform.restart(next);
|
||||||
}
|
}
|
||||||
|
|||||||
+46
-36
@@ -1,66 +1,76 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// the box next to the mouse saying what an item is, like minecraft's: its name, the fluid in it, what it's worth, then
|
// the box next to the mouse saying what an item is, like minecraft's: its name, the fluid in it, its food, mods' lines,
|
||||||
// its lore
|
// then its lore
|
||||||
import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
import { EverythingRegistry, ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { contained_fluid, type ItemStack, sell_value } from "$/common/inventory.ts";
|
import { contained_fluid, type ItemStack } from "@/common/inventory.ts";
|
||||||
import { display_name } from "$/common/utils.ts";
|
import { type Color, TOOLTIP_PRIORITY, type TooltipLine } from "@/common/mod_api/client.ts";
|
||||||
import { fluid_rules } from "$/client/fluid_rules.ts";
|
import type { ItemStack as ApiItemStack } from "@/common/mod_api/shared.ts";
|
||||||
import { canvas, draw_text, draw_texture_region, measure_text, type Texture } from "$/client/renderer/mod.ts";
|
import { display_name } from "@/common/utils.ts";
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { fluid_rules } from "@/client/fluid_rules.ts";
|
||||||
import type { MenuTank } from "$/common/protocol.ts";
|
import { canvas, draw_text, draw_texture_region, measure_text, type Texture } from "@/client/renderer/mod.ts";
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
|
import type { MenuTank } from "@/common/protocol.ts";
|
||||||
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
||||||
import { TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
|
import { TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
|
||||||
|
|
||||||
type Color = [number, number, number, number];
|
export type { TooltipLine };
|
||||||
|
|
||||||
const NAME_COLOR: Color = [1, 1, 1, 1];
|
const NAME_COLOR: Color = [1, 1, 1, 1];
|
||||||
const LORE_COLOR: Color = [0.66, 0.66, 0.66, 1];
|
const LORE_COLOR: Color = [0.66, 0.66, 0.66, 1];
|
||||||
const FOOD_COLOR: Color = [0.85, 0.6, 0.35, 1];
|
const FOOD_COLOR: Color = [0.85, 0.6, 0.35, 1];
|
||||||
const FLUID_COLOR: Color = [0.55, 0.75, 0.95, 1];
|
const FLUID_COLOR: Color = [0.55, 0.75, 0.95, 1];
|
||||||
const VALUE_COLOR: Color = [0.95, 0.8, 0.3, 1];
|
const WHITE: Color = [1, 1, 1, 1];
|
||||||
// from the edge of the tooltip sprite to the text
|
// from the edge of the tooltip sprite to the text
|
||||||
const PADDING = 4 * GUI_SCALE;
|
const PADDING = 4 * GUI_SCALE;
|
||||||
const LINE_GAP = 4;
|
const LINE_GAP = 4;
|
||||||
// between a line's icon and its text
|
// between a line's icon and its text
|
||||||
const ICON_GAP = 4;
|
const ICON_GAP = 4;
|
||||||
// drawn before what an item sells for
|
|
||||||
const VALUE_ICON = "bworld:copper_coin";
|
|
||||||
// from the mouse, so the cursor doesn't cover it
|
// from the mouse, so the cursor doesn't cover it
|
||||||
const OFFSET = 16;
|
const OFFSET = 16;
|
||||||
|
|
||||||
export interface TooltipLine {
|
// what client phases add to every item's tooltip, in load order, see ctx.ui.add_item_tooltip. client/mods.ts fills it,
|
||||||
text: string;
|
// each wrapped so one throwing is logged under its mod
|
||||||
color: Color;
|
export const item_tooltips: ((item: ApiItemStack, lines: TooltipLine[]) => void)[] = [];
|
||||||
// a texture drawn before the text, a square as tall as the line
|
|
||||||
icon?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// its name, the fluid a full container holds, the item's lore from its json, then what the server's scripts said about
|
// its name, the fluid a full container holds, its food, the lines mods add, then the item's lore from its json and what
|
||||||
// this stack
|
// the server's scripts said about this stack. extra lines go under all of it unless they have a priority
|
||||||
export function item_tooltip(item: ItemStack): TooltipLine[] {
|
export function item_tooltip(item: ItemStack, extra: TooltipLine[] = []): TooltipLine[] {
|
||||||
const lines: TooltipLine[] = [{ text: display_name(item.type_id), color: NAME_COLOR }];
|
const lines: TooltipLine[] = [
|
||||||
|
{ text: display_name(item.type_id), color: NAME_COLOR, priority: TOOLTIP_PRIORITY.name },
|
||||||
|
];
|
||||||
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||||
const fluid = contained_fluid(item.type_id, item.data);
|
const fluid = contained_fluid(item.type_id, item.data);
|
||||||
if (fluid) {
|
if (fluid) {
|
||||||
lines.push({ text: `${fluid_rules.name(fluid)}, ${info!.fluid_container!.capacity} mB`, color: FLUID_COLOR });
|
lines.push({
|
||||||
|
text: `${fluid_rules.name(fluid)}, ${info!.fluid_container!.capacity} mB`,
|
||||||
|
color: FLUID_COLOR,
|
||||||
|
priority: TOOLTIP_PRIORITY.fluid,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (info?.food) {
|
if (info?.food) {
|
||||||
lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR });
|
lines.push({
|
||||||
|
text: `Restores ${info.food.nutrition} hunger`,
|
||||||
|
color: FOOD_COLOR,
|
||||||
|
priority: TOOLTIP_PRIORITY.food,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const value = sell_value(item.type_id, item.data, fluid_rules);
|
for (const lore of [info?.lore, item.lore]) {
|
||||||
if (value !== undefined) {
|
|
||||||
lines.push({ icon: VALUE_ICON, text: `${value}`, color: VALUE_COLOR });
|
|
||||||
}
|
|
||||||
const static_lore = info?.lore;
|
|
||||||
for (const lore of [static_lore, item.lore]) {
|
|
||||||
for (const text of lore?.split("\n") ?? []) {
|
for (const text of lore?.split("\n") ?? []) {
|
||||||
lines.push({ text, color: LORE_COLOR });
|
lines.push({ text, color: LORE_COLOR, priority: TOOLTIP_PRIORITY.lore });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return lines;
|
if (item_tooltips.length) {
|
||||||
|
const stack = { id: item.type_id, count: item.amount, data: item.data };
|
||||||
|
for (const fn of item_tooltips) fn(stack, lines);
|
||||||
|
}
|
||||||
|
for (const line of extra) lines.push({ ...line, priority: line.priority ?? TOOLTIP_PRIORITY.extra });
|
||||||
|
// sort is stable, so lines with the same priority stay in the order they were added
|
||||||
|
return lines
|
||||||
|
.filter((line) => typeof line?.text === "string")
|
||||||
|
.sort((a, b) => (a.priority ?? TOOLTIP_PRIORITY.default) - (b.priority ?? TOOLTIP_PRIORITY.default));
|
||||||
}
|
}
|
||||||
|
|
||||||
// a menu's fluid slot, like modern industrialization's: the fluid, how much of the tank it fills, and what clicking it
|
// a menu's fluid slot, like modern industrialization's: the fluid, how much of the tank it fills, and what clicking it
|
||||||
@@ -92,7 +102,7 @@ export function draw_tooltip(lines: TooltipLine[], mouse_x: number, mouse_y: num
|
|||||||
y = Math.max(0, y);
|
y = Math.max(0, y);
|
||||||
|
|
||||||
draw_gui_sprite("tooltip", x, y, width, height);
|
draw_gui_sprite("tooltip", x, y, width, height);
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
lines.forEach((line, i) => {
|
lines.forEach((line, i) => {
|
||||||
const line_y = y + PADDING + i * (line_height + LINE_GAP);
|
const line_y = y + PADDING + i * (line_height + LINE_GAP);
|
||||||
if (line.icon) {
|
if (line.icon) {
|
||||||
@@ -109,6 +119,6 @@ export function draw_tooltip(lines: TooltipLine[], mouse_x: number, mouse_y: num
|
|||||||
line_height * 2,
|
line_height * 2,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
draw_text(line.text, x + PADDING + icon_width(line), line_y, TEXT_SCALE, line.color);
|
draw_text(line.text, x + PADDING + icon_width(line), line_y, TEXT_SCALE, line.color ?? WHITE);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+100
-5
@@ -1,10 +1,11 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { point_inside_rec } from "$/common/utils.ts";
|
import { point_inside_rec } from "@/common/utils.ts";
|
||||||
import { InputManager, type KeyCode } from "$/client/input_manager.ts";
|
import { InputManager, type KeyCode } from "@/client/input_manager.ts";
|
||||||
import { draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
import { draw_rect, draw_rect_stroke, draw_text, measure_text } from "@/client/renderer/mod.ts";
|
||||||
import { draw_gui_sprite } from "./gui_sprites.ts";
|
import { draw_gui_sprite } from "./gui_sprites.ts";
|
||||||
|
import { platform } from "@/client/platform.ts";
|
||||||
|
|
||||||
export const TEXT_SCALE = 2;
|
export const TEXT_SCALE = 2;
|
||||||
// how tall the font is at scale 1
|
// how tall the font is at scale 1
|
||||||
@@ -124,14 +125,14 @@ export class TextInput {
|
|||||||
const copy = InputManager.is_shortcut_pressed("c");
|
const copy = InputManager.is_shortcut_pressed("c");
|
||||||
const cut = InputManager.is_shortcut_pressed("x");
|
const cut = InputManager.is_shortcut_pressed("x");
|
||||||
if ((copy || cut) && this.anchor !== this.caret) {
|
if ((copy || cut) && this.anchor !== this.caret) {
|
||||||
navigator.clipboard?.writeText(this.selected_text()).catch(() => {});
|
platform.write_clipboard(this.selected_text()).catch(() => {});
|
||||||
if (cut) {
|
if (cut) {
|
||||||
this.delete_to(this.caret);
|
this.delete_to(this.caret);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (InputManager.is_shortcut_pressed("v")) {
|
if (InputManager.is_shortcut_pressed("v")) {
|
||||||
// the browser may ask first, it's put in once it answers
|
// the browser may ask first, it's put in once it answers
|
||||||
navigator.clipboard?.readText().then((text) => this.insert(text), () => {});
|
platform.read_clipboard().then((text) => this.insert(text), () => {});
|
||||||
}
|
}
|
||||||
for (const char of InputManager.get_typed_characters()) {
|
for (const char of InputManager.get_typed_characters()) {
|
||||||
this.insert(char);
|
this.insert(char);
|
||||||
@@ -345,3 +346,97 @@ export class EditBox {
|
|||||||
return this.x + 10;
|
return this.x + 10;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const LIST_ROW_HEIGHT = 40;
|
||||||
|
const CHECK_SIZE = 20;
|
||||||
|
|
||||||
|
// rows of text that scroll with the mouse wheel, like minecraft's selection lists. a row can have a box ticked or not
|
||||||
|
// in front, for lists of things to turn on and off
|
||||||
|
export class ListBox {
|
||||||
|
x = 0;
|
||||||
|
y = 0;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
rows: { text: string; checked?: boolean }[] = [];
|
||||||
|
selected = -1;
|
||||||
|
// clicking a row, double is whether it was the second click of a double click
|
||||||
|
on_click: (row: number, double: boolean) => void;
|
||||||
|
#scroll = 0;
|
||||||
|
#hovered = -1;
|
||||||
|
#last_click = { row: -1, time: -Infinity };
|
||||||
|
|
||||||
|
constructor(width: number, height: number, on_click: (row: number, double: boolean) => void) {
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
this.on_click = on_click;
|
||||||
|
}
|
||||||
|
|
||||||
|
get #visible() {
|
||||||
|
return Math.max(1, Math.floor(this.height / LIST_ROW_HEIGHT));
|
||||||
|
}
|
||||||
|
|
||||||
|
handle_input() {
|
||||||
|
const mouse = InputManager.get_mouse_position();
|
||||||
|
const inside = point_inside_rec(mouse.x, mouse.y, this.x, this.y, this.width, this.height);
|
||||||
|
const max_scroll = Math.max(0, this.rows.length - this.#visible);
|
||||||
|
if (inside) this.#scroll += Math.sign(InputManager.get_wheel_delta());
|
||||||
|
this.#scroll = Math.max(0, Math.min(max_scroll, this.#scroll));
|
||||||
|
|
||||||
|
const row = this.#scroll + Math.floor((mouse.y - this.y) / LIST_ROW_HEIGHT);
|
||||||
|
this.#hovered = inside && row < this.rows.length ? row : -1;
|
||||||
|
if (this.#hovered >= 0 && InputManager.is_mouse_pressed(0)) {
|
||||||
|
InputManager.consume_mouse(0);
|
||||||
|
const now = performance.now();
|
||||||
|
const double = this.#last_click.row === row && now - this.#last_click.time < DOUBLE_CLICK_MS;
|
||||||
|
this.#last_click = double ? { row: -1, time: -Infinity } : { row, time: now };
|
||||||
|
this.on_click(row, double);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
draw_rect(this.x, this.y, this.width, this.height, [0, 0, 0, 0.5]);
|
||||||
|
const shown = this.rows.slice(this.#scroll, this.#scroll + this.#visible);
|
||||||
|
for (const [i, row] of shown.entries()) {
|
||||||
|
const index = this.#scroll + i;
|
||||||
|
const y = this.y + i * LIST_ROW_HEIGHT;
|
||||||
|
if (index === this.selected) {
|
||||||
|
draw_rect(this.x, y, this.width, LIST_ROW_HEIGHT, SELECTION_COLOR);
|
||||||
|
} else if (index === this.#hovered) {
|
||||||
|
draw_rect(this.x, y, this.width, LIST_ROW_HEIGHT, [1, 1, 1, 0.1]);
|
||||||
|
}
|
||||||
|
let text_x = this.x + 12;
|
||||||
|
if (row.checked !== undefined) {
|
||||||
|
const box_y = y + (LIST_ROW_HEIGHT - CHECK_SIZE) / 2;
|
||||||
|
draw_rect_stroke(text_x, box_y, CHECK_SIZE, CHECK_SIZE, [1, 1, 1, 1], 2);
|
||||||
|
if (row.checked) draw_rect(text_x + 5, box_y + 5, CHECK_SIZE - 10, CHECK_SIZE - 10);
|
||||||
|
text_x += CHECK_SIZE + 12;
|
||||||
|
}
|
||||||
|
draw_text(row.text, text_x, y + (LIST_ROW_HEIGHT - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE);
|
||||||
|
}
|
||||||
|
// how far down it's scrolled, when it doesn't all fit
|
||||||
|
if (this.rows.length > this.#visible) {
|
||||||
|
const bar = this.height * this.#visible / this.rows.length;
|
||||||
|
const bar_y = this.y + (this.height - bar) * this.#scroll / (this.rows.length - this.#visible);
|
||||||
|
draw_rect(this.x + this.width - 6, bar_y, 6, bar, [1, 1, 1, 0.5]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// text split into lines no wider than width pixels at TEXT_SCALE, at spaces and at its own line breaks
|
||||||
|
export function wrap_text(text: string, width: number): string[] {
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (const line of text.split("\n")) {
|
||||||
|
let current = "";
|
||||||
|
for (const word of line.split(" ")) {
|
||||||
|
const next = current ? `${current} ${word}` : word;
|
||||||
|
if (current && measure_text(next, TEXT_SCALE) > width) {
|
||||||
|
lines.push(current);
|
||||||
|
current = word;
|
||||||
|
} else {
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push(current);
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|||||||
+7
-6
@@ -3,10 +3,11 @@
|
|||||||
|
|
||||||
// connecting to a server and getting what it needs before joining, see docs/modding/networking/index.md:
|
// connecting to a server and getting what it needs before joining, see docs/modding/networking/index.md:
|
||||||
// hello -> welcome, download and check everything, ready -> join
|
// hello -> welcome, download and check everything, ready -> join
|
||||||
import { ClientMessage, PROTOCOL_VERSION, ServerMessage } from "$/common/protocol.ts";
|
import { ClientMessage, PROTOCOL_VERSION, ServerMessage } from "@/common/protocol.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
const CONNECT_TIMEOUT_MS = 5000;
|
const CONNECT_TIMEOUT_MS = 5000;
|
||||||
const TRUST_KEY_PREFIX = "bworld:trusted:";
|
const TRUST_KEY_PREFIX = "cubi:trusted:";
|
||||||
|
|
||||||
export type Welcome = Extract<ServerMessage, { type: "welcome" }>;
|
export type Welcome = Extract<ServerMessage, { type: "welcome" }>;
|
||||||
export type Join = Extract<ServerMessage, { type: "join" }>;
|
export type Join = Extract<ServerMessage, { type: "join" }>;
|
||||||
@@ -23,12 +24,12 @@ export interface ServerAddress {
|
|||||||
export class HandshakeError extends Error {}
|
export class HandshakeError extends Error {}
|
||||||
|
|
||||||
// what the server field starts as: ?server=host:port, otherwise the server that served the page
|
// what the server field starts as: ?server=host:port, otherwise the server that served the page
|
||||||
export function default_server(page = new URL(location.href)): string {
|
export function default_server(page = platform.page): string {
|
||||||
return page.searchParams.get("server") ?? page.host;
|
return page.searchParams.get("server") ?? page.host;
|
||||||
}
|
}
|
||||||
|
|
||||||
// what a player typed as the server: host:port, or a full http(s) or ws(s) url to pick the scheme
|
// what a player typed as the server: host:port, or a full http(s) or ws(s) url to pick the scheme
|
||||||
export function server_address(input: string, page = new URL(location.href)): ServerAddress {
|
export function server_address(input: string, page = platform.page): ServerAddress {
|
||||||
const text = input.trim();
|
const text = input.trim();
|
||||||
let host = text;
|
let host = text;
|
||||||
let secure: boolean;
|
let secure: boolean;
|
||||||
@@ -209,7 +210,7 @@ function mod_versions(welcome: Welcome) {
|
|||||||
|
|
||||||
export function is_trusted(address: ServerAddress, welcome: Welcome): boolean {
|
export function is_trusted(address: ServerAddress, welcome: Welcome): boolean {
|
||||||
try {
|
try {
|
||||||
return localStorage.getItem(trust_key(address)) === mod_versions(welcome);
|
return platform.storage.getItem(trust_key(address)) === mod_versions(welcome);
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -217,7 +218,7 @@ export function is_trusted(address: ServerAddress, welcome: Welcome): boolean {
|
|||||||
|
|
||||||
export function remember_trust(address: ServerAddress, welcome: Welcome) {
|
export function remember_trust(address: ServerAddress, welcome: Welcome) {
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(trust_key(address), mod_versions(welcome));
|
platform.storage.setItem(trust_key(address), mod_versions(welcome));
|
||||||
} catch {
|
} catch {
|
||||||
// private windows and blocked storage just ask again next time
|
// private windows and blocked storage just ask again next time
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>bworld</title>
|
<title>Cubi</title>
|
||||||
<style>
|
<style>
|
||||||
html,
|
html,
|
||||||
body {
|
body {
|
||||||
|
|||||||
+56
-210
@@ -1,7 +1,7 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { canvas } from "./renderer/core.ts";
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
export type KeyCode =
|
export type KeyCode =
|
||||||
// letters
|
// letters
|
||||||
@@ -79,16 +79,8 @@ export type KeyCode =
|
|||||||
| "F11"
|
| "F11"
|
||||||
| "F12";
|
| "F12";
|
||||||
|
|
||||||
// the keys the game keeps in fullscreen, see "fullscreenchange". not every key: with all of them locked, chromium
|
// what the player presses and how the mouse moves, kept for the frame. where it runs feeds it events: the page's
|
||||||
// can keep alt+tab and the windows key from the os too
|
// (browser_input.ts) or the desktop app's window (native/), and grabs the mouse for it (see platform.ts)
|
||||||
const FULLSCREEN_LOCKED_KEYS = ["Escape", "KeyW"];
|
|
||||||
|
|
||||||
// chromium's keyboard lock api, typescript's dom types don't have it yet
|
|
||||||
interface KeyboardLock {
|
|
||||||
lock(codes?: string[]): Promise<void>;
|
|
||||||
unlock(): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class InputManager {
|
export class InputManager {
|
||||||
static keys_down = new Set<string>();
|
static keys_down = new Set<string>();
|
||||||
static keys_pressed = new Set<string>();
|
static keys_pressed = new Set<string>();
|
||||||
@@ -108,8 +100,6 @@ export class InputManager {
|
|||||||
// around a screen can never turn it
|
// around a screen can never turn it
|
||||||
static look_delta_x = 0;
|
static look_delta_x = 0;
|
||||||
static look_delta_y = 0;
|
static look_delta_y = 0;
|
||||||
// chrome sometimes sends a huge movement with the first mouse event after the lock starts
|
|
||||||
static #skip_look_event = false;
|
|
||||||
static wheel_delta = 0;
|
static wheel_delta = 0;
|
||||||
|
|
||||||
// in the order they were typed. a list, since the same letter can be typed twice in one frame
|
// in the order they were typed. a list, since the same letter can be typed twice in one frame
|
||||||
@@ -117,147 +107,71 @@ export class InputManager {
|
|||||||
// letters pressed with ctrl (cmd on macs) held, like "a" for select all
|
// letters pressed with ctrl (cmd on macs) held, like "a" for select all
|
||||||
static shortcuts: string[] = [];
|
static shortcuts: string[] = [];
|
||||||
|
|
||||||
static pointer_lock_flag = false;
|
// code is a KeyCode, key what it types: a character, or a name like "Enter". shortcut is whether ctrl (cmd on
|
||||||
static mouse_grab_timer = 0;
|
// macs) is held for one, then a letter is a shortcut instead of being typed
|
||||||
static mouse_ungrab_timer = 0;
|
static key_down(code: string, key: string, shortcut: boolean) {
|
||||||
static mouse_ungrab_timeout = -1;
|
if (!this.keys_down.has(code)) {
|
||||||
static pointer_lock_waiting = false;
|
this.keys_pressed.add(code);
|
||||||
// the browser let go of the mouse while the game wanted it, like escape or switching windows
|
|
||||||
static #lost_pointer_lock = false;
|
|
||||||
// the canvas had the pointer lock at the last pointerlockchange
|
|
||||||
static #was_locked = false;
|
|
||||||
// the desktop app moving the cursor after the mouse was let go, see center_desktop_mouse. grabbing it again waits
|
|
||||||
// for that, or the move would come while it's locked and turn the camera
|
|
||||||
static #centering = Promise.resolve();
|
|
||||||
static #awaiting_centering = false;
|
|
||||||
// the locked mouse doesn't turn the camera until then, the move can still reach chromium after the app answered,
|
|
||||||
// or the mouse was locked again before chromium said it let go
|
|
||||||
static #ignore_look_until = 0;
|
|
||||||
// what the game last asked for, it can change while grabbing waits
|
|
||||||
static #want_grab = false;
|
|
||||||
|
|
||||||
static initialize(canvas: HTMLCanvasElement) {
|
|
||||||
self.addEventListener("keydown", (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
if (!this.keys_down.has(e.code)) {
|
|
||||||
this.keys_pressed.add(e.code);
|
|
||||||
}
|
}
|
||||||
this.keys_down.add(e.code);
|
this.keys_down.add(code);
|
||||||
if (e.key.length === 1) {
|
if (key.length === 1) {
|
||||||
if (this.#is_shortcut(e)) {
|
if (shortcut) {
|
||||||
this.shortcuts.push(e.key.toLowerCase());
|
this.shortcuts.push(key.toLowerCase());
|
||||||
} else {
|
} else {
|
||||||
this.typed_characters.push(e.key);
|
this.typed_characters.push(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
// keys let go while the window isn't focused never send keyup, so they'd stay held
|
|
||||||
self.addEventListener("blur", () => {
|
|
||||||
this.keys_down.clear();
|
|
||||||
this.mouse_buttons_down.clear();
|
|
||||||
});
|
|
||||||
|
|
||||||
self.addEventListener("keyup", (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
this.keys_down.delete(e.code);
|
|
||||||
this.keys_released.add(e.code);
|
|
||||||
});
|
|
||||||
|
|
||||||
self.addEventListener("mousedown", (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
if (!document.hasFocus() && document.pointerLockElement !== canvas) {
|
|
||||||
this.set_mouse_grabbed(true);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (!this.mouse_buttons_down.has(e.button)) {
|
|
||||||
this.mouse_buttons_pressed.add(e.button);
|
// for where typing comes apart from keys, the desktop app's window
|
||||||
|
static type_text(text: string) {
|
||||||
|
this.typed_characters.push(...text);
|
||||||
}
|
}
|
||||||
this.mouse_buttons_down.add(e.button);
|
|
||||||
});
|
|
||||||
|
|
||||||
self.addEventListener("mouseup", (e) => {
|
static key_up(code: string) {
|
||||||
e.preventDefault();
|
this.keys_down.delete(code);
|
||||||
this.mouse_buttons_down.delete(e.button);
|
this.keys_released.add(code);
|
||||||
this.mouse_buttons_released.add(e.button);
|
|
||||||
});
|
|
||||||
|
|
||||||
// ctrl+scroll (and pinching a trackpad, which browsers send as that) would zoom the page. only a listener that
|
|
||||||
// isn't passive can stop it, and on the window they're passive unless told otherwise
|
|
||||||
self.addEventListener("wheel", (e) => {
|
|
||||||
if (e.ctrlKey) {
|
|
||||||
e.preventDefault();
|
|
||||||
}
|
}
|
||||||
this.wheel_delta += e.deltaY;
|
|
||||||
}, { passive: false });
|
|
||||||
|
|
||||||
document.addEventListener("mousemove", (e) => {
|
// buttons are numbered like the dom's: 0 left, 1 middle, 2 right
|
||||||
e.preventDefault();
|
static mouse_down(button: number) {
|
||||||
if (document.pointerLockElement === canvas) {
|
if (!this.mouse_buttons_down.has(button)) {
|
||||||
if (this.#skip_look_event) {
|
this.mouse_buttons_pressed.add(button);
|
||||||
this.#skip_look_event = false;
|
}
|
||||||
return;
|
this.mouse_buttons_down.add(button);
|
||||||
}
|
}
|
||||||
if (performance.now() < this.#ignore_look_until) return;
|
|
||||||
this.look_delta_x += e.movementX;
|
|
||||||
this.look_delta_y += e.movementY;
|
|
||||||
} else {
|
|
||||||
const rect = canvas.getBoundingClientRect();
|
|
||||||
const new_x = e.clientX - rect.left;
|
|
||||||
const new_y = e.clientY - rect.top;
|
|
||||||
|
|
||||||
|
static mouse_up(button: number) {
|
||||||
|
this.mouse_buttons_down.delete(button);
|
||||||
|
this.mouse_buttons_released.add(button);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the cursor at x y, in the canvas's pixels
|
||||||
|
static move_cursor(x: number, y: number) {
|
||||||
// not from where it was before the mouse was grabbed, that's -1
|
// not from where it was before the mouse was grabbed, that's -1
|
||||||
if (this.mouse_x >= 0 && this.mouse_y >= 0) {
|
if (this.mouse_x >= 0 && this.mouse_y >= 0) {
|
||||||
this.mouse_delta_x += new_x - this.mouse_x;
|
this.mouse_delta_x += x - this.mouse_x;
|
||||||
this.mouse_delta_y += new_y - this.mouse_y;
|
this.mouse_delta_y += y - this.mouse_y;
|
||||||
|
}
|
||||||
|
this.mouse_x = x;
|
||||||
|
this.mouse_y = y;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.mouse_x = new_x;
|
// the grabbed mouse moved
|
||||||
this.mouse_y = new_y;
|
static look(x: number, y: number) {
|
||||||
|
this.look_delta_x += x;
|
||||||
|
this.look_delta_y += y;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener("pointerlockchange", () => {
|
// down is positive, about 100 for a notch of a wheel
|
||||||
const locked = document.pointerLockElement === canvas;
|
static scroll(amount: number) {
|
||||||
if (this.#was_locked && !locked) {
|
this.wheel_delta += amount;
|
||||||
this.#ignore_look_until = Infinity;
|
|
||||||
this.#centering = center_desktop_mouse().then(() => {
|
|
||||||
this.#ignore_look_until = performance.now() + CENTERING_SETTLE_MS;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
this.#was_locked = locked;
|
|
||||||
this.#skip_look_event = locked;
|
|
||||||
self.setTimeout(() => {
|
|
||||||
const grab = document.pointerLockElement === canvas;
|
|
||||||
if (!grab) {
|
|
||||||
if (this.pointer_lock_flag) {
|
|
||||||
this.mouse_ungrab_timer = performance.now();
|
|
||||||
this.#lost_pointer_lock = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.pointer_lock_flag = grab;
|
|
||||||
}, 60);
|
|
||||||
this.pointer_lock_waiting = false;
|
|
||||||
});
|
|
||||||
|
|
||||||
// in fullscreen, chromium's keyboard lock gives the game escape (holding it still leaves fullscreen) and ctrl+w,
|
// keys and buttons let go while the game didn't have focus never come up, so they'd stay held
|
||||||
// instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before
|
static release_all() {
|
||||||
document.addEventListener("fullscreenchange", () => {
|
this.keys_down.clear();
|
||||||
const keyboard = (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard;
|
this.mouse_buttons_down.clear();
|
||||||
if (!keyboard?.lock) return;
|
|
||||||
if (document.fullscreenElement) {
|
|
||||||
keyboard.lock(FULLSCREEN_LOCKED_KEYS).catch(() => {});
|
|
||||||
} else {
|
|
||||||
keyboard.unlock();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener("pointerlockerror", () => {
|
|
||||||
this.pointer_lock_waiting = false;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static is_key_down(code: KeyCode): boolean {
|
static is_key_down(code: KeyCode): boolean {
|
||||||
@@ -306,12 +220,6 @@ export class InputManager {
|
|||||||
this.mouse_buttons_consumed.add(button);
|
this.mouse_buttons_consumed.add(button);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it
|
|
||||||
// isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl
|
|
||||||
static #is_shortcut(e: KeyboardEvent) {
|
|
||||||
return e.metaKey || (e.ctrlKey && !e.altKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
static is_shortcut_pressed(letter: string): boolean {
|
static is_shortcut_pressed(letter: string): boolean {
|
||||||
return this.shortcuts.includes(letter);
|
return this.shortcuts.includes(letter);
|
||||||
}
|
}
|
||||||
@@ -337,83 +245,21 @@ export class InputManager {
|
|||||||
this.mouse_buttons_consumed.clear();
|
this.mouse_buttons_consumed.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
static async set_mouse_grabbed(grab: boolean) {
|
// the game calls this every frame
|
||||||
this.pointer_lock_flag = grab;
|
static set_mouse_grabbed(grab: boolean) {
|
||||||
this.#want_grab = grab;
|
platform.set_mouse_grabbed(grab);
|
||||||
// a retry to grab it again mustn't happen once it shouldn't be grabbed
|
|
||||||
if (!grab && this.mouse_ungrab_timeout !== -1) {
|
|
||||||
self.clearTimeout(this.mouse_ungrab_timeout);
|
|
||||||
this.mouse_ungrab_timeout = -1;
|
|
||||||
}
|
|
||||||
// already how it should be, the game calls this every frame
|
|
||||||
const locked = document.pointerLockElement === canvas;
|
|
||||||
if (grab ? locked : !locked && !this.pointer_lock_waiting) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (grab) {
|
|
||||||
// called every frame, once is enough
|
|
||||||
if (this.#awaiting_centering) return;
|
|
||||||
this.#awaiting_centering = true;
|
|
||||||
await this.#centering;
|
|
||||||
this.#awaiting_centering = false;
|
|
||||||
// a gui opened again meanwhile
|
|
||||||
if (!this.#want_grab || document.pointerLockElement === canvas) return;
|
|
||||||
}
|
|
||||||
const t = performance.now();
|
|
||||||
this.mouse_grab_timer = t;
|
|
||||||
if (grab) {
|
|
||||||
this.mouse_x = -1;
|
|
||||||
this.mouse_y = -1;
|
|
||||||
this.pointer_lock_waiting = true;
|
|
||||||
try {
|
|
||||||
await canvas.requestPointerLock();
|
|
||||||
} catch (_) { /* */ }
|
|
||||||
if (this.mouse_ungrab_timeout !== -1) {
|
|
||||||
self.clearTimeout(this.mouse_ungrab_timeout);
|
|
||||||
}
|
|
||||||
this.mouse_ungrab_timeout = -1;
|
|
||||||
if (t - this.mouse_ungrab_timer < 3000) {
|
|
||||||
this.mouse_ungrab_timeout = self.setTimeout(async () => {
|
|
||||||
try {
|
|
||||||
await canvas.requestPointerLock();
|
|
||||||
} catch (_) { /* */ }
|
|
||||||
}, 3100 - (t - this.mouse_ungrab_timer));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (!this.pointer_lock_waiting) {
|
|
||||||
document.exitPointerLock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// whether the mouse was taken away since the last call, browsers eat the escape that does it
|
// whether the mouse was taken away since the last call, like browsers do with escape
|
||||||
static take_lost_pointer_lock() {
|
static take_lost_pointer_lock() {
|
||||||
const lost = this.#lost_pointer_lock;
|
return platform.take_lost_mouse();
|
||||||
this.#lost_pointer_lock = false;
|
|
||||||
return lost;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static is_mouse_grabbed() {
|
static is_mouse_grabbed() {
|
||||||
return document.hasFocus() && document.pointerLockElement === canvas;
|
return platform.is_mouse_grabbed();
|
||||||
}
|
}
|
||||||
|
|
||||||
static toggle_fullscreen() {
|
static toggle_fullscreen() {
|
||||||
if (!document.fullscreenElement) {
|
platform.toggle_fullscreen();
|
||||||
canvas.requestFullscreen();
|
|
||||||
} else {
|
|
||||||
document.exitFullscreen();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const CENTERING_TIMEOUT_MS = 250;
|
|
||||||
const CENTERING_SETTLE_MS = 100;
|
|
||||||
|
|
||||||
// the desktop app (the page has ?singleplayer there, see desktop/main.ts) moves the cursor to the middle of the
|
|
||||||
// window when the mouse is let go to open a gui, like minecraft. chromium would put it back where it was grabbed.
|
|
||||||
// resolves once the cursor was moved, or after CENTERING_TIMEOUT_MS if the app is slow, so grabbing isn't held up
|
|
||||||
function center_desktop_mouse(): Promise<void> {
|
|
||||||
if (!new URL(location.href).searchParams.has("singleplayer")) return Promise.resolve();
|
|
||||||
const moved = fetch("/desktop/center_mouse", { method: "POST" }).then(() => {}, () => {});
|
|
||||||
return Promise.race([moved, new Promise<void>((resolve) => self.setTimeout(resolve, CENTERING_TIMEOUT_MS))]);
|
|
||||||
}
|
|
||||||
|
|||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { Container, Cursor } from "$/common/inventory.ts";
|
import { Container, Cursor } from "@/common/inventory.ts";
|
||||||
import type { MenuSlotInfo } from "$/common/protocol.ts";
|
import type { MenuSlotInfo } from "@/common/protocol.ts";
|
||||||
|
|
||||||
// the local copies of the containers the server syncs to this player
|
// the local copies of the containers the server syncs to this player
|
||||||
export class ClientInventories {
|
export class ClientInventories {
|
||||||
|
|||||||
+311
-230
@@ -8,29 +8,31 @@ import {
|
|||||||
fluid_block,
|
fluid_block,
|
||||||
fluid_in_cell,
|
fluid_in_cell,
|
||||||
is_waterlogged,
|
is_waterlogged,
|
||||||
} from "$/common/utils.ts";
|
} from "@/common/utils.ts";
|
||||||
import { AIR_ID } from "$/common/protocol.ts";
|
import { AIR_ID } from "@/common/protocol.ts";
|
||||||
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
|
import { decode_level_chunk } from "@/common/chunk_streaming.ts";
|
||||||
import { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "$/common/worldgen/biome_colors.ts";
|
import { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "@/common/worldgen/biome_colors.ts";
|
||||||
import {
|
import {
|
||||||
block_light_emission,
|
|
||||||
block_light_opacity,
|
|
||||||
BlockRegistry,
|
BlockRegistry,
|
||||||
EverythingRegistry,
|
EverythingRegistry,
|
||||||
is_fluid_block,
|
is_fluid_block,
|
||||||
RENDER_LAYERS,
|
light_tables,
|
||||||
RenderLayer,
|
RenderLayer,
|
||||||
} from "$/common/everything_registry.ts";
|
} from "@/common/everything_registry.ts";
|
||||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
|
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
|
||||||
|
import { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
|
||||||
|
import { ChunkColumn, column_heights, section_index, type SectionBiomes, type SectionData } from "@/common/section.ts";
|
||||||
import { AssetManager } from "../assets.ts";
|
import { AssetManager } from "../assets.ts";
|
||||||
import { ChunkWorkerPool } from "../chunk_workers.ts";
|
import { ChunkWorkerPool } from "../chunk_workers.ts";
|
||||||
import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts";
|
import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts";
|
||||||
import { create_index_buffer, create_vertex_buffer, destroy_buffer, Texture } from "../renderer/mod.ts";
|
import { create_index_buffer, create_vertex_buffer, destroy_buffer, render_debug, Texture } from "../renderer/mod.ts";
|
||||||
import { crosses_planes } from "../workers/translucent_sort.ts";
|
import { crosses_planes } from "../workers/translucent_sort.ts";
|
||||||
|
import { ALL_VISIBLE } from "../workers/visibility.ts";
|
||||||
|
import { region_key, REGION_LAYERS, type RegionLayer, RenderRegion } from "./render_region.ts";
|
||||||
import { Camera } from "../camera.ts";
|
import { Camera } from "../camera.ts";
|
||||||
import type { Entity } from "../entity/entity.ts";
|
import type { Entity } from "../entity/entity.ts";
|
||||||
import type { ModelJson } from "$/common/block_models.ts";
|
import type { ModelJson } from "@/common/block_models.ts";
|
||||||
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "$/common/block_shapes.ts";
|
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "@/common/block_shapes.ts";
|
||||||
import { BlockPredictions } from "./block_predictions.ts";
|
import { BlockPredictions } from "./block_predictions.ts";
|
||||||
import { block_visuals, Visuals } from "../rendering/visuals.ts";
|
import { block_visuals, Visuals } from "../rendering/visuals.ts";
|
||||||
|
|
||||||
@@ -41,36 +43,56 @@ export interface Block {
|
|||||||
z: number;
|
z: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE };
|
export { CHUNK_AREA, CHUNK_SIZE };
|
||||||
|
|
||||||
export interface Chunk {
|
export interface Chunk {
|
||||||
x: number;
|
x: number;
|
||||||
z: number;
|
z: number;
|
||||||
blocks: Uint32Array;
|
// its blocks and each column's biome, as the server sent them
|
||||||
dirty: boolean;
|
column: ChunkColumn;
|
||||||
|
// each column's lowest y that sees the sky, see column_heights in common/section.ts. kept up to date with its blocks
|
||||||
|
sky: Int16Array;
|
||||||
|
// one for each of its sections, from the bottom of the world up
|
||||||
|
sections: RenderSection[];
|
||||||
|
// each of its biome palette's grass, foliage and water colors, three numbers a biome
|
||||||
|
biome_colors: Uint32Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a chunk's section as it's drawn, like sodium's RenderSection. each is meshed and lit on its own
|
||||||
|
export interface RenderSection {
|
||||||
|
chunk: Chunk;
|
||||||
|
// in its chunk, from the bottom of the world up
|
||||||
|
index: number;
|
||||||
// bumped on every mesh request so late results from older requests get ignored
|
// bumped on every mesh request so late results from older requests get ignored
|
||||||
mesh_version: number;
|
mesh_version: number;
|
||||||
meshes: Partial<Record<RenderLayer, ChunkMesh>>;
|
meshes: Partial<Record<RenderLayer, ChunkMesh>>;
|
||||||
// the lowest and highest y of its meshes, for frustum culling
|
// the lowest and highest y of its quads and visuals, for frustum culling. Infinity and -Infinity when it has none
|
||||||
min_y: number;
|
min_y: number;
|
||||||
max_y: number;
|
max_y: number;
|
||||||
// only for translucent meshes that have to be sorted again as the camera moves
|
// only for translucent meshes that have to be sorted again as the camera moves
|
||||||
translucent_sort?: TranslucentSort;
|
translucent_sort?: TranslucentSort;
|
||||||
// each column's biome id, x then z
|
|
||||||
biomes: string[];
|
|
||||||
// each column's biome grass color, x then z, then each column's foliage color, then water color
|
|
||||||
biome_colors: Uint32Array;
|
|
||||||
// from its last mesh, see get_light. undefined until it's been meshed
|
// from its last mesh, see get_light. undefined until it's been meshed
|
||||||
light?: Uint8Array;
|
light?: SectionLight;
|
||||||
|
// from its last mesh, which faces see which, see client/workers/visibility.ts. all of them until it's been meshed
|
||||||
|
visibility: number;
|
||||||
|
// the last search for what the camera can see that reached it, and the faces it was reached through, see
|
||||||
|
// client/rendering/occlusion.ts
|
||||||
|
search: number;
|
||||||
|
incoming: number;
|
||||||
|
// where its solid and cutout quads are, see render_region.ts
|
||||||
|
region: RenderRegion;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ChunkMesh {
|
export interface ChunkMesh {
|
||||||
vertex_buffer: GPUBuffer;
|
|
||||||
quad_count: number;
|
quad_count: number;
|
||||||
// the translucent layer's quads sorted back to front, the others are drawn in order
|
|
||||||
index_buffer?: GPUBuffer;
|
|
||||||
// solid and cutout quads by the way they face, see FACE_GROUPS in chunk_messages.ts
|
// solid and cutout quads by the way they face, see FACE_GROUPS in chunk_messages.ts
|
||||||
groups?: FaceGroup[];
|
groups?: FaceGroup[];
|
||||||
|
// the section's own buffer, the translucent layer's quads sorted back to front by index_buffer. solid and cutout
|
||||||
|
// quads are in its region's buffer instead with the render_regions switch on, see render_region.ts, and slot is
|
||||||
|
// the section's place in the order the region's sections are in it
|
||||||
|
vertex_buffer?: GPUBuffer;
|
||||||
|
index_buffer?: GPUBuffer;
|
||||||
|
slot?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TranslucentSort {
|
interface TranslucentSort {
|
||||||
@@ -106,23 +128,32 @@ export interface BlockData {
|
|||||||
data: Record<string, unknown>;
|
data: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1]] as const;
|
// light spreads diagonally too, so meshing and lighting need all 8 neighbors
|
||||||
// light spreads diagonally too, so meshing and lighting need all 8
|
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
|
||||||
const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
|
// how far a change in light reaches, and one more for the faces at its edge, whose corners are lit from beyond them
|
||||||
|
const LIGHT_REACH = 16;
|
||||||
// how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client
|
// how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client
|
||||||
// which ones to forget, this only catches the ones it didn't
|
// which ones to forget, this only catches the ones it didn't
|
||||||
const STORAGE_MARGIN = 3;
|
const STORAGE_MARGIN = 3;
|
||||||
// block light 0 and sky light 15, packed like Chunk.light
|
|
||||||
export const FULL_SKY_LIGHT = 15;
|
|
||||||
|
|
||||||
// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it. the
|
// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it. the
|
||||||
// chunks are what the server sent, see common/chunk_streaming.ts
|
// chunks are what the server sent, see common/chunk_streaming.ts
|
||||||
export class ClientLevel {
|
export class ClientLevel {
|
||||||
image: Texture = AssetManager.instance.get("bworld:textures");
|
image: Texture = AssetManager.instance.get("cubi:textures");
|
||||||
chunks = new Map<number, Chunk>();
|
chunks = new Map<number, Chunk>();
|
||||||
// the chunks request_meshes and update_translucent_sorting look at, so they don't go through every chunk each frame
|
// the sections request_meshes and update_translucent_sorting look at, so they don't go through every one each
|
||||||
#dirty = new Set<Chunk>();
|
// frame. dirty ones by chunk, since a chunk's go in one request
|
||||||
#sorted = new Set<Chunk>();
|
#dirty = new Map<Chunk, Set<RenderSection>>();
|
||||||
|
#sorted = new Set<RenderSection>();
|
||||||
|
// the sections with quads or visuals, the only ones there are to draw
|
||||||
|
drawn = new Set<RenderSection>();
|
||||||
|
// by region_key, and the ones whose sections' meshes changed since update_regions
|
||||||
|
regions = new Map<number, RenderRegion>();
|
||||||
|
#changed_regions = new Set<RenderRegion>();
|
||||||
|
// whether solid and cutout quads go in their regions' buffers, see use_render_regions
|
||||||
|
#render_regions = render_debug.render_regions;
|
||||||
|
// bumped whenever a chunk comes or goes or a section is meshed, which can change what the camera sees
|
||||||
|
sections_version = 0;
|
||||||
second_timer = 0;
|
second_timer = 0;
|
||||||
tick_timer = 0;
|
tick_timer = 0;
|
||||||
// world time in ticks, counted here between the server's updates. see common/time.ts
|
// world time in ticks, counted here between the server's updates. see common/time.ts
|
||||||
@@ -131,6 +162,8 @@ export class ClientLevel {
|
|||||||
ticks = 0;
|
ticks = 0;
|
||||||
// in chunks, what the server was asked to send
|
// in chunks, what the server was asked to send
|
||||||
view_distance: number;
|
view_distance: number;
|
||||||
|
// the dimension's height and sky light
|
||||||
|
readonly shape: WorldShape;
|
||||||
// the chunk the server says the player is in
|
// the chunk the server says the player is in
|
||||||
center: { x: number; z: number } | undefined;
|
center: { x: number; z: number } | undefined;
|
||||||
// what this client changed ahead of the server, see MultiPlayerGameMode.predict
|
// what this client changed ahead of the server, see MultiPlayerGameMode.predict
|
||||||
@@ -138,6 +171,7 @@ export class ClientLevel {
|
|||||||
|
|
||||||
workers: ChunkWorkerPool;
|
workers: ChunkWorkerPool;
|
||||||
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
||||||
|
#light = light_tables(this.#blocks);
|
||||||
// the server's numeric block ids to this client's
|
// the server's numeric block ids to this client's
|
||||||
#to_local: Uint32Array;
|
#to_local: Uint32Array;
|
||||||
|
|
||||||
@@ -151,8 +185,9 @@ export class ClientLevel {
|
|||||||
break_progress = new Map<string, { x: number; y: number; z: number; stage: number }>();
|
break_progress = new Map<string, { x: number; y: number; z: number; stage: number }>();
|
||||||
|
|
||||||
// server_blocks is the server's block id for each of its numeric ids
|
// server_blocks is the server's block id for each of its numeric ids
|
||||||
constructor(server_blocks: string[], view_distance: number) {
|
constructor(server_blocks: string[], shape: WorldShape, view_distance: number) {
|
||||||
this.view_distance = view_distance;
|
this.view_distance = view_distance;
|
||||||
|
this.shape = shape;
|
||||||
this.#to_local = new Uint32Array(server_blocks.length);
|
this.#to_local = new Uint32Array(server_blocks.length);
|
||||||
server_blocks.forEach((id, nid) => {
|
server_blocks.forEach((id, nid) => {
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
@@ -170,9 +205,10 @@ export class ClientLevel {
|
|||||||
type: "init",
|
type: "init",
|
||||||
blocks_registry: strip_functions(EverythingRegistry.get_registry<BlockRegistry>("blocks")),
|
blocks_registry: strip_functions(EverythingRegistry.get_registry<BlockRegistry>("blocks")),
|
||||||
models: Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")),
|
models: Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")),
|
||||||
textures_info: AssetManager.instance.get("bworld:textures_info"),
|
textures_info: AssetManager.instance.get("cubi:textures_info"),
|
||||||
image: { width: this.image.width, height: this.image.height },
|
image: { width: this.image.width, height: this.image.height },
|
||||||
visuals: [...block_visuals].map(([nid, visual]) => [nid, visual.replaces_model]),
|
visuals: [...block_visuals].map(([nid, visual]) => [nid, visual.replaces_model]),
|
||||||
|
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,55 +231,60 @@ export class ClientLevel {
|
|||||||
|
|
||||||
// a level_chunk from the server: the whole chunk, replacing it if it was already here
|
// a level_chunk from the server: the whole chunk, replacing it if it was already here
|
||||||
load_chunk(data: Uint8Array) {
|
load_chunk(data: Uint8Array) {
|
||||||
const { x, z, blocks, biomes } = decode_level_chunk(
|
const { x, z, sections, biomes } = decode_level_chunk(
|
||||||
data,
|
data,
|
||||||
(value) => this.#to_local[value & ID_MASK] | (value & ~ID_MASK),
|
(value) => this.#to_local[value & ID_MASK] | (value & ~ID_MASK),
|
||||||
);
|
);
|
||||||
if (!this.#in_storage_range(x, z)) {
|
if (!this.#in_storage_range(x, z)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.set_chunk(x, z, blocks, biomes);
|
// throws when it isn't as tall as the dimension
|
||||||
|
this.set_chunk(new ChunkColumn(x, z, this.shape, sections, biomes));
|
||||||
}
|
}
|
||||||
|
|
||||||
// a whole chunk, replacing it if it was already here. blocks are this client's numeric ids with their state bits
|
// a whole chunk, replacing it if it was already here. its blocks are this client's numeric ids with their state bits
|
||||||
set_chunk(x: number, z: number, blocks: Uint32Array, biomes: string[]) {
|
set_chunk(column: ChunkColumn) {
|
||||||
const biome_colors = new Uint32Array(CHUNK_AREA * 3);
|
const { x, z } = column;
|
||||||
biomes.forEach((biome, column) => {
|
const biome_colors = Uint32Array.from(
|
||||||
biome_colors[column] = grass_color(biome);
|
column.biomes.palette.flatMap((biome) => [grass_color(biome), foliage_color(biome), water_color(biome)]),
|
||||||
biome_colors[CHUNK_AREA + column] = foliage_color(biome);
|
);
|
||||||
biome_colors[CHUNK_AREA * 2 + column] = water_color(biome);
|
|
||||||
});
|
const sky = column_heights(column, this.#light.opacity).slice(CHUNK_AREA);
|
||||||
|
|
||||||
const chunk = this.get_chunk(x, z);
|
const chunk = this.get_chunk(x, z);
|
||||||
if (chunk) {
|
if (chunk) {
|
||||||
// its old mesh stays up until the new one is ready
|
// its old meshes stay up until the new ones are ready
|
||||||
chunk.blocks = blocks;
|
chunk.column = column;
|
||||||
chunk.biomes = biomes;
|
chunk.sky = sky;
|
||||||
chunk.biome_colors = biome_colors;
|
chunk.biome_colors = biome_colors;
|
||||||
this.#mark_dirty(chunk);
|
|
||||||
} else {
|
} else {
|
||||||
const chunk: Chunk = {
|
const chunk: Chunk = { x, z, column, sky, biome_colors, sections: [] };
|
||||||
x,
|
for (let index = 0; index < column.sections.length; index++) {
|
||||||
z,
|
const key = region_key(x, index, z);
|
||||||
blocks,
|
let region = this.regions.get(key);
|
||||||
biomes,
|
if (!region) {
|
||||||
biome_colors,
|
region = new RenderRegion();
|
||||||
dirty: true,
|
this.regions.set(key, region);
|
||||||
|
}
|
||||||
|
region.section_count += 1;
|
||||||
|
chunk.sections.push({
|
||||||
|
chunk,
|
||||||
|
index,
|
||||||
mesh_version: 0,
|
mesh_version: 0,
|
||||||
meshes: {},
|
meshes: {},
|
||||||
min_y: 0,
|
min_y: Infinity,
|
||||||
max_y: 0,
|
max_y: -Infinity,
|
||||||
};
|
visibility: ALL_VISIBLE,
|
||||||
|
search: 0,
|
||||||
|
incoming: 0,
|
||||||
|
region,
|
||||||
|
});
|
||||||
|
}
|
||||||
this.chunks.set(chunk_key(x, z), chunk);
|
this.chunks.set(chunk_key(x, z), chunk);
|
||||||
this.#dirty.add(chunk);
|
this.sections_version += 1;
|
||||||
}
|
|
||||||
// their border faces and light depend on this one
|
|
||||||
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
|
|
||||||
const neighbor = this.get_chunk(x + dx, z + dz);
|
|
||||||
if (neighbor) {
|
|
||||||
this.#mark_dirty(neighbor);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// and its neighbors, whose border faces and light depend on it
|
||||||
|
this.#mark_dirty_around(x, z, this.shape.min_y, this.shape.max_y);
|
||||||
}
|
}
|
||||||
|
|
||||||
// the server moved the player's view, chunks far outside it go even if the server didn't say
|
// the server moved the player's view, chunks far outside it go even if the server didn't say
|
||||||
@@ -266,11 +307,15 @@ export class ClientLevel {
|
|||||||
dispose() {
|
dispose() {
|
||||||
this.workers.terminate();
|
this.workers.terminate();
|
||||||
for (const chunk of this.chunks.values()) {
|
for (const chunk of this.chunks.values()) {
|
||||||
this.delete_chunk_mesh(chunk);
|
for (const section of chunk.sections) this.#delete_mesh(section);
|
||||||
}
|
}
|
||||||
this.visuals.dispose();
|
this.visuals.dispose();
|
||||||
|
for (const region of this.regions.values()) region.dispose();
|
||||||
|
this.regions.clear();
|
||||||
|
this.#changed_regions.clear();
|
||||||
this.chunks.clear();
|
this.chunks.clear();
|
||||||
this.#dirty.clear();
|
this.#dirty.clear();
|
||||||
|
this.drawn.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
get_chunk(x: number, z: number) {
|
get_chunk(x: number, z: number) {
|
||||||
@@ -286,34 +331,30 @@ export class ClientLevel {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!this.shape.contains(block.y)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
|
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
|
||||||
this.#retain(block.x, block.y, block.z);
|
this.#retain(block.x, block.y, block.z);
|
||||||
|
|
||||||
const lx = block.x - block_chunk_x * CHUNK_SIZE;
|
const old_nid = chunk.column.get(block.x, block.y, block.z) & ID_MASK;
|
||||||
const lz = block.z - block_chunk_z * CHUNK_SIZE;
|
const value = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
|
||||||
const ly = block.y;
|
chunk.column.set(block.x, block.y, block.z, value);
|
||||||
|
this.#block_changed(chunk, block.x, block.y, block.z, old_nid, nid);
|
||||||
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
|
|
||||||
|
|
||||||
const old_nid = chunk.blocks[index] & ID_MASK;
|
|
||||||
chunk.blocks[index] = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
|
|
||||||
this.#mark_dirty(chunk);
|
|
||||||
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// block light << 4 | sky light there, as of its chunk's last mesh. full sky light above the world and where it isn't
|
// block light << 4 | sky light there, as of its section's last mesh. the shape's open light (full sky light, unless
|
||||||
// known yet, so entities don't go dark while their chunk loads
|
// the dimension has none) above the world and where it isn't known yet, so entities don't go dark while their
|
||||||
|
// chunk loads
|
||||||
get_light(x: number, y: number, z: number): number {
|
get_light(x: number, y: number, z: number): number {
|
||||||
const block_y = Math.floor(y);
|
const block_y = Math.floor(y);
|
||||||
if (block_y >= CHUNK_HEIGHT) return FULL_SKY_LIGHT;
|
if (block_y >= this.shape.max_y) return this.shape.open_light;
|
||||||
if (block_y < 0) return 0;
|
if (block_y < this.shape.min_y) return 0;
|
||||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
|
||||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
const light = chunk?.sections[(block_y - this.shape.min_y) >> 4].light;
|
||||||
const light = this.get_chunk(chunk_x, chunk_z)?.light;
|
if (light === undefined) return this.shape.open_light;
|
||||||
if (!light) return FULL_SKY_LIGHT;
|
return typeof light === "number" ? light : light[section_index(Math.floor(x), block_y, Math.floor(z))];
|
||||||
const lx = Math.floor(x) - chunk_x * CHUNK_SIZE;
|
|
||||||
const lz = Math.floor(z) - chunk_z * CHUNK_SIZE;
|
|
||||||
return light[block_y * CHUNK_AREA + lz * CHUNK_SIZE + lx];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// the id with its state bits, VOID outside loaded chunks
|
// the id with its state bits, VOID outside loaded chunks
|
||||||
@@ -324,8 +365,7 @@ export class ClientLevel {
|
|||||||
if (!chunk) {
|
if (!chunk) {
|
||||||
return VOID;
|
return VOID;
|
||||||
}
|
}
|
||||||
return chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)] ??
|
return chunk.column.get(x, y, z);
|
||||||
AIR;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get_block(x: number, y: number, z: number) {
|
get_block(x: number, y: number, z: number) {
|
||||||
@@ -337,14 +377,7 @@ export class ClientLevel {
|
|||||||
if (!chunk) {
|
if (!chunk) {
|
||||||
return VOID;
|
return VOID;
|
||||||
}
|
}
|
||||||
|
return chunk.column.get(x, y, z) & ID_MASK;
|
||||||
const lx = x - chunk_x * CHUNK_SIZE;
|
|
||||||
const lz = z - chunk_z * CHUNK_SIZE;
|
|
||||||
const ly = y;
|
|
||||||
|
|
||||||
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
|
|
||||||
|
|
||||||
return chunk.blocks[index] & ID_MASK;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// whether entities bump into the block there. unloaded chunks count as solid, so nothing falls out of the world
|
// whether entities bump into the block there. unloaded chunks count as solid, so nothing falls out of the world
|
||||||
@@ -363,22 +396,17 @@ export class ClientLevel {
|
|||||||
return block ? collision_shape_at(block, value) : true;
|
return block ? collision_shape_at(block, value) : true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// the column's biome, undefined in unloaded chunks
|
// the biome at a block, undefined in unloaded chunks
|
||||||
biome_at(x: number, z: number): string | undefined {
|
biome_at(x: number, y: number, z: number): string | undefined {
|
||||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
return this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE))?.column.biome_at(x, y, z);
|
||||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
|
||||||
return this.get_chunk(chunk_x, chunk_z)
|
|
||||||
?.biomes[(z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// the biome's water color at a column as 0xRRGGBB, see "tint". plains' in unloaded chunks
|
// the biome's water color at a block as 0xRRGGBB, see "tint". plains' in unloaded chunks
|
||||||
water_color(x: number, z: number) {
|
water_color(x: number, y: number, z: number) {
|
||||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
|
||||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
|
||||||
const chunk = this.get_chunk(chunk_x, chunk_z);
|
|
||||||
if (!chunk) return DEFAULT_WATER_COLOR;
|
if (!chunk) return DEFAULT_WATER_COLOR;
|
||||||
return chunk
|
const biome = chunk.column.biomes.palette.indexOf(chunk.column.biome_at(x, y, z));
|
||||||
.biome_colors[CHUNK_AREA * 2 + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
|
return chunk.biome_colors[biome * 3 + 2];
|
||||||
}
|
}
|
||||||
|
|
||||||
// the fluid there and how high it is, for fluids pushing things along. unloaded chunks have none
|
// the fluid there and how high it is, for fluids pushing things along. unloaded chunks have none
|
||||||
@@ -400,86 +428,68 @@ export class ClientLevel {
|
|||||||
const block_chunk_x = Math.floor(x / CHUNK_SIZE);
|
const block_chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||||
const block_chunk_z = Math.floor(z / CHUNK_SIZE);
|
const block_chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||||
const chunk = this.get_chunk(block_chunk_x, block_chunk_z);
|
const chunk = this.get_chunk(block_chunk_x, block_chunk_z);
|
||||||
if (!chunk) {
|
if (!chunk || !this.shape.contains(y)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.#retain(x, y, z);
|
this.#retain(x, y, z);
|
||||||
|
|
||||||
const lx = x - block_chunk_x * CHUNK_SIZE;
|
const old_value = chunk.column.get(x, y, z);
|
||||||
const lz = z - block_chunk_z * CHUNK_SIZE;
|
|
||||||
const ly = y;
|
|
||||||
|
|
||||||
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
|
|
||||||
const old_value = chunk.blocks[index];
|
|
||||||
const old_nid = old_value & ID_MASK;
|
const old_nid = old_value & ID_MASK;
|
||||||
const old_block = this.#blocks[old_nid];
|
const old_block = this.#blocks[old_nid];
|
||||||
// a waterlogged block leaves its fluid, like the server's destroy_block
|
// a waterlogged block leaves its fluid, like the server's destroy_block
|
||||||
const fluid = is_waterlogged(old_value, old_block)
|
const fluid = is_waterlogged(old_value, old_block)
|
||||||
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
|
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
|
||||||
: AIR;
|
: AIR;
|
||||||
chunk.blocks[index] = fluid;
|
chunk.column.set(x, y, z, fluid);
|
||||||
this.#mark_dirty(chunk);
|
this.#block_changed(chunk, x, y, z, old_nid, fluid);
|
||||||
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, fluid);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// a block that lets through or gives off a different amount of light changes the light up to 15 blocks
|
// what a block changing remeshes: its section, and the ones beside it when it's on their border. a block that lets
|
||||||
// away, so in every neighbor. otherwise only a block on a chunk's edge matters, for its neighbor's faces
|
// through or gives off a different amount of light changes the light up to 15 blocks away, so in every section
|
||||||
#mark_neighbors_dirty(
|
// around it, and when it moves its column's sky height, from the old height to the new one in the columns around
|
||||||
block_chunk_x: number,
|
#block_changed(chunk: Chunk, x: number, y: number, z: number, old_nid: number, new_nid: number) {
|
||||||
block_chunk_z: number,
|
const { opacity, emission } = this.#light;
|
||||||
lx: number,
|
if (opacity[old_nid] !== opacity[new_nid] || emission[old_nid] !== emission[new_nid]) {
|
||||||
lz: number,
|
const column = (z & 15) * CHUNK_SIZE + (x & 15);
|
||||||
old_nid: number,
|
const old_sky = chunk.sky[column];
|
||||||
new_nid: number,
|
chunk.sky = column_heights(chunk.column, opacity).slice(CHUNK_AREA);
|
||||||
) {
|
const new_sky = chunk.sky[column];
|
||||||
const old_block = this.#blocks[old_nid];
|
const changed = old_sky === new_sky ? [y] : [y, old_sky, new_sky];
|
||||||
const new_block = this.#blocks[new_nid];
|
this.#mark_dirty_around(
|
||||||
if (
|
chunk.x,
|
||||||
block_light_opacity(old_block) !== block_light_opacity(new_block) ||
|
chunk.z,
|
||||||
block_light_emission(old_block) !== block_light_emission(new_block)
|
Math.min(...changed) - LIGHT_REACH,
|
||||||
) {
|
Math.max(...changed) + LIGHT_REACH,
|
||||||
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
|
);
|
||||||
const n = this.get_chunk(block_chunk_x + dx, block_chunk_z + dz);
|
|
||||||
if (n) {
|
|
||||||
this.#mark_dirty(n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lx === 0) {
|
// the way to the neighbor on each axis whose faces it's next to, 0 for none
|
||||||
const n = this.get_chunk(block_chunk_x - 1, block_chunk_z);
|
const side = (local: number) => local === 0 ? -1 : local === CHUNK_SIZE - 1 ? 1 : 0;
|
||||||
if (n) {
|
const sx = side(x & 15);
|
||||||
this.#mark_dirty(n);
|
const sy = side((y - this.shape.min_y) & 15);
|
||||||
|
const sz = side(z & 15);
|
||||||
|
const index = (y - this.shape.min_y) >> 4;
|
||||||
|
for (const dx of new Set([0, sx])) {
|
||||||
|
for (const dz of new Set([0, sz])) {
|
||||||
|
const sections = this.get_chunk(chunk.x + dx, chunk.z + dz)?.sections;
|
||||||
|
for (const dy of new Set([0, sy])) {
|
||||||
|
const section = sections?.[index + dy];
|
||||||
|
if (section) this.#mark_dirty(section);
|
||||||
}
|
}
|
||||||
} else if (lx === CHUNK_SIZE - 1) {
|
|
||||||
const n = this.get_chunk(block_chunk_x + 1, block_chunk_z);
|
|
||||||
if (n) {
|
|
||||||
this.#mark_dirty(n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (lz === 0) {
|
|
||||||
const n = this.get_chunk(block_chunk_x, block_chunk_z - 1);
|
|
||||||
if (n) {
|
|
||||||
this.#mark_dirty(n);
|
|
||||||
}
|
|
||||||
} else if (lz === CHUNK_SIZE - 1) {
|
|
||||||
const n = this.get_chunk(block_chunk_x, block_chunk_z + 1);
|
|
||||||
if (n) {
|
|
||||||
this.#mark_dirty(n);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
index_to_xyz(index: number) {
|
// the sections from from_y to to_y of a chunk and the 8 around it
|
||||||
const y = Math.floor(index / CHUNK_AREA);
|
#mark_dirty_around(chunk_x: number, chunk_z: number, from_y: number, to_y: number) {
|
||||||
const rem = index % CHUNK_AREA;
|
const lowest = Math.max(0, (from_y - this.shape.min_y) >> 4);
|
||||||
|
for (const [dx, dz] of [[0, 0], ...NEIGHBOR_OFFSETS]) {
|
||||||
const z = Math.floor(rem / CHUNK_SIZE);
|
const sections = this.get_chunk(chunk_x + dx, chunk_z + dz)?.sections ?? [];
|
||||||
const x = rem % CHUNK_SIZE;
|
const highest = Math.min(sections.length - 1, (to_y - this.shape.min_y) >> 4);
|
||||||
|
for (let i = lowest; i <= highest; i++) this.#mark_dirty(sections[i]);
|
||||||
return [x, y, z];
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// set a block the server told us about. the server only sends them for chunks this client has. a block this
|
// set a block the server told us about. the server only sends them for chunks this client has. a block this
|
||||||
@@ -536,9 +546,19 @@ export class ClientLevel {
|
|||||||
if (!chunk) {
|
if (!chunk) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.delete_chunk_mesh(chunk);
|
for (const section of chunk.sections) {
|
||||||
this.chunks.delete(key);
|
this.#delete_mesh(section);
|
||||||
|
this.drawn.delete(section);
|
||||||
|
section.region.section_count -= 1;
|
||||||
|
if (section.region.section_count === 0) {
|
||||||
|
section.region.dispose();
|
||||||
|
this.regions.delete(region_key(cx, section.index, cz));
|
||||||
|
this.#changed_regions.delete(section.region);
|
||||||
|
}
|
||||||
|
}
|
||||||
this.#dirty.delete(chunk);
|
this.#dirty.delete(chunk);
|
||||||
|
this.chunks.delete(key);
|
||||||
|
this.sections_version += 1;
|
||||||
this.block_data.delete(key);
|
this.block_data.delete(key);
|
||||||
this.visuals.unload(cx, cz);
|
this.visuals.unload(cx, cz);
|
||||||
for (const [position, { x, z }] of this.break_progress) {
|
for (const [position, { x, z }] of this.break_progress) {
|
||||||
@@ -582,10 +602,10 @@ export class ClientLevel {
|
|||||||
return this.block_data.get(key)?.get(`${x},${y},${z}`)?.data;
|
return this.block_data.get(key)?.get(`${x},${y},${z}`)?.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be
|
// a chunk's sections are only meshed once all its neighbors exist, otherwise their border faces and light would be
|
||||||
// wrong and it would have to be meshed again as each neighbor loads
|
// wrong and they would have to be meshed again as each neighbor loads
|
||||||
can_mesh(chunk: Chunk) {
|
can_mesh(chunk: Chunk) {
|
||||||
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
|
for (const [dx, dz] of NEIGHBOR_OFFSETS) {
|
||||||
if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) {
|
if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -593,45 +613,61 @@ export class ClientLevel {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// meshes asked of the workers that haven't come back, for the f3 performance window
|
// mesh requests sent to the workers that haven't come back, for the f3 performance window. each is some sections of
|
||||||
|
// a chunk
|
||||||
meshes_in_flight = 0;
|
meshes_in_flight = 0;
|
||||||
// the rest wait for the next frame. chunks from the server come a few at a time, but the benchmark's level has every
|
// the rest wait for the next frame. chunks from the server come a few at a time, but the benchmark's level has every
|
||||||
// chunk at once, and each request copies its 3x3 chunks
|
// chunk at once, and each request copies the sections around the ones it's for
|
||||||
max_meshes_in_flight = Infinity;
|
max_meshes_in_flight = Infinity;
|
||||||
|
|
||||||
// dirty chunks that can be meshed and the meshes the workers are on, 0 once every chunk that can be is meshed
|
// requests for chunks with dirty sections that can be meshed, and the ones the workers are on. 0 once every
|
||||||
|
// section that can be is meshed
|
||||||
get meshes_pending() {
|
get meshes_pending() {
|
||||||
let pending = this.meshes_in_flight;
|
let pending = this.meshes_in_flight;
|
||||||
for (const chunk of this.#dirty) {
|
for (const chunk of this.#dirty.keys()) {
|
||||||
if (this.can_mesh(chunk)) pending += 1;
|
if (this.can_mesh(chunk)) pending += 1;
|
||||||
}
|
}
|
||||||
return pending;
|
return pending;
|
||||||
}
|
}
|
||||||
|
|
||||||
// meshes every chunk again, for the benchmark to time
|
// meshes every section again, for the benchmark to time
|
||||||
remesh_all() {
|
remesh_all() {
|
||||||
for (const chunk of this.chunks.values()) this.#mark_dirty(chunk);
|
for (const chunk of this.chunks.values()) {
|
||||||
|
for (const section of chunk.sections) this.#mark_dirty(section);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// sends every dirty chunk that can be meshed to the workers
|
// sends every dirty section that can be meshed to the workers, a request per chunk
|
||||||
request_meshes(camera: Camera) {
|
request_meshes(camera: Camera) {
|
||||||
for (const chunk of this.#dirty) {
|
for (const [chunk, sections] of this.#dirty) {
|
||||||
if (this.meshes_in_flight >= this.max_meshes_in_flight) {
|
if (this.meshes_in_flight >= this.max_meshes_in_flight) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!this.can_mesh(chunk)) {
|
if (!this.can_mesh(chunk)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
chunk.dirty = false;
|
|
||||||
this.#dirty.delete(chunk);
|
this.#dirty.delete(chunk);
|
||||||
chunk.mesh_version += 1;
|
let lowest = Infinity;
|
||||||
// copies, the worker lights the whole 3x3 area
|
let highest = -Infinity;
|
||||||
const chunks: (Uint32Array | null)[] = [];
|
for (const section of sections) {
|
||||||
|
section.mesh_version += 1;
|
||||||
|
lowest = Math.min(lowest, section.index);
|
||||||
|
highest = Math.max(highest, section.index);
|
||||||
|
}
|
||||||
|
// they're lit with the 3x3 chunks' sections from the one below them to the one above. posting copies the
|
||||||
|
// blocks, of only the sections that aren't all one block
|
||||||
|
const first = Math.max(0, lowest - 1);
|
||||||
|
const end = Math.min(chunk.sections.length, highest + 2);
|
||||||
|
const chunks: (SectionData[] | null)[] = [];
|
||||||
|
const sky: (Int16Array | null)[] = [];
|
||||||
|
const biomes: (SectionBiomes[] | null)[] = [];
|
||||||
const biome_colors: (Uint32Array | null)[] = [];
|
const biome_colors: (Uint32Array | null)[] = [];
|
||||||
for (let dz = -1; dz <= 1; dz++) {
|
for (let dz = -1; dz <= 1; dz++) {
|
||||||
for (let dx = -1; dx <= 1; dx++) {
|
for (let dx = -1; dx <= 1; dx++) {
|
||||||
const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz);
|
const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz);
|
||||||
chunks.push(neighbor?.blocks.slice() ?? null);
|
chunks.push(neighbor?.column.sections.slice(first, end).map((section) => section.data) ?? null);
|
||||||
|
sky.push(neighbor?.sky ?? null);
|
||||||
|
biomes.push(neighbor?.column.biomes.sections.slice(first, end) ?? null);
|
||||||
biome_colors.push(neighbor?.biome_colors ?? null);
|
biome_colors.push(neighbor?.biome_colors ?? null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -640,20 +676,23 @@ export class ClientLevel {
|
|||||||
type: "mesh",
|
type: "mesh",
|
||||||
chunk_x: chunk.x,
|
chunk_x: chunk.x,
|
||||||
chunk_z: chunk.z,
|
chunk_z: chunk.z,
|
||||||
version: chunk.mesh_version,
|
sections: [...sections].map((section) => ({ index: section.index, version: section.mesh_version })),
|
||||||
|
first,
|
||||||
chunks,
|
chunks,
|
||||||
|
sky,
|
||||||
|
biomes,
|
||||||
biome_colors,
|
biome_colors,
|
||||||
camera: [camera.x, camera.y, camera.z],
|
camera: [camera.x, camera.y, camera.z],
|
||||||
}, chunks.filter((blocks) => blocks !== null).map((blocks) => blocks.buffer));
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// like sodium, a chunk's translucent quads only change order when the camera crosses one of the
|
// like sodium, a section's translucent quads only change order when the camera crosses one of the planes they lie
|
||||||
// planes they lie on, so that's the only time they get sorted again
|
// on, so that's the only time they get sorted again
|
||||||
update_translucent_sorting(camera: Camera) {
|
update_translucent_sorting(camera: Camera) {
|
||||||
const position = [camera.x, camera.y, camera.z];
|
const position = [camera.x, camera.y, camera.z];
|
||||||
for (const chunk of this.#sorted) {
|
for (const section of this.#sorted) {
|
||||||
const sort = chunk.translucent_sort!;
|
const sort = section.translucent_sort!;
|
||||||
if (!crosses_planes(sort.planes, sort.camera, position)) {
|
if (!crosses_planes(sort.planes, sort.camera, position)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -661,8 +700,9 @@ export class ClientLevel {
|
|||||||
sort.requested += 1;
|
sort.requested += 1;
|
||||||
this.workers.post({
|
this.workers.post({
|
||||||
type: "sort",
|
type: "sort",
|
||||||
chunk_x: chunk.x,
|
chunk_x: section.chunk.x,
|
||||||
chunk_z: chunk.z,
|
chunk_z: section.chunk.z,
|
||||||
|
index: section.index,
|
||||||
version: sort.mesh_version,
|
version: sort.mesh_version,
|
||||||
sort_version: sort.requested,
|
sort_version: sort.requested,
|
||||||
centers: sort.centers,
|
centers: sort.centers,
|
||||||
@@ -682,34 +722,53 @@ export class ClientLevel {
|
|||||||
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
|
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
|
||||||
this.meshes_in_flight -= 1;
|
this.meshes_in_flight -= 1;
|
||||||
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
|
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
|
||||||
// unloaded, or remeshed again since this was requested
|
if (!chunk) {
|
||||||
if (!chunk || chunk.mesh_version !== message.version) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
for (const mesh of message.sections) {
|
||||||
|
const section = chunk.sections[mesh.index];
|
||||||
|
// remeshed again since this was requested
|
||||||
|
if (section.mesh_version !== mesh.version) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
this.#delete_mesh(section);
|
||||||
|
this.sections_version += 1;
|
||||||
|
section.light = mesh.light;
|
||||||
|
section.visibility = mesh.visibility;
|
||||||
|
section.min_y = mesh.min_y;
|
||||||
|
section.max_y = mesh.max_y;
|
||||||
|
// with no quads or visuals its bounds are empty
|
||||||
|
if (mesh.min_y <= mesh.max_y) this.drawn.add(section);
|
||||||
|
else this.drawn.delete(section);
|
||||||
|
this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y + section.index * SECTION_HEIGHT, mesh.visuals);
|
||||||
|
|
||||||
this.delete_chunk_mesh(chunk);
|
for (const layer of REGION_LAYERS) {
|
||||||
chunk.light = message.light;
|
const { vertices, quad_count, groups } = mesh[layer];
|
||||||
chunk.min_y = message.min_y;
|
|
||||||
chunk.max_y = message.max_y;
|
|
||||||
this.visuals.meshed(chunk.x, chunk.z, message.visuals);
|
|
||||||
|
|
||||||
for (const layer of RENDER_LAYERS) {
|
|
||||||
const { vertices, quad_count, groups } = message[layer];
|
|
||||||
if (quad_count === 0) {
|
if (quad_count === 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
chunk.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
|
if (this.#render_regions) {
|
||||||
|
section.meshes[layer] = { quad_count, groups };
|
||||||
|
section.region.meshed(layer, section, vertices);
|
||||||
|
this.#changed_regions.add(section.region);
|
||||||
|
} else {
|
||||||
|
section.meshes[layer] = { quad_count, groups, vertex_buffer: create_vertex_buffer(vertices) };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const translucent = message.translucent;
|
const translucent = mesh.translucent;
|
||||||
if (translucent.quad_count === 0) {
|
if (translucent.quad_count === 0) {
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
chunk.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices);
|
section.meshes.translucent = {
|
||||||
|
quad_count: translucent.quad_count,
|
||||||
|
vertex_buffer: create_vertex_buffer(translucent.vertices),
|
||||||
|
index_buffer: create_index_buffer(translucent.indices),
|
||||||
|
};
|
||||||
if (translucent.sort_type === "dynamic") {
|
if (translucent.sort_type === "dynamic") {
|
||||||
this.#sorted.add(chunk);
|
this.#sorted.add(section);
|
||||||
chunk.translucent_sort = {
|
section.translucent_sort = {
|
||||||
mesh_version: message.version,
|
mesh_version: mesh.version,
|
||||||
centers: translucent.centers,
|
centers: translucent.centers,
|
||||||
planes: translucent.planes,
|
planes: translucent.planes,
|
||||||
camera: message.camera,
|
camera: message.camera,
|
||||||
@@ -718,11 +777,12 @@ export class ClientLevel {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#on_sorted(message: Extract<FromChunkWorker, { type: "sorted" }>) {
|
#on_sorted(message: Extract<FromChunkWorker, { type: "sorted" }>) {
|
||||||
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
|
const section = this.get_chunk(message.chunk_x, message.chunk_z)?.sections[message.index];
|
||||||
const sort = chunk?.translucent_sort;
|
const sort = section?.translucent_sort;
|
||||||
const mesh = chunk?.meshes.translucent;
|
const mesh = section?.meshes.translucent;
|
||||||
// remeshed since, or a newer sort already came back
|
// remeshed since, or a newer sort already came back
|
||||||
if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) {
|
if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) {
|
||||||
return;
|
return;
|
||||||
@@ -734,26 +794,47 @@ export class ClientLevel {
|
|||||||
mesh.index_buffer = create_index_buffer(message.indices);
|
mesh.index_buffer = create_index_buffer(message.indices);
|
||||||
}
|
}
|
||||||
|
|
||||||
delete_chunk_mesh(chunk: Chunk) {
|
#delete_mesh(section: RenderSection) {
|
||||||
for (const mesh of Object.values(chunk.meshes)) {
|
for (const [layer, mesh] of Object.entries(section.meshes)) {
|
||||||
|
if (mesh.vertex_buffer) {
|
||||||
destroy_buffer(mesh.vertex_buffer);
|
destroy_buffer(mesh.vertex_buffer);
|
||||||
if (mesh.index_buffer) {
|
if (mesh.index_buffer) destroy_buffer(mesh.index_buffer);
|
||||||
destroy_buffer(mesh.index_buffer);
|
} else {
|
||||||
|
section.region.removed(layer as RegionLayer, section);
|
||||||
|
this.#changed_regions.add(section.region);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
chunk.meshes = {};
|
section.meshes = {};
|
||||||
chunk.translucent_sort = undefined;
|
section.translucent_sort = undefined;
|
||||||
this.#sorted.delete(chunk);
|
this.#sorted.delete(section);
|
||||||
}
|
}
|
||||||
|
|
||||||
// chunks that need meshing, some waiting on their neighbors to load
|
// render regions draw solid and cutout terrain in about a fifth of the draw calls, but in firefox that didn't make
|
||||||
|
// frames any faster and the gpu took longer, so they're the f3 window's render_regions switch, off by default.
|
||||||
|
// switching meshes everything again, each section's quads going in its own buffer or its region's as they come back
|
||||||
|
use_render_regions(on: boolean) {
|
||||||
|
if (on === this.#render_regions) return;
|
||||||
|
this.#render_regions = on;
|
||||||
|
this.remesh_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
// puts the buffers of the regions whose sections' solid or cutout quads changed together again, before they're drawn
|
||||||
|
update_regions() {
|
||||||
|
for (const region of this.#changed_regions) region.update();
|
||||||
|
this.#changed_regions.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// sections that need meshing, some waiting on their chunk's neighbors to load
|
||||||
get dirty_count() {
|
get dirty_count() {
|
||||||
return this.#dirty.size;
|
let count = 0;
|
||||||
|
for (const sections of this.#dirty.values()) count += sections.size;
|
||||||
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
#mark_dirty(chunk: Chunk) {
|
#mark_dirty(section: RenderSection) {
|
||||||
chunk.dirty = true;
|
const sections = this.#dirty.get(section.chunk);
|
||||||
this.#dirty.add(chunk);
|
if (sections) sections.add(section);
|
||||||
|
else this.#dirty.set(section.chunk, new Set([section]));
|
||||||
}
|
}
|
||||||
|
|
||||||
// the closest entity whose box is along the view of something at x/y/z looking at yaw/pitch, within max_distance.
|
// the closest entity whose box is along the view of something at x/y/z looking at yaw/pitch, within max_distance.
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// sections are drawn by region, like sodium's RenderRegion: the solid and cutout quads of 8x4x8 sections share one
|
||||||
|
// buffer per layer, so drawing them binds it once. webgpu has no multi-draw, so the buffer is laid out to need fewer
|
||||||
|
// draws instead: by face group, every section's quads facing up, then every section's facing down, and so on (see
|
||||||
|
// FACE_GROUPS). the sections in view whose group faces the camera are then mostly next to each other, and a run of
|
||||||
|
// them is one draw
|
||||||
|
import { copy_buffer, create_copyable_vertex_buffer, destroy_buffer, write_buffer } from "@/client/renderer/mod.ts";
|
||||||
|
import { FACE_GROUPS, TERRAIN_QUAD_BYTES } from "@/client/workers/chunk_messages.ts";
|
||||||
|
import type { RenderSection } from "./client_level.ts";
|
||||||
|
|
||||||
|
export const REGION_WIDTH = 8;
|
||||||
|
export const REGION_HEIGHT = 4;
|
||||||
|
|
||||||
|
export type RegionLayer = "solid" | "cutout";
|
||||||
|
export const REGION_LAYERS: RegionLayer[] = ["solid", "cutout"];
|
||||||
|
|
||||||
|
// a region by the chunk and section index of any section in it. a chunk coordinate is under 2^19, so a region's x and
|
||||||
|
// z are each under 2^16 either way, and a world is at most 256 sections tall, so its regions under 2^8
|
||||||
|
export function region_key(chunk_x: number, index: number, chunk_z: number) {
|
||||||
|
return ((chunk_x >> 3) + 65536) * 2 ** 25 + ((chunk_z >> 3) + 65536) * 2 ** 8 + (index >> 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// what a region does with its buffers, apart so tests can see what's in them without a gpu
|
||||||
|
export interface RegionBuffers {
|
||||||
|
create(size: number): GPUBuffer;
|
||||||
|
write(buffer: GPUBuffer, offset: number, data: Uint8Array<ArrayBuffer>, first: number, size: number): void;
|
||||||
|
// as from offset, to offset and size in bytes, three numbers each
|
||||||
|
copy(from: GPUBuffer, to: GPUBuffer, ranges: number[]): void;
|
||||||
|
destroy(buffer: GPUBuffer): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const GPU_BUFFERS: RegionBuffers = {
|
||||||
|
create: create_copyable_vertex_buffer,
|
||||||
|
write: write_buffer,
|
||||||
|
copy: copy_buffer,
|
||||||
|
destroy: destroy_buffer,
|
||||||
|
};
|
||||||
|
|
||||||
|
interface LayerBuffer {
|
||||||
|
buffer: GPUBuffer | undefined;
|
||||||
|
// its sections in the order their quads are in each group's part of the buffer
|
||||||
|
sections: RenderSection[];
|
||||||
|
// meshed since it was last put together, with their quads as the chunk worker sent them
|
||||||
|
meshed: Map<RenderSection, Uint8Array<ArrayBuffer>>;
|
||||||
|
// whether any of its sections were meshed or lost their quads since
|
||||||
|
changed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const empty_layer = (): LayerBuffer => ({ buffer: undefined, sections: [], meshed: new Map(), changed: false });
|
||||||
|
|
||||||
|
export class RenderRegion {
|
||||||
|
layers: Record<RegionLayer, LayerBuffer> = { solid: empty_layer(), cutout: empty_layer() };
|
||||||
|
// the loaded chunks' sections in it, so it goes when they do
|
||||||
|
section_count = 0;
|
||||||
|
|
||||||
|
constructor(readonly buffers = GPU_BUFFERS) {}
|
||||||
|
|
||||||
|
// a section's new quads in a layer, put in the buffer by the next update. section.meshes[layer].groups say where
|
||||||
|
// each group's quads are in vertices, and after the update where they are in the buffer
|
||||||
|
meshed(layer: RegionLayer, section: RenderSection, vertices: Uint8Array<ArrayBuffer>) {
|
||||||
|
this.layers[layer].meshed.set(section, vertices);
|
||||||
|
this.layers[layer].changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a section's quads in a layer went, the next update takes them out
|
||||||
|
removed(layer: RegionLayer, section: RenderSection) {
|
||||||
|
this.layers[layer].meshed.delete(section);
|
||||||
|
this.layers[layer].changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// puts each layer's buffer together again: a new one, with the quads of the sections that didn't change copied over
|
||||||
|
// from the old one on the gpu, and the new quads written to it. a section with no quads in a layer anymore isn't
|
||||||
|
// in it. only for regions whose sections changed since, see ClientLevel.update_regions
|
||||||
|
update() {
|
||||||
|
for (const layer of REGION_LAYERS) {
|
||||||
|
const old = this.layers[layer];
|
||||||
|
if (!old.changed) continue;
|
||||||
|
const sections = old.sections.filter((section) => section.meshes[layer] && !old.meshed.has(section));
|
||||||
|
sections.push(...old.meshed.keys());
|
||||||
|
|
||||||
|
// where each group of each section goes, group after group
|
||||||
|
const firsts = new Uint32Array(sections.length * FACE_GROUPS);
|
||||||
|
let quads = 0;
|
||||||
|
for (let g = 0; g < FACE_GROUPS; g++) {
|
||||||
|
for (let i = 0; i < sections.length; i++) {
|
||||||
|
firsts[i * FACE_GROUPS + g] = quads;
|
||||||
|
quads += sections[i].meshes[layer]!.groups![g].count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = quads > 0 ? this.buffers.create(quads * TERRAIN_QUAD_BYTES) : undefined;
|
||||||
|
// copies from the old buffer, one per run of quads that's together in both
|
||||||
|
const copies: number[] = [];
|
||||||
|
for (let g = 0; g < FACE_GROUPS && buffer; g++) {
|
||||||
|
for (let i = 0; i < sections.length; i++) {
|
||||||
|
const group = sections[i].meshes[layer]!.groups![g];
|
||||||
|
if (group.count === 0) continue;
|
||||||
|
const from = group.first * TERRAIN_QUAD_BYTES;
|
||||||
|
const to = firsts[i * FACE_GROUPS + g] * TERRAIN_QUAD_BYTES;
|
||||||
|
const size = group.count * TERRAIN_QUAD_BYTES;
|
||||||
|
const vertices = old.meshed.get(sections[i]);
|
||||||
|
if (vertices) {
|
||||||
|
this.buffers.write(buffer, to, vertices, from, size);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const last = copies.length - 3;
|
||||||
|
if (
|
||||||
|
last >= 0 && copies[last] + copies[last + 2] === from &&
|
||||||
|
copies[last + 1] + copies[last + 2] === to
|
||||||
|
) {
|
||||||
|
copies[last + 2] += size;
|
||||||
|
} else {
|
||||||
|
copies.push(from, to, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (old.buffer) {
|
||||||
|
if (buffer) this.buffers.copy(old.buffer, buffer, copies);
|
||||||
|
this.buffers.destroy(old.buffer);
|
||||||
|
}
|
||||||
|
for (let i = 0; i < sections.length; i++) {
|
||||||
|
const mesh = sections[i].meshes[layer]!;
|
||||||
|
for (let g = 0; g < FACE_GROUPS; g++) mesh.groups![g].first = firsts[i * FACE_GROUPS + g];
|
||||||
|
mesh.slot = i;
|
||||||
|
}
|
||||||
|
this.layers[layer] = { buffer, sections, meshed: new Map(), changed: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose() {
|
||||||
|
for (const layer of REGION_LAYERS) {
|
||||||
|
if (this.layers[layer].buffer) this.buffers.destroy(this.layers[layer].buffer!);
|
||||||
|
this.layers[layer] = empty_layer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-247
@@ -1,221 +1,17 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { AssetManager } from "./assets.ts";
|
// the client in a browser page, drawing on index.html's canvas. the desktop app's starts at native/main.ts
|
||||||
import { Client } from "./client.ts";
|
import { set_platform } from "./platform.ts";
|
||||||
import { InputManager } from "./input_manager.ts";
|
import { browser_platform } from "./browser_platform.ts";
|
||||||
import { Connection } from "./network.ts";
|
import { listen_to_page } from "./browser_input.ts";
|
||||||
import { Options } from "./options.ts";
|
import { init_window, resize_canvas } from "./renderer/mod.ts";
|
||||||
import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts";
|
import { show_fatal_error } from "./fatal.ts";
|
||||||
import { build_atlas, engine_textures } from "./atlas.ts";
|
import { sounds } from "./sounds.ts";
|
||||||
import { confirm_mods } from "./confirm_mods.ts";
|
import { WebAudioOutput } from "./audio_output.ts";
|
||||||
import { set_texture_animations } from "./texture_animations.ts";
|
import { start_client } from "./client_loop.ts";
|
||||||
import type { TextureJson } from "$/common/texture_animation.ts";
|
|
||||||
import { ModLoadError } from "$/common/mod_loader.ts";
|
|
||||||
import {
|
|
||||||
begin_drawing,
|
|
||||||
canvas,
|
|
||||||
clear_background,
|
|
||||||
device,
|
|
||||||
end_drawing,
|
|
||||||
init_font,
|
|
||||||
init_window,
|
|
||||||
load_texture,
|
|
||||||
render_debug,
|
|
||||||
resize_canvas,
|
|
||||||
} from "./renderer/mod.ts";
|
|
||||||
import { is_stopped, show_fatal_error } from "./fatal.ts";
|
|
||||||
import { download_mods, load_client_mods, set_mods_client } from "./mods.ts";
|
|
||||||
import type { GuiScreen } from "./gui/gui_screen.ts";
|
|
||||||
import { TitleScreen } from "./gui/title_screen.ts";
|
|
||||||
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
|
|
||||||
import { profiler } from "./profiler.ts";
|
|
||||||
|
|
||||||
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
|
set_platform(browser_platform);
|
||||||
export // while playing, the browser asks before leaving the page. sprinting is ctrl and walking is w, and ctrl+w closes the
|
|
||||||
// tab without the page getting a say. in fullscreen the keyboard lock catches it instead (see input_manager.ts)
|
|
||||||
function confirm_leaving(confirm: boolean) {
|
|
||||||
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// with render_debug.uncapped, the most frames between two of the display's refreshes. it's the highest fps that shows,
|
|
||||||
// 960 on a 60 hz display, and what the gpu can be behind by
|
|
||||||
const UNCAPPED_FRAMES_PER_REFRESH = 16;
|
|
||||||
|
|
||||||
class ClientLoop {
|
|
||||||
running = false;
|
|
||||||
last_time = 0;
|
|
||||||
client: Client | undefined;
|
|
||||||
screen: GuiScreen | undefined;
|
|
||||||
|
|
||||||
frame_count = 0;
|
|
||||||
last_fps_time = 0;
|
|
||||||
|
|
||||||
start() {
|
|
||||||
document.addEventListener("visibilitychange", () => {
|
|
||||||
if (!document.hidden) {
|
|
||||||
this.last_time = performance.now();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.#next_task.port1.onmessage = () => this.loop(performance.now());
|
|
||||||
this.running = true;
|
|
||||||
const now = performance.now();
|
|
||||||
this.last_time = now;
|
|
||||||
this.frame_count = 0;
|
|
||||||
this.last_fps_time = this.last_time;
|
|
||||||
requestAnimationFrame((time) => this.loop(time));
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
this.running = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
show_screen(screen: GuiScreen) {
|
|
||||||
this.screen?.on_close();
|
|
||||||
this.client = undefined;
|
|
||||||
confirm_leaving(false);
|
|
||||||
this.screen = screen;
|
|
||||||
InputManager.set_mouse_grabbed(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
play(connection: Connection) {
|
|
||||||
const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message)));
|
|
||||||
set_mods_client(client);
|
|
||||||
client.chat.add("Connected to the server");
|
|
||||||
this.screen?.on_close();
|
|
||||||
this.screen = undefined;
|
|
||||||
this.client = client;
|
|
||||||
confirm_leaving(true);
|
|
||||||
console.log("Game started");
|
|
||||||
}
|
|
||||||
|
|
||||||
// with render_debug.uncapped: frames since the display last refreshed, and whether the next one waits for it
|
|
||||||
#frames_this_refresh = 0;
|
|
||||||
#waiting_for_refresh = false;
|
|
||||||
#refresh_requested = false;
|
|
||||||
#next_task = new MessageChannel();
|
|
||||||
|
|
||||||
// with the display's refresh, or with render_debug.uncapped right away, so frames aren't held to vsync and show what
|
|
||||||
// they cost. up to UNCAPPED_FRAMES_PER_REFRESH, then it waits for the next refresh, which the browser holds back
|
|
||||||
// while the gpu is behind, so frames the gpu can't keep up with don't pile up. the browser saying a frame is done
|
|
||||||
// can't be waited on instead, firefox only says so every 100 ms when nothing else is sent to the gpu
|
|
||||||
#next_frame() {
|
|
||||||
if (!render_debug.uncapped) {
|
|
||||||
requestAnimationFrame((time) => this.loop(time));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!this.#refresh_requested) {
|
|
||||||
this.#refresh_requested = true;
|
|
||||||
requestAnimationFrame(() => {
|
|
||||||
this.#refresh_requested = false;
|
|
||||||
this.#frames_this_refresh = 0;
|
|
||||||
if (this.#waiting_for_refresh) {
|
|
||||||
this.#waiting_for_refresh = false;
|
|
||||||
this.loop(performance.now());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
this.#frames_this_refresh += 1;
|
|
||||||
if (this.#frames_this_refresh < UNCAPPED_FRAMES_PER_REFRESH) {
|
|
||||||
// a task of its own, so input and the workers' messages get handled in between
|
|
||||||
this.#next_task.port2.postMessage(null);
|
|
||||||
} else {
|
|
||||||
this.#waiting_for_refresh = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
loop(time: number) {
|
|
||||||
if (!this.running || is_stopped()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const delta = (time - this.last_time) / 1000;
|
|
||||||
|
|
||||||
profiler.begin_frame();
|
|
||||||
profiler.section("begin frame", begin_drawing);
|
|
||||||
clear_background(0.69, 0.8, 1, 1.0);
|
|
||||||
if (this.client) {
|
|
||||||
this.client.run_frame(delta);
|
|
||||||
} else if (this.screen) {
|
|
||||||
this.screen.on_tick(delta);
|
|
||||||
this.screen.on_render();
|
|
||||||
}
|
|
||||||
profiler.section("submit", end_drawing);
|
|
||||||
profiler.end_frame();
|
|
||||||
|
|
||||||
this.frame_count += 1;
|
|
||||||
const now = performance.now();
|
|
||||||
if (now - this.last_fps_time >= 1000) {
|
|
||||||
const fps = (this.frame_count * 1000) / (now - this.last_fps_time);
|
|
||||||
console.log(`FPS: ${fps.toFixed(2)}`);
|
|
||||||
this.frame_count = 0;
|
|
||||||
this.last_fps_time = now;
|
|
||||||
}
|
|
||||||
|
|
||||||
InputManager.update();
|
|
||||||
|
|
||||||
this.last_time = time;
|
|
||||||
this.#next_frame();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// a server's blocks, items and scripts can't be taken back out once loaded, so a failure after that point
|
|
||||||
// can't go back to the title screen to try again, the page has to start over
|
|
||||||
class FailedAfterLoadingMods extends Error {}
|
|
||||||
|
|
||||||
// the game only runs against a server, it owns the world and everything in it. see docs/modding/networking/index.md
|
|
||||||
async function join_server(address: ServerAddress, name: string, status: (text: string) => void): Promise<Connection> {
|
|
||||||
const { socket, welcome } = await connect(address, name);
|
|
||||||
console.log(`Connected to ${address.ws_url}`);
|
|
||||||
|
|
||||||
let loaded_mods = false;
|
|
||||||
try {
|
|
||||||
if (address.cross_origin && !is_trusted(address, welcome)) {
|
|
||||||
status("Waiting for you to accept the server's mods...");
|
|
||||||
if (!await confirm_mods(address, welcome)) {
|
|
||||||
throw new HandshakeError(`You didn't join ${address.base.host}`);
|
|
||||||
}
|
|
||||||
remember_trust(address, welcome);
|
|
||||||
}
|
|
||||||
|
|
||||||
// textures, blocks and items all come from the server's mods, so this happens before anything else
|
|
||||||
status("Downloading the server's mods...");
|
|
||||||
const bmods = await download_mods(welcome.mods, address.base);
|
|
||||||
const textures = await engine_textures();
|
|
||||||
const texture_json = new Map<string, TextureJson>();
|
|
||||||
for (const bmod of bmods) {
|
|
||||||
for (const [id, png] of bmod.textures) textures.set(id, png);
|
|
||||||
for (const [id, json] of bmod.texture_json ?? []) texture_json.set(id, json);
|
|
||||||
}
|
|
||||||
const atlas = await build_atlas(textures, texture_json);
|
|
||||||
loaded_mods = true;
|
|
||||||
const atlas_texture = load_texture(atlas.image);
|
|
||||||
set_texture_animations(atlas_texture.tex, device.queue, atlas.animated);
|
|
||||||
AssetManager.instance.assets["bworld:textures"] = atlas_texture;
|
|
||||||
AssetManager.instance.assets["bworld:textures_info"] = atlas.regions;
|
|
||||||
await load_client_mods(welcome.mods, bmods);
|
|
||||||
console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`);
|
|
||||||
|
|
||||||
status("Joining...");
|
|
||||||
const joined = await join(socket, new Options().render_distance);
|
|
||||||
return new Connection(socket, welcome, joined);
|
|
||||||
} catch (e) {
|
|
||||||
socket.close();
|
|
||||||
const message = error_message(e);
|
|
||||||
throw loaded_mods ? new FailedAfterLoadingMods(message) : new HandshakeError(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function error_message(e: unknown) {
|
|
||||||
if (e instanceof HandshakeError) {
|
|
||||||
return e.message;
|
|
||||||
}
|
|
||||||
if (e instanceof ModLoadError) {
|
|
||||||
return `Couldn't load the server's mods: ${e.message}`;
|
|
||||||
}
|
|
||||||
return `Something went wrong joining the server: ${e instanceof Error ? e.message : e}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const game_canvas = document.getElementById("game") as HTMLCanvasElement;
|
const game_canvas = document.getElementById("game") as HTMLCanvasElement;
|
||||||
if (!game_canvas) {
|
if (!game_canvas) {
|
||||||
@@ -229,37 +25,12 @@ try {
|
|||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
InputManager.initialize(game_canvas);
|
listen_to_page(game_canvas);
|
||||||
self.addEventListener("resize", resize_canvas);
|
// waits for the first click or key, which the title screen gets
|
||||||
resize_canvas();
|
sounds.set_output(new WebAudioOutput());
|
||||||
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
|
const fit_page = () => resize_canvas(self.innerWidth, self.innerHeight);
|
||||||
|
self.addEventListener("resize", fit_page);
|
||||||
|
fit_page();
|
||||||
|
game_canvas.addEventListener("contextmenu", (event) => event.preventDefault());
|
||||||
|
|
||||||
AssetManager.instance.load("bworld:assets_text", "/assets/ASSETS.md");
|
await start_client();
|
||||||
|
|
||||||
AssetManager.instance.load("bworld:skin", "/assets/sprites/skin_template.png");
|
|
||||||
AssetManager.instance.load("bworld:gui", "/assets/sprites/gui.png");
|
|
||||||
|
|
||||||
AssetManager.instance.load("bworld:m6x11", "/assets/fonts/m6x11.png");
|
|
||||||
AssetManager.instance.load("bworld:m6x11_fnt", "/assets/fonts/m6x11.fnt");
|
|
||||||
|
|
||||||
await AssetManager.instance.load_all();
|
|
||||||
|
|
||||||
init_font();
|
|
||||||
|
|
||||||
const loop = new ClientLoop();
|
|
||||||
loop.show_screen(
|
|
||||||
new TitleScreen(async (address, name, status) => {
|
|
||||||
let connection: Connection;
|
|
||||||
try {
|
|
||||||
connection = await join_server(address, name, status);
|
|
||||||
} catch (e) {
|
|
||||||
if (e instanceof FailedAfterLoadingMods) {
|
|
||||||
loop.show_screen(new DisconnectedScreen(e.message));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
loop.play(connection);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
loop.start();
|
|
||||||
|
|||||||
+3
-3
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
// the client's copy of a menu, like neoforge's client menu: built from what the server sent when it opened, kept up
|
// the client's copy of a menu, like neoforge's client menu: built from what the server sent when it opened, kept up
|
||||||
// to date with what it syncs. clicks go to the server, which decides what they do
|
// to date with what it syncs. clicks go to the server, which decides what they do
|
||||||
import { Container } from "$/common/inventory.ts";
|
import { Container } from "@/common/inventory.ts";
|
||||||
import {
|
import {
|
||||||
CRAFTING_RESULT_SLOT,
|
CRAFTING_RESULT_SLOT,
|
||||||
type MenuFluidSlotInfo,
|
type MenuFluidSlotInfo,
|
||||||
@@ -11,9 +11,9 @@ import {
|
|||||||
type MenuTank,
|
type MenuTank,
|
||||||
PLAYER_MENU,
|
PLAYER_MENU,
|
||||||
PLAYER_MENU_EXTRA,
|
PLAYER_MENU_EXTRA,
|
||||||
} from "$/common/protocol.ts";
|
} from "@/common/protocol.ts";
|
||||||
import type { ClientInventories } from "./inventory.ts";
|
import type { ClientInventories } from "./inventory.ts";
|
||||||
import type { ItemStack as ApiItemStack } from "$/common/mod_api/client.ts";
|
import type { ItemStack as ApiItemStack } from "@/common/mod_api/client.ts";
|
||||||
|
|
||||||
export interface ClientSlot {
|
export interface ClientSlot {
|
||||||
// where its item is on this client
|
// where its item is on this client
|
||||||
|
|||||||
+198
-132
@@ -1,38 +1,55 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// loads the mods the server lists: downloads their .bmod files, registers their data, then runs their client scripts.
|
// loads the mods the server lists: downloads their .cubi files, registers their data, then runs their scripts' shared
|
||||||
// see docs/modding/networking/index.md
|
// and client phases. see docs/modding/networking/index.md
|
||||||
import { AIR } from "$/common/constants.ts";
|
import { AIR } from "@/common/constants.ts";
|
||||||
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import type { ClientContext, ClientMenu, InventoryOverlay, KeyMappings, MenuScreen } from "$/common/mod_api/client.ts";
|
import type {
|
||||||
|
ClientContext,
|
||||||
|
ClientMenu,
|
||||||
|
Graphics,
|
||||||
|
HudLayer,
|
||||||
|
HudSpace,
|
||||||
|
InventoryOverlay,
|
||||||
|
KeyMappings,
|
||||||
|
MenuScreen,
|
||||||
|
} from "@/common/mod_api/client.ts";
|
||||||
import {
|
import {
|
||||||
check_recipe_types,
|
check_recipe_types,
|
||||||
ModListing,
|
ModListing,
|
||||||
ModLoadError,
|
ModLoadError,
|
||||||
|
type Phase,
|
||||||
recipe_lookup,
|
recipe_lookup,
|
||||||
RecipeBook,
|
RecipeBook,
|
||||||
register_mod_data,
|
register_mod_data,
|
||||||
shared_recipes_api,
|
registrar,
|
||||||
} from "$/common/mod_loader.ts";
|
run_phase,
|
||||||
import { type Bmod, read_bmod } from "$/common/bmod.ts";
|
} from "@/common/mod_loader.ts";
|
||||||
import { get_state_value, set_state_value, shared_items_api } from "$/common/utils.ts";
|
import { blocks_api, shared_context } from "@/common/shared_context.ts";
|
||||||
import { BlockRules } from "$/common/block_rules.ts";
|
import { type Mod, read_mod } from "@/common/mod.ts";
|
||||||
import { fluid_exists, FluidRules, same_fluid } from "$/common/fluids.ts";
|
import { get_state_value, set_state_value, shared_items_api } from "@/common/utils.ts";
|
||||||
|
import { BlockRules } from "@/common/block_rules.ts";
|
||||||
|
import { FluidRules } from "@/common/fluids.ts";
|
||||||
import { fluid_rules, set_fluid_rules } from "./fluid_rules.ts";
|
import { fluid_rules, set_fluid_rules } from "./fluid_rules.ts";
|
||||||
import { covers_face, EMPTY_SHAPE, FULL_SHAPE, is_solid } from "$/common/block_shapes.ts";
|
import { covers_face, EMPTY_SHAPE, FULL_SHAPE } from "@/common/block_shapes.ts";
|
||||||
import type { SharedContext, SharedWorld } from "$/common/mod_api/shared.ts";
|
import type { SharedWorld } from "@/common/mod_api/shared.ts";
|
||||||
import { tag_api } from "$/common/tags.ts";
|
import { tag_api } from "@/common/tags.ts";
|
||||||
import { AIR_ID } from "$/common/protocol.ts";
|
import { AIR_ID } from "@/common/protocol.ts";
|
||||||
import type { Client } from "./client.ts";
|
import type { Client } from "./client.ts";
|
||||||
import { code_url, fetch_verified } from "./handshake.ts";
|
import { code_url, fetch_verified } from "./handshake.ts";
|
||||||
import { GuiModScreen } from "./gui/gui_mod_screens.ts";
|
import { GuiModScreen } from "./gui/gui_mod_screens.ts";
|
||||||
import { clear_hooks, expose_engine, loading_mod } from "$/common/hooks.ts";
|
import { item_tooltips } from "./gui/tooltip.ts";
|
||||||
import { common_engine } from "$/common/engine_modules.ts";
|
import { clear_hooks, expose_engine } from "@/common/hooks.ts";
|
||||||
|
import { common_engine } from "@/common/engine_modules.ts";
|
||||||
import { client_engine } from "./engine_modules.ts";
|
import { client_engine } from "./engine_modules.ts";
|
||||||
import { block_visuals } from "./rendering/visuals.ts";
|
import { block_visuals } from "./rendering/visuals.ts";
|
||||||
import { biome_season } from "$/common/worldgen/biomes.ts";
|
import { entity_animators } from "./rendering/entity_animators.ts";
|
||||||
import type { LootTableJson } from "$/common/loot.ts";
|
import { biome_season } from "@/common/worldgen/biomes.ts";
|
||||||
|
import { clock, farming_day } from "@/common/time.ts";
|
||||||
|
import type { LootTableJson } from "@/common/loot.ts";
|
||||||
|
import type { ClipJson } from "@/common/mod_data.ts";
|
||||||
|
import { sounds } from "./sounds.ts";
|
||||||
|
|
||||||
// each loaded mod's credits file, for the credits screen
|
// each loaded mod's credits file, for the credits screen
|
||||||
export const mod_credits: { name: string; version: string; text: string }[] = [];
|
export const mod_credits: { name: string; version: string; text: string }[] = [];
|
||||||
@@ -46,6 +63,27 @@ export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] =
|
|||||||
// each menu type's screen, see ctx.ui.register_menu_screen
|
// each menu type's screen, see ctx.ui.register_menu_screen
|
||||||
export const menu_screens = new Map<string, { mod: string; create: (menu: ClientMenu) => MenuScreen }>();
|
export const menu_screens = new Map<string, { mod: string; create: (menu: ClientMenu) => MenuScreen }>();
|
||||||
|
|
||||||
|
// what mods draw over the world, in order, see ctx.hud and client/gui/hud.ts
|
||||||
|
export const hud_layers: { mod: string; id: string; layer: HudLayer }[] = [];
|
||||||
|
|
||||||
|
// draws every hud layer in order, all raising the same space. one that throws is removed so it doesn't throw every frame
|
||||||
|
export function render_hud_layers(g: Graphics, space: HudSpace) {
|
||||||
|
for (const entry of [...hud_layers]) {
|
||||||
|
try {
|
||||||
|
entry.layer.on_render(g, space);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${entry.mod}] hud layer ${entry.id} threw, so it's removed:`, e);
|
||||||
|
hud_layers.splice(hud_layers.indexOf(entry), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const overlay_listeners: { mod: string; fn: (text: string) => void }[] = [];
|
||||||
|
|
||||||
|
// the server sent an overlay message, see MessageOptions.overlay
|
||||||
|
export function receive_overlay_message(text: string) {
|
||||||
|
for (const { mod, fn } of overlay_listeners) run_mod(mod, "an overlay message listener", () => fn(text));
|
||||||
|
}
|
||||||
|
|
||||||
// mod channels, see ctx.net: who listens on each channel
|
// mod channels, see ctx.net: who listens on each channel
|
||||||
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
|
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
|
||||||
|
|
||||||
@@ -91,18 +129,18 @@ const rules_world: SharedWorld = {
|
|||||||
const shape = client?.level.collision_shape(x, y, z) ?? false;
|
const shape = client?.level.collision_shape(x, y, z) ?? false;
|
||||||
return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face);
|
return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face);
|
||||||
},
|
},
|
||||||
biome_at: (x, z) => client?.level.biome_at(Math.floor(x), Math.floor(z)),
|
biome_at: (x, y, z) => client?.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z)),
|
||||||
season_at(x, z) {
|
season_at(x, y, z) {
|
||||||
const biome = this.biome_at(x, z);
|
const biome = this.biome_at(x, y, z);
|
||||||
return biome === undefined ? undefined : biome_season(biome, client!.level.time);
|
return biome === undefined ? undefined : biome_season(biome, client!.level.time);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts
|
// what the mods' shared phases registered, run to guess ahead of the server, see common/block_rules.ts
|
||||||
export let block_rules = new BlockRules(run_mod, rules_world.get_block);
|
export let block_rules = new BlockRules(run_mod, rules_world.get_block);
|
||||||
// whether shared scripts are being set up, the only time they can register rules
|
// whether shared phases are being set up, the only time they can register rules
|
||||||
let rules_setup = false;
|
let rules_setup = false;
|
||||||
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told
|
// whether client phases are being set up, the only time they can register visuals, since chunk workers are told
|
||||||
// which blocks have them when the level starts
|
// which blocks have them when the level starts
|
||||||
let client_setup = false;
|
let client_setup = false;
|
||||||
|
|
||||||
@@ -135,78 +173,82 @@ export function set_mods_client(game_client: Client) {
|
|||||||
client = game_client;
|
client = game_client;
|
||||||
}
|
}
|
||||||
|
|
||||||
// downloads every mod's .bmod and checks it against the hash the server listed. everything a mod runs comes from
|
// downloads every mod's .cubi and checks it against the hash the server listed. everything a mod runs comes from
|
||||||
// the checked bytes, never fetched twice
|
// the checked bytes, never fetched twice
|
||||||
export async function download_mods(listings: ModListing[], base: URL): Promise<Bmod[]> {
|
export async function download_mods(listings: ModListing[], base: URL): Promise<Mod[]> {
|
||||||
return await Promise.all(listings.map(async (listing) => {
|
return await Promise.all(listings.map(async (listing) => {
|
||||||
try {
|
try {
|
||||||
const bytes = await fetch_verified(new URL(listing.file, base), listing.sha256, `${listing.name}`);
|
const bytes = await fetch_verified(new URL(listing.file, base), listing.sha256, `${listing.name}`);
|
||||||
const bmod = read_bmod(bytes, `${listing.id}.bmod`);
|
const mod = read_mod(bytes, `${listing.id}.cubi`);
|
||||||
if (bmod.manifest.id !== listing.id) throw new Error(`the server listed it as ${listing.id}`);
|
if (mod.manifest.id !== listing.id) throw new Error(`the server listed it as ${listing.id}`);
|
||||||
// the confirm screen said whether it has engine access, going by the listing
|
// the confirm screen said whether it has engine access, going by the listing
|
||||||
if ((bmod.manifest.engine_access ?? false) !== (listing.engine_access ?? false)) {
|
if ((mod.manifest.engine_access ?? false) !== (listing.engine_access ?? false)) {
|
||||||
throw new Error("its engine access isn't what the server listed");
|
throw new Error("its engine access isn't what the server listed");
|
||||||
}
|
}
|
||||||
return bmod;
|
return mod;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new ModLoadError(listing.id, (e as Error).message);
|
throw new ModLoadError(listing.id, (e as Error).message);
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// registers the mods' data and runs their client scripts, in the order the server listed them
|
// registers the mods' data and runs their scripts' shared and client phases, in the order the server listed them
|
||||||
export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
|
export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
|
||||||
for (const [i, bmod] of bmods.entries()) {
|
for (const [i, mod] of mods.entries()) {
|
||||||
if (bmod.credits) {
|
if (mod.credits) {
|
||||||
mod_credits.push({ name: listings[i].name, version: listings[i].version, text: bmod.credits });
|
mod_credits.push({ name: listings[i].name, version: listings[i].version, text: mod.credits });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const recipes = register_mod_data(bmods.map((bmod) => ({ id: bmod.manifest.id, data: bmod.data })));
|
const recipes = register_mod_data(mods.map((mod) => ({ id: mod.manifest.id, data: mod.data })));
|
||||||
|
sounds.set_files(mods.map((mod) => ({ id: mod.manifest.id, sounds: mod.sounds })));
|
||||||
recipe_book = recipes;
|
recipe_book = recipes;
|
||||||
inventory_overlays.length = 0;
|
inventory_overlays.length = 0;
|
||||||
|
hud_layers.length = 0;
|
||||||
|
overlay_listeners.length = 0;
|
||||||
|
item_tooltips.length = 0;
|
||||||
menu_screens.clear();
|
menu_screens.clear();
|
||||||
net_handlers.clear();
|
net_handlers.clear();
|
||||||
block_visuals.clear();
|
block_visuals.clear();
|
||||||
|
entity_animators.clear();
|
||||||
mod_names.clear();
|
mod_names.clear();
|
||||||
for (const listing of listings) mod_names.set(listing.id, listing.name);
|
for (const listing of listings) mod_names.set(listing.id, listing.name);
|
||||||
|
|
||||||
// for engine access mods. the last server's hooks go first
|
// for engine access mods. the last server's hooks go first
|
||||||
clear_hooks();
|
clear_hooks();
|
||||||
expose_engine({ common: common_engine(), client: client_engine() });
|
expose_engine({ common: common_engine(), client: client_engine() });
|
||||||
const as_mod = (bmod: Bmod, fn: () => Promise<void>) =>
|
|
||||||
loading_mod(bmod.manifest.id, bmod.manifest.engine_access ?? false, fn);
|
|
||||||
|
|
||||||
// every mod's shared rules first, so client scripts can count on any mod's being there
|
// one url for each mod's script, so its phases share one module
|
||||||
|
const urls = mods.map((mod) => mod.script === undefined ? undefined : script_url(mod.script));
|
||||||
|
const run = async (phase: Phase, context: (i: number) => unknown) => {
|
||||||
|
for (const [i, mod] of mods.entries()) {
|
||||||
|
const url = urls[i];
|
||||||
|
if (url === undefined) continue;
|
||||||
|
const as = { id: mod.manifest.id, engine_access: mod.manifest.engine_access };
|
||||||
|
await run_phase(as, url, phase, () => context(i));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// every mod's shared rules first, so client phases can count on any mod's being there
|
||||||
block_rules = new BlockRules(run_mod, rules_world.get_block);
|
block_rules = new BlockRules(run_mod, rules_world.get_block);
|
||||||
set_fluid_rules(new FluidRules(run_mod));
|
set_fluid_rules(new FluidRules(run_mod));
|
||||||
rules_setup = true;
|
rules_setup = true;
|
||||||
for (const [i, bmod] of bmods.entries()) {
|
await run("shared", (i) =>
|
||||||
const code = bmod.scripts.shared;
|
shared_context({ id: listings[i].id, version: listings[i].version }, {
|
||||||
if (!code) continue;
|
side: "client",
|
||||||
await as_mod(bmod, async () => {
|
world: rules_world,
|
||||||
const module = await import(script_url(code));
|
block_rules,
|
||||||
if (typeof module.setup !== "function") {
|
fluid_rules,
|
||||||
throw new ModLoadError(bmod.manifest.id, "the shared script doesn't export a setup function");
|
recipes: () => recipe_book,
|
||||||
}
|
running: () => rules_setup,
|
||||||
await module.setup(shared_context(listings[i]));
|
// rules only run here to guess what the player's own actions do, so this is the sound their action makes
|
||||||
});
|
play_sound: (sound, x, y, z, options) => sounds.play(sound, { ...options, at: { x, y, z } }),
|
||||||
}
|
}));
|
||||||
rules_setup = false;
|
rules_setup = false;
|
||||||
check_recipe_types(recipe_book);
|
check_recipe_types(recipe_book);
|
||||||
|
|
||||||
client_setup = true;
|
client_setup = true;
|
||||||
for (const [i, bmod] of bmods.entries()) {
|
await run("client", (i) => client_context(listings[i]));
|
||||||
const code = bmod.scripts.client;
|
|
||||||
if (!code) continue;
|
|
||||||
await as_mod(bmod, async () => {
|
|
||||||
const module = await import(script_url(code));
|
|
||||||
if (typeof module.setup !== "function") {
|
|
||||||
throw new ModLoadError(bmod.manifest.id, "the client script doesn't export a setup function");
|
|
||||||
}
|
|
||||||
await module.setup(client_context(listings[i]));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
client_setup = false;
|
client_setup = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,56 +256,6 @@ function script_url(code: string) {
|
|||||||
return code_url(new TextEncoder().encode(code));
|
return code_url(new TextEncoder().encode(code));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ctx.blocks, the same in shared and client scripts
|
|
||||||
function blocks_api(mod: string): SharedContext["blocks"] {
|
|
||||||
return {
|
|
||||||
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
|
|
||||||
components(id) {
|
|
||||||
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
|
||||||
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
|
|
||||||
return structuredClone(block.components ?? {});
|
|
||||||
},
|
|
||||||
solid(id) {
|
|
||||||
if (id === AIR_ID) return false;
|
|
||||||
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
|
||||||
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
|
|
||||||
return is_solid(block);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function shared_context(listing: ModListing): SharedContext {
|
|
||||||
const mod = listing.id;
|
|
||||||
return {
|
|
||||||
mod: { id: mod, version: listing.version },
|
|
||||||
side: "client",
|
|
||||||
tags: tag_api(),
|
|
||||||
blocks: blocks_api(mod),
|
|
||||||
items: shared_items_api(mod),
|
|
||||||
fluids: {
|
|
||||||
exists: fluid_exists,
|
|
||||||
same: same_fluid,
|
|
||||||
register(id, rules) {
|
|
||||||
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
|
|
||||||
fluid_rules.register(mod, id, rules);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
recipes: shared_recipes_api(mod, () => recipe_book, () => rules_setup, (message) => {
|
|
||||||
throw new Error(`[${mod}] ${message}`);
|
|
||||||
}),
|
|
||||||
world: rules_world,
|
|
||||||
components: {
|
|
||||||
register_block(id, rules) {
|
|
||||||
if (!id.startsWith(`${mod}:`)) {
|
|
||||||
throw new Error(`[${mod}] component ${id} must be in the namespace "${mod}"`);
|
|
||||||
}
|
|
||||||
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
|
|
||||||
block_rules.register(mod, id, rules);
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function client_context(listing: ModListing): ClientContext {
|
function client_context(listing: ModListing): ClientContext {
|
||||||
const mod = listing.id;
|
const mod = listing.id;
|
||||||
const not_yet = (name: string, where: string) =>
|
const not_yet = (name: string, where: string) =>
|
||||||
@@ -279,11 +271,7 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
return client;
|
return client;
|
||||||
};
|
};
|
||||||
|
|
||||||
const own = (id: string, what = "channel") => {
|
const register = registrar(mod, "client", () => client_setup);
|
||||||
if (!id.startsWith(`${mod}:`)) {
|
|
||||||
throw new Error(`[${mod}] ${what} ${id} must be in the namespace "${mod}"`);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const known_item = (id: string) => {
|
const known_item = (id: string) => {
|
||||||
const item = EverythingRegistry.get<ItemRegistry>("items", id);
|
const item = EverythingRegistry.get<ItemRegistry>("items", id);
|
||||||
if (!item) throw new Error(`[${mod}] unknown item ${id}`);
|
if (!item) throw new Error(`[${mod}] unknown item ${id}`);
|
||||||
@@ -294,8 +282,8 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
mod: { id: mod, version: listing.version },
|
mod: { id: mod, version: listing.version },
|
||||||
ui: {
|
ui: {
|
||||||
register_menu_screen(type, create) {
|
register_menu_screen(type, create) {
|
||||||
own(type, "menu type");
|
register.own("menu type", type);
|
||||||
if (menu_screens.has(type)) throw new Error(`[${mod}] ${type} already has a screen`);
|
if (menu_screens.has(type)) register.fail(`the screen of ${type} is registered twice`);
|
||||||
menu_screens.set(type, { mod, create });
|
menu_screens.set(type, { mod, create });
|
||||||
},
|
},
|
||||||
open(screen) {
|
open(screen) {
|
||||||
@@ -309,19 +297,33 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
add_inventory_overlay(overlay) {
|
add_inventory_overlay(overlay) {
|
||||||
inventory_overlays.push({ mod, overlay });
|
inventory_overlays.push({ mod, overlay });
|
||||||
},
|
},
|
||||||
|
add_item_tooltip(fn) {
|
||||||
|
if (typeof fn !== "function") throw new Error(`[${mod}] add_item_tooltip takes a function`);
|
||||||
|
item_tooltips.push((item, lines) => run_mod(mod, "an item tooltip", () => fn(item, lines)));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
hud: {
|
||||||
|
register(id, layer) {
|
||||||
|
register.new_id("hud layer", id, hud_layers.some((other) => other.id === id));
|
||||||
|
if (typeof layer?.on_render !== "function") throw new Error(`[${mod}] a hud layer needs an on_render`);
|
||||||
|
hud_layers.push({ mod, id, layer });
|
||||||
|
},
|
||||||
|
on_overlay_message(fn) {
|
||||||
|
if (typeof fn !== "function") throw new Error(`[${mod}] on_overlay_message takes a function`);
|
||||||
|
overlay_listeners.push({ mod, fn });
|
||||||
|
},
|
||||||
},
|
},
|
||||||
hud: not_yet("hud", "HUD elements") as ClientContext["hud"],
|
|
||||||
input: not_yet("input", "keybinds") as ClientContext["input"],
|
input: not_yet("input", "keybinds") as ClientContext["input"],
|
||||||
options: key_mappings(need_client),
|
options: key_mappings(need_client),
|
||||||
net: {
|
net: {
|
||||||
on(channel, handler) {
|
on(channel, handler) {
|
||||||
own(channel);
|
register.own("channel", channel);
|
||||||
const handlers = net_handlers.get(channel) ?? [];
|
const handlers = net_handlers.get(channel) ?? [];
|
||||||
handlers.push({ mod, handler: handler as (data: unknown) => void });
|
handlers.push({ mod, handler: handler as (data: unknown) => void });
|
||||||
net_handlers.set(channel, handlers);
|
net_handlers.set(channel, handlers);
|
||||||
},
|
},
|
||||||
send(channel, data) {
|
send(channel, data) {
|
||||||
own(channel);
|
register.own("channel", channel);
|
||||||
need_client().connection.send({ type: "mod", channel, data });
|
need_client().connection.send({ type: "mod", channel, data });
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -334,15 +336,44 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
return { x, y, z };
|
return { x, y, z };
|
||||||
},
|
},
|
||||||
get biome() {
|
get biome() {
|
||||||
const { x, z } = need_client().player;
|
const { x, y, z } = need_client().player;
|
||||||
return rules_world.biome_at(x, z);
|
return rules_world.biome_at(x, y, z);
|
||||||
},
|
},
|
||||||
get season() {
|
get season() {
|
||||||
const { x, z } = need_client().player;
|
const { x, y, z } = need_client().player;
|
||||||
return rules_world.season_at(x, z);
|
return rules_world.season_at(x, y, z);
|
||||||
},
|
},
|
||||||
is_swimming: () => need_client().player.swimming,
|
is_swimming: () => need_client().player.swimming,
|
||||||
is_sneaking: () => need_client().player.holding_sneak,
|
is_sneaking: () => need_client().player.holding_sneak,
|
||||||
|
get health() {
|
||||||
|
return need_client().player.health;
|
||||||
|
},
|
||||||
|
get max_health() {
|
||||||
|
return need_client().player.max_health;
|
||||||
|
},
|
||||||
|
get food() {
|
||||||
|
return need_client().player.food;
|
||||||
|
},
|
||||||
|
get saturation() {
|
||||||
|
return need_client().player.saturation;
|
||||||
|
},
|
||||||
|
get air() {
|
||||||
|
return need_client().player.air;
|
||||||
|
},
|
||||||
|
is_underwater: () => need_client().player.eyes_in_water,
|
||||||
|
attack_strength: () => need_client().player.attack_strength(),
|
||||||
|
inventory: {
|
||||||
|
get size() {
|
||||||
|
return need_client().player.inventories.inventory.size;
|
||||||
|
},
|
||||||
|
get(slot) {
|
||||||
|
const item = need_client().player.inventories.inventory.get_item(slot);
|
||||||
|
return item && structuredClone(item.to_data());
|
||||||
|
},
|
||||||
|
},
|
||||||
|
get selected_slot() {
|
||||||
|
return need_client().player.inventories.hotbar_selected;
|
||||||
|
},
|
||||||
},
|
},
|
||||||
world: {
|
world: {
|
||||||
get_block(x, y, z) {
|
get_block(x, y, z) {
|
||||||
@@ -352,20 +383,33 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
},
|
},
|
||||||
get_client_data: (x, y, z, field) =>
|
get_client_data: (x, y, z, field) =>
|
||||||
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
|
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
|
||||||
biome_at: (x, z) => rules_world.biome_at(x, z),
|
biome_at: (x, y, z) => rules_world.biome_at(x, y, z),
|
||||||
season_at: (x, z) => rules_world.season_at(x, z),
|
season_at: (x, y, z) => rules_world.season_at(x, y, z),
|
||||||
|
get min_y() {
|
||||||
|
return need_client().level.shape.min_y;
|
||||||
|
},
|
||||||
|
get max_y() {
|
||||||
|
return need_client().level.shape.max_y;
|
||||||
|
},
|
||||||
get time() {
|
get time() {
|
||||||
return need_client().level.time;
|
return need_client().level.time;
|
||||||
},
|
},
|
||||||
|
get day() {
|
||||||
|
return farming_day(need_client().level.time);
|
||||||
|
},
|
||||||
|
get hour() {
|
||||||
|
const { hour, minute } = clock(need_client().level.time);
|
||||||
|
return hour + minute / 60;
|
||||||
|
},
|
||||||
},
|
},
|
||||||
items: {
|
items: {
|
||||||
...shared_items_api(mod),
|
...shared_items_api(mod, fluid_rules),
|
||||||
mod(id) {
|
mod(id) {
|
||||||
known_item(id);
|
known_item(id);
|
||||||
return mod_name(id);
|
return mod_name(id);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
blocks: blocks_api(mod),
|
blocks: blocks_api(),
|
||||||
fluids: {
|
fluids: {
|
||||||
...fluid_rules.api(),
|
...fluid_rules.api(),
|
||||||
mod(id) {
|
mod(id) {
|
||||||
@@ -384,14 +428,36 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
tags: tag_api(),
|
tags: tag_api(),
|
||||||
render: {
|
render: {
|
||||||
register_visual(block, create, options) {
|
register_visual(block, create, options) {
|
||||||
if (!client_setup) throw new Error(`[${mod}] visuals can only be registered during setup`);
|
register.running("visual");
|
||||||
const nid = EverythingRegistry.get_id("blocks", block);
|
const nid = EverythingRegistry.get_id("blocks", block);
|
||||||
if (nid === undefined) throw new Error(`[${mod}] unknown block ${block}`);
|
if (nid === undefined) throw new Error(`[${mod}] unknown block ${block}`);
|
||||||
if (typeof create !== "function") throw new Error(`[${mod}] a visual needs a function that makes it`);
|
if (typeof create !== "function") throw new Error(`[${mod}] a visual needs a function that makes it`);
|
||||||
const other = block_visuals.get(nid);
|
const other = block_visuals.get(nid);
|
||||||
if (other) throw new Error(`[${mod}] ${block} already has a visual, from ${other.mod}`);
|
if (other) register.fail(`${block} already has a visual, from ${other.mod}`);
|
||||||
block_visuals.set(nid, { mod, create, replaces_model: options?.replaces_model ?? false });
|
block_visuals.set(nid, { mod, create, replaces_model: options?.replaces_model ?? false });
|
||||||
},
|
},
|
||||||
|
register_entity_animator(type, create) {
|
||||||
|
register.running("entity animator");
|
||||||
|
if (!EverythingRegistry.get("entities", type)) throw new Error(`[${mod}] unknown entity ${type}`);
|
||||||
|
if (typeof create !== "function") {
|
||||||
|
throw new Error(`[${mod}] an animator needs a function that makes it`);
|
||||||
|
}
|
||||||
|
const other = entity_animators.get(type);
|
||||||
|
if (other) register.fail(`${type} already has an animator, from ${other.mod}`);
|
||||||
|
entity_animators.set(type, { mod, create });
|
||||||
|
},
|
||||||
|
clip(id) {
|
||||||
|
const json = EverythingRegistry.get<ClipJson>("animations", id);
|
||||||
|
if (!json) throw new Error(`[${mod}] unknown clip ${id}`);
|
||||||
|
return Object.freeze({ id, length: json.length, loop: json.loop });
|
||||||
|
},
|
||||||
|
},
|
||||||
|
sounds: {
|
||||||
|
play(sound, options) {
|
||||||
|
if (!sounds.exists(sound)) throw new Error(`[${mod}] unknown sound ${sound}`);
|
||||||
|
return sounds.play(sound, options);
|
||||||
|
},
|
||||||
|
exists: (sound) => sounds.exists(sound),
|
||||||
},
|
},
|
||||||
log: (...args) => console.log(`[${mod}]`, ...args),
|
log: (...args) => console.log(`[${mod}]`, ...args),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { canvas, draw_rect, draw_text, measure_text } from "../renderer/mod.ts";
|
||||||
|
import { GuiScreen } from "../gui/gui_screen.ts";
|
||||||
|
import { credit_sections } from "../gui/credits_screen.ts";
|
||||||
|
import { Button, ListBox, TEXT_SCALE, wrap_text } from "../gui/widgets.ts";
|
||||||
|
|
||||||
|
const MAX_WIDTH = 1200;
|
||||||
|
const MARGIN = 32;
|
||||||
|
const TOP = 90;
|
||||||
|
const BUTTON_WIDTH = 200;
|
||||||
|
const BUTTON_HEIGHT = 48;
|
||||||
|
// the list's own padding around its text
|
||||||
|
const TEXT_PADDING = 24;
|
||||||
|
|
||||||
|
// the credits in the desktop app, drawn in the window with the markdown as it's written, since there's no browser to
|
||||||
|
// show it as a page. after them, the credits of the libraries the app comes with (see desktop/libraries.ts)
|
||||||
|
export class TextCreditsScreen extends GuiScreen {
|
||||||
|
#list = new ListBox(0, 0, () => {});
|
||||||
|
#back: Button;
|
||||||
|
#sections: { heading: string; text: string }[];
|
||||||
|
// what the lines were wrapped for
|
||||||
|
#wrapped_width = 0;
|
||||||
|
|
||||||
|
constructor(on_back: () => void, libraries: string | undefined) {
|
||||||
|
super();
|
||||||
|
this.#back = new Button("Back", BUTTON_WIDTH, BUTTON_HEIGHT, on_back);
|
||||||
|
this.#sections = [...credit_sections(), ...(libraries ? [{ heading: "Libraries", text: libraries }] : [])];
|
||||||
|
}
|
||||||
|
|
||||||
|
on_tick(_delta: number): void {
|
||||||
|
const list = this.#list;
|
||||||
|
list.width = Math.min(MAX_WIDTH, canvas.width - MARGIN * 2);
|
||||||
|
list.height = Math.max(BUTTON_HEIGHT, canvas.height - TOP - BUTTON_HEIGHT - MARGIN * 2);
|
||||||
|
list.x = (canvas.width - list.width) / 2;
|
||||||
|
list.y = TOP;
|
||||||
|
if (list.width !== this.#wrapped_width) {
|
||||||
|
this.#wrapped_width = list.width;
|
||||||
|
list.rows = credit_lines(this.#sections, list.width - TEXT_PADDING).map((text) => ({ text }));
|
||||||
|
}
|
||||||
|
this.#back.x = (canvas.width - BUTTON_WIDTH) / 2;
|
||||||
|
this.#back.y = list.y + list.height + MARGIN;
|
||||||
|
list.handle_input();
|
||||||
|
this.#back.handle_input();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_render(): void {
|
||||||
|
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.6]);
|
||||||
|
const scale = TEXT_SCALE * 2;
|
||||||
|
draw_text("Credits", (canvas.width - measure_text("Credits", scale)) / 2, TOP / 2 - 12, scale);
|
||||||
|
this.#list.render();
|
||||||
|
this.#back.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_close(): void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// every section's heading and text, wrapped at spaces to width pixels
|
||||||
|
function credit_lines(sections: { heading: string; text: string }[], width: number): string[] {
|
||||||
|
return sections.flatMap(({ heading, text }) => [heading, "", ...wrap_text(text, width), ""]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the desktop app's client: a deno worker drawing into the app's window with webgpu, see desktop/main.ts. the
|
||||||
|
// window sends what the player does (messages.ts), and does what needs the os, like grabbing the mouse. the browser's
|
||||||
|
// client starts at ../main.ts
|
||||||
|
import { type Platform, set_platform } from "../platform.ts";
|
||||||
|
import { InputManager } from "../input_manager.ts";
|
||||||
|
import { init_window, resize_canvas } from "../renderer/mod.ts";
|
||||||
|
import { show_fatal_error } from "../fatal.ts";
|
||||||
|
import { start_client } from "../client_loop.ts";
|
||||||
|
import { TextCreditsScreen } from "./credits_screen.ts";
|
||||||
|
import { install_web_audio, sources_ended } from "./web_audio.ts";
|
||||||
|
import { sounds } from "../sounds.ts";
|
||||||
|
import { WebAudioOutput } from "../audio_output.ts";
|
||||||
|
import type { ClientMessage, WindowMessage } from "./messages.ts";
|
||||||
|
|
||||||
|
const post = (message: ClientMessage) => self.postMessage(message);
|
||||||
|
|
||||||
|
// what the game asked for, the window does it
|
||||||
|
let grabbed = false;
|
||||||
|
let focused = true;
|
||||||
|
// the window let go of the mouse while the game had it, see Platform.take_lost_mouse
|
||||||
|
let lost_mouse = false;
|
||||||
|
|
||||||
|
// frames are each a task of their own, so input, the network and the workers' messages get handled in between.
|
||||||
|
// waiting for the display's refresh happens while drawing, the window's surface holds back frames the display can't
|
||||||
|
// show yet. a timer, not a MessageChannel like the browser's: deno handles a channel's messages before timers,
|
||||||
|
// fetches and the gpu's callbacks, so frames one after another through one would hold those back
|
||||||
|
let shown = true;
|
||||||
|
let next_frame: ((time: number) => void) | undefined;
|
||||||
|
let frame_waiting = false;
|
||||||
|
const shown_listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function run_frame() {
|
||||||
|
frame_waiting = false;
|
||||||
|
const frame = next_frame;
|
||||||
|
next_frame = undefined;
|
||||||
|
frame?.(performance.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
function request_frame(frame: (time: number) => void) {
|
||||||
|
next_frame = frame;
|
||||||
|
// a hidden window gets no frames, drawing to it could wait until it's shown again
|
||||||
|
if (shown) wait_for_frame();
|
||||||
|
}
|
||||||
|
|
||||||
|
function wait_for_frame() {
|
||||||
|
if (frame_waiting) return;
|
||||||
|
frame_waiting = true;
|
||||||
|
setTimeout(run_frame, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function set_shown(now_shown: boolean) {
|
||||||
|
if (shown === now_shown) return;
|
||||||
|
shown = now_shown;
|
||||||
|
if (!shown) return;
|
||||||
|
for (const listener of shown_listeners) listener();
|
||||||
|
if (next_frame) wait_for_frame();
|
||||||
|
}
|
||||||
|
|
||||||
|
// what was asked of the window, by id, waiting for its answer
|
||||||
|
let next_id = 0;
|
||||||
|
const asking = new Map<number, (answer: string) => void>();
|
||||||
|
|
||||||
|
function ask(question: (id: number) => ClientMessage): Promise<string> {
|
||||||
|
const id = next_id++;
|
||||||
|
post(question(id));
|
||||||
|
return new Promise((resolve) => asking.set(id, resolve));
|
||||||
|
}
|
||||||
|
|
||||||
|
function native_platform(page: URL, stored: Record<string, string>, credits: string | undefined): Platform {
|
||||||
|
const storage = new Map(Object.entries(stored));
|
||||||
|
return {
|
||||||
|
page,
|
||||||
|
restart(url) {
|
||||||
|
post({ type: "restart", page: url.href });
|
||||||
|
},
|
||||||
|
request_frame,
|
||||||
|
on_shown(listener) {
|
||||||
|
shown_listeners.add(listener);
|
||||||
|
return () => shown_listeners.delete(listener);
|
||||||
|
},
|
||||||
|
// kept by the window, which saves it with the app's data
|
||||||
|
storage: {
|
||||||
|
getItem: (key) => storage.get(key) ?? null,
|
||||||
|
setItem(key, value) {
|
||||||
|
storage.set(key, value);
|
||||||
|
post({ type: "store", key, value });
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// the window saves the world when it closes
|
||||||
|
confirm_leaving() {},
|
||||||
|
show_fatal_error(message) {
|
||||||
|
post({ type: "fatal", message });
|
||||||
|
},
|
||||||
|
credits_screen: (on_back) => new TextCreditsScreen(on_back, credits),
|
||||||
|
read_clipboard: () => ask((id) => ({ type: "read_clipboard", id })),
|
||||||
|
write_clipboard(text) {
|
||||||
|
post({ type: "write_clipboard", text });
|
||||||
|
return Promise.resolve();
|
||||||
|
},
|
||||||
|
set_mouse_grabbed(grab) {
|
||||||
|
if (grab === grabbed) return;
|
||||||
|
grabbed = grab;
|
||||||
|
// it's no longer where it was, see InputManager.move_cursor
|
||||||
|
if (grab) {
|
||||||
|
InputManager.mouse_x = -1;
|
||||||
|
InputManager.mouse_y = -1;
|
||||||
|
}
|
||||||
|
post({ type: "grab", grab });
|
||||||
|
},
|
||||||
|
is_mouse_grabbed: () => grabbed && focused,
|
||||||
|
take_lost_mouse() {
|
||||||
|
const lost = lost_mouse;
|
||||||
|
lost_mouse = false;
|
||||||
|
return lost;
|
||||||
|
},
|
||||||
|
toggle_fullscreen() {
|
||||||
|
post({ type: "fullscreen" });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start(message: Extract<WindowMessage, { type: "start" }>) {
|
||||||
|
set_platform(native_platform(new URL(message.page), message.storage, message.credits));
|
||||||
|
const { surface: handles, width, height } = message;
|
||||||
|
const surface = new Deno.UnsafeWindowSurface({
|
||||||
|
system: handles.system,
|
||||||
|
windowHandle: Deno.UnsafePointer.create(handles.window),
|
||||||
|
displayHandle: Deno.UnsafePointer.create(handles.display),
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
});
|
||||||
|
// pointers to the window were all that needed ffi. mods run in here too, they don't get it
|
||||||
|
await Deno.permissions.revoke({ name: "ffi" });
|
||||||
|
try {
|
||||||
|
await init_window(surface);
|
||||||
|
} catch (e) {
|
||||||
|
show_fatal_error(e instanceof Error ? e.message : String(e));
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
resize_canvas(width, height);
|
||||||
|
if (message.audio) {
|
||||||
|
install_web_audio((commands) => post({ type: "audio", commands }));
|
||||||
|
sounds.set_output(new WebAudioOutput(false));
|
||||||
|
}
|
||||||
|
await start_client();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.onmessage = (event: MessageEvent<WindowMessage>) => {
|
||||||
|
const message = event.data;
|
||||||
|
switch (message.type) {
|
||||||
|
case "start":
|
||||||
|
start(message);
|
||||||
|
break;
|
||||||
|
case "resize":
|
||||||
|
resize_canvas(message.width, message.height);
|
||||||
|
break;
|
||||||
|
case "key":
|
||||||
|
if (message.down) InputManager.key_down(message.code, message.key, message.shortcut);
|
||||||
|
else InputManager.key_up(message.code);
|
||||||
|
break;
|
||||||
|
case "text":
|
||||||
|
InputManager.type_text(message.text);
|
||||||
|
break;
|
||||||
|
case "button":
|
||||||
|
if (message.down) InputManager.mouse_down(message.button);
|
||||||
|
else InputManager.mouse_up(message.button);
|
||||||
|
break;
|
||||||
|
case "cursor":
|
||||||
|
InputManager.move_cursor(message.x, message.y);
|
||||||
|
break;
|
||||||
|
case "look":
|
||||||
|
if (grabbed) InputManager.look(message.x, message.y);
|
||||||
|
break;
|
||||||
|
case "scroll":
|
||||||
|
InputManager.scroll(message.amount);
|
||||||
|
break;
|
||||||
|
case "focus":
|
||||||
|
focused = message.focused;
|
||||||
|
if (focused) break;
|
||||||
|
InputManager.release_all();
|
||||||
|
// the window let go of it, the game asks again once it wants it
|
||||||
|
if (grabbed) {
|
||||||
|
lost_mouse = true;
|
||||||
|
grabbed = false;
|
||||||
|
post({ type: "grab", grab: false });
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "shown":
|
||||||
|
set_shown(message.shown);
|
||||||
|
break;
|
||||||
|
case "clipboard":
|
||||||
|
asking.get(message.id)?.(message.text);
|
||||||
|
asking.delete(message.id);
|
||||||
|
break;
|
||||||
|
case "audio_ended":
|
||||||
|
sources_ended(message.sources);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// what the desktop app's window (desktop/main.ts, on deno's main thread) and the client running in a worker (see
|
||||||
|
// main.ts here) tell each other. the window has the os's events and the client draws into it
|
||||||
|
|
||||||
|
// the window's surface, for deno's UnsafeWindowSurface. handles are pointers' addresses, pointers can't be posted
|
||||||
|
export interface SurfaceHandles {
|
||||||
|
system: "cocoa" | "win32" | "x11" | "wayland";
|
||||||
|
window: bigint;
|
||||||
|
display: bigint;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WindowMessage =
|
||||||
|
| {
|
||||||
|
type: "start";
|
||||||
|
page: string;
|
||||||
|
surface: SurfaceHandles;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
// what the client saved, see Platform.storage
|
||||||
|
storage: Record<string, string>;
|
||||||
|
// whether the window can play sound, see desktop/openal.ts
|
||||||
|
audio: boolean;
|
||||||
|
// the credits of the libraries the app comes with, see desktop/libraries.ts. an app older than its client
|
||||||
|
// (updated from the site) doesn't send them
|
||||||
|
credits?: string;
|
||||||
|
}
|
||||||
|
// in pixels, what's drawn to is this big now
|
||||||
|
| { type: "resize"; width: number; height: number }
|
||||||
|
// code like a KeyboardEvent's, key the letter for a shortcut (see InputManager.key_down), "" otherwise
|
||||||
|
| { type: "key"; down: boolean; code: string; key: string; shortcut: boolean }
|
||||||
|
| { type: "text"; text: string }
|
||||||
|
// buttons numbered like the dom's
|
||||||
|
| { type: "button"; down: boolean; button: number }
|
||||||
|
// the cursor, in pixels from the window's top left
|
||||||
|
| { type: "cursor"; x: number; y: number }
|
||||||
|
// the grabbed mouse moved
|
||||||
|
| { type: "look"; x: number; y: number }
|
||||||
|
// down is positive, about 100 for a notch, like the dom's
|
||||||
|
| { type: "scroll"; amount: number }
|
||||||
|
// the window lost or got focus, losing it lets go of the mouse
|
||||||
|
| { type: "focus"; focused: boolean }
|
||||||
|
// whether the window can be seen
|
||||||
|
| { type: "shown"; shown: boolean }
|
||||||
|
// the answer to read_clipboard, by the id it was asked with
|
||||||
|
| { type: "clipboard"; id: number; text: string }
|
||||||
|
// sources that played to their end, see web_audio.ts
|
||||||
|
| { type: "audio_ended"; sources: number[] };
|
||||||
|
|
||||||
|
export type ClientMessage =
|
||||||
|
| { type: "grab"; grab: boolean }
|
||||||
|
| { type: "fullscreen" }
|
||||||
|
// start the client over at page, see Platform.restart
|
||||||
|
| { type: "restart"; page: string }
|
||||||
|
| { type: "fatal"; message: string }
|
||||||
|
| { type: "read_clipboard"; id: number }
|
||||||
|
| { type: "write_clipboard"; text: string }
|
||||||
|
| { type: "store"; key: string; value: string }
|
||||||
|
| { type: "audio"; commands: AudioCommand[] };
|
||||||
|
|
||||||
|
// how a playing source sounds: everything between it and the speakers worked out, see web_audio.ts. gain 0 is silent
|
||||||
|
export interface SourceSettings {
|
||||||
|
gain: number;
|
||||||
|
pitch: number;
|
||||||
|
// where it is, with its distance falloff: full gain within ref_distance, fading linearly to 1 - rolloff at
|
||||||
|
// max_distance. undefined plays it as it is, not from anywhere
|
||||||
|
at: [number, number, number] | undefined;
|
||||||
|
ref_distance: number;
|
||||||
|
max_distance: number;
|
||||||
|
rolloff: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what the client's web audio has the window's openal do. ids are the client's own
|
||||||
|
export type AudioCommand =
|
||||||
|
// a decoded file, one array of samples a channel
|
||||||
|
| { op: "buffer"; id: number; channels: Float32Array[]; sample_rate: number }
|
||||||
|
| { op: "play"; id: number; buffer: number; loop: boolean; offset: number; settings: SourceSettings }
|
||||||
|
| { op: "set"; id: number; settings: SourceSettings }
|
||||||
|
| { op: "stop"; id: number }
|
||||||
|
| {
|
||||||
|
op: "listener";
|
||||||
|
position: [number, number, number];
|
||||||
|
forward: [number, number, number];
|
||||||
|
up: [number, number, number];
|
||||||
|
};
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the web audio api for the desktop app's client, which runs in deno with no audio of its own. only what
|
||||||
|
// client/audio_output.ts uses: buffer sources, gains and panners connected in a chain to the destination, the
|
||||||
|
// listener, and decoding the ogg files mods' sounds are (vorbis or opus). the window plays it with openal
|
||||||
|
// (desktop/openal.ts): each playing source is one openal source, its chain worked out into one gain, pitch and place
|
||||||
|
// at the end of every task something changed in. panners are all hrtf with linear distance, like cubi makes them
|
||||||
|
import decode_vorbis from "@audio/decode-vorbis";
|
||||||
|
import decode_opus from "@audio/decode-opus";
|
||||||
|
import type { AudioCommand, SourceSettings } from "./messages.ts";
|
||||||
|
|
||||||
|
type Vector = [number, number, number];
|
||||||
|
|
||||||
|
// sends what changed to the window
|
||||||
|
let send: (commands: AudioCommand[]) => void = () => {};
|
||||||
|
let next_id = 0;
|
||||||
|
// what's been started and hasn't ended, by id
|
||||||
|
const playing = new Map<number, BufferSource>();
|
||||||
|
|
||||||
|
class Param {
|
||||||
|
#value: number;
|
||||||
|
#context: Context;
|
||||||
|
|
||||||
|
constructor(context: Context, value: number) {
|
||||||
|
this.#context = context;
|
||||||
|
this.#value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
get value() {
|
||||||
|
return this.#value;
|
||||||
|
}
|
||||||
|
|
||||||
|
set value(value: number) {
|
||||||
|
this.#value = value;
|
||||||
|
this.#context.changed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Node {
|
||||||
|
readonly context: Context;
|
||||||
|
// where it plays into, cubi connects each node to one other
|
||||||
|
output: Node | undefined;
|
||||||
|
|
||||||
|
constructor(context: Context) {
|
||||||
|
this.context = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
connect<T extends Node>(destination: T): T {
|
||||||
|
this.output = destination;
|
||||||
|
this.context.changed();
|
||||||
|
return destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {
|
||||||
|
this.output = undefined;
|
||||||
|
this.context.changed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Destination extends Node {}
|
||||||
|
|
||||||
|
class Gain extends Node {
|
||||||
|
readonly gain: Param;
|
||||||
|
|
||||||
|
constructor(context: Context, options: { gain?: number } = {}) {
|
||||||
|
super(context);
|
||||||
|
this.gain = new Param(context, options.gain ?? 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PannerOptions {
|
||||||
|
panningModel?: string;
|
||||||
|
distanceModel?: string;
|
||||||
|
refDistance?: number;
|
||||||
|
maxDistance?: number;
|
||||||
|
rolloffFactor?: number;
|
||||||
|
positionX?: number;
|
||||||
|
positionY?: number;
|
||||||
|
positionZ?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Panner extends Node {
|
||||||
|
readonly positionX: Param;
|
||||||
|
readonly positionY: Param;
|
||||||
|
readonly positionZ: Param;
|
||||||
|
// openal plays every panner like this, whatever it's set to
|
||||||
|
panningModel = "HRTF";
|
||||||
|
distanceModel = "linear";
|
||||||
|
#ref_distance: number;
|
||||||
|
#max_distance: number;
|
||||||
|
#rolloff: number;
|
||||||
|
|
||||||
|
constructor(context: Context, options: PannerOptions = {}) {
|
||||||
|
super(context);
|
||||||
|
this.positionX = new Param(context, options.positionX ?? 0);
|
||||||
|
this.positionY = new Param(context, options.positionY ?? 0);
|
||||||
|
this.positionZ = new Param(context, options.positionZ ?? 0);
|
||||||
|
this.#ref_distance = options.refDistance ?? 1;
|
||||||
|
this.#max_distance = options.maxDistance ?? 10000;
|
||||||
|
this.#rolloff = options.rolloffFactor ?? 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
get refDistance() {
|
||||||
|
return this.#ref_distance;
|
||||||
|
}
|
||||||
|
set refDistance(value: number) {
|
||||||
|
this.#ref_distance = value;
|
||||||
|
this.context.changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
get maxDistance() {
|
||||||
|
return this.#max_distance;
|
||||||
|
}
|
||||||
|
set maxDistance(value: number) {
|
||||||
|
this.#max_distance = value;
|
||||||
|
this.context.changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
get rolloffFactor() {
|
||||||
|
return this.#rolloff;
|
||||||
|
}
|
||||||
|
set rolloffFactor(value: number) {
|
||||||
|
this.#rolloff = value;
|
||||||
|
this.context.changed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Buffer {
|
||||||
|
readonly sampleRate: number;
|
||||||
|
readonly length: number;
|
||||||
|
readonly numberOfChannels: number;
|
||||||
|
#channels: Float32Array[];
|
||||||
|
// once the window has it, see BufferSource.start
|
||||||
|
id: number | undefined;
|
||||||
|
|
||||||
|
constructor(channels: Float32Array[], sample_rate: number) {
|
||||||
|
this.#channels = channels;
|
||||||
|
this.sampleRate = sample_rate;
|
||||||
|
this.length = channels[0]?.length ?? 0;
|
||||||
|
this.numberOfChannels = channels.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
get duration() {
|
||||||
|
return this.length / this.sampleRate;
|
||||||
|
}
|
||||||
|
|
||||||
|
getChannelData(channel: number) {
|
||||||
|
return this.#channels[channel];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BufferSource extends Node {
|
||||||
|
readonly id = next_id++;
|
||||||
|
buffer: Buffer | null;
|
||||||
|
loop: boolean;
|
||||||
|
readonly playbackRate: Param;
|
||||||
|
onended: (() => void) | null = null;
|
||||||
|
// seconds into the buffer it starts at
|
||||||
|
offset = 0;
|
||||||
|
// what the window was last told, undefined before it was told to play it
|
||||||
|
sent: SourceSettings | undefined;
|
||||||
|
#started = false;
|
||||||
|
|
||||||
|
constructor(context: Context, options: { buffer?: Buffer; loop?: boolean; playbackRate?: number } = {}) {
|
||||||
|
super(context);
|
||||||
|
this.buffer = options.buffer ?? null;
|
||||||
|
this.loop = options.loop ?? false;
|
||||||
|
this.playbackRate = new Param(context, options.playbackRate ?? 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// it's always now, cubi starts sources as it makes them
|
||||||
|
start(_when = 0, offset = 0) {
|
||||||
|
if (this.#started) throw new Error("A source can only be started once");
|
||||||
|
this.#started = true;
|
||||||
|
this.offset = offset;
|
||||||
|
playing.set(this.id, this);
|
||||||
|
this.context.changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
if (!playing.has(this.id)) return;
|
||||||
|
if (this.sent) this.context.queue({ op: "stop", id: this.id });
|
||||||
|
this.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
end() {
|
||||||
|
playing.delete(this.id);
|
||||||
|
queueMicrotask(() => this.onended?.());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Listener {
|
||||||
|
readonly positionX: Param;
|
||||||
|
readonly positionY: Param;
|
||||||
|
readonly positionZ: Param;
|
||||||
|
readonly forwardX: Param;
|
||||||
|
readonly forwardY: Param;
|
||||||
|
readonly forwardZ: Param;
|
||||||
|
readonly upX: Param;
|
||||||
|
readonly upY: Param;
|
||||||
|
readonly upZ: Param;
|
||||||
|
|
||||||
|
constructor(context: Context) {
|
||||||
|
const param = (value: number) => new Param(context, value);
|
||||||
|
[this.positionX, this.positionY, this.positionZ] = [param(0), param(0), param(0)];
|
||||||
|
[this.forwardX, this.forwardY, this.forwardZ] = [param(0), param(0), param(-1)];
|
||||||
|
[this.upX, this.upY, this.upZ] = [param(0), param(1), param(0)];
|
||||||
|
}
|
||||||
|
|
||||||
|
setPosition(x: number, y: number, z: number) {
|
||||||
|
[this.positionX.value, this.positionY.value, this.positionZ.value] = [x, y, z];
|
||||||
|
}
|
||||||
|
|
||||||
|
setOrientation(x: number, y: number, z: number, up_x: number, up_y: number, up_z: number) {
|
||||||
|
[this.forwardX.value, this.forwardY.value, this.forwardZ.value] = [x, y, z];
|
||||||
|
[this.upX.value, this.upY.value, this.upZ.value] = [up_x, up_y, up_z];
|
||||||
|
}
|
||||||
|
|
||||||
|
command(): AudioCommand {
|
||||||
|
const values = (params: Param[]) => params.map((param) => param.value) as Vector;
|
||||||
|
return {
|
||||||
|
op: "listener",
|
||||||
|
position: values([this.positionX, this.positionY, this.positionZ]),
|
||||||
|
forward: values([this.forwardX, this.forwardY, this.forwardZ]),
|
||||||
|
up: values([this.upX, this.upY, this.upZ]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Context {
|
||||||
|
// there's no rule against playing before the player clicks, it plays right away
|
||||||
|
readonly state = "running";
|
||||||
|
readonly destination: Destination = new Destination(this);
|
||||||
|
readonly listener: Listener = new Listener(this);
|
||||||
|
#queued: AudioCommand[] = [];
|
||||||
|
#flushing = false;
|
||||||
|
#last_listener = "";
|
||||||
|
|
||||||
|
createGain() {
|
||||||
|
return new Gain(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
resume() {
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
for (const source of playing.values()) source.stop();
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ogg vorbis or ogg opus, by the first packet: after the first page's 27 byte header and its segment table
|
||||||
|
async decodeAudioData(data: ArrayBuffer): Promise<Buffer> {
|
||||||
|
const bytes = new Uint8Array(data);
|
||||||
|
const packet = 27 + (bytes[26] ?? 0);
|
||||||
|
const head = new TextDecoder().decode(bytes.subarray(packet, packet + 8));
|
||||||
|
const decode = head.startsWith("OpusHead") ? decode_opus : head.includes("vorbis") ? decode_vorbis : undefined;
|
||||||
|
if (!decode) throw new Error("Only ogg vorbis and ogg opus can be decoded");
|
||||||
|
const { channelData, sampleRate } = await decode(bytes);
|
||||||
|
if (!channelData.length || !channelData[0].length) throw new Error("There's no audio in it");
|
||||||
|
return new Buffer(channelData, sampleRate);
|
||||||
|
}
|
||||||
|
|
||||||
|
queue(command: AudioCommand) {
|
||||||
|
this.#queued.push(command);
|
||||||
|
this.changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// something about what plays changed, the window hears about it once this task is done
|
||||||
|
changed() {
|
||||||
|
if (this.#flushing) return;
|
||||||
|
this.#flushing = true;
|
||||||
|
queueMicrotask(() => this.#flush());
|
||||||
|
}
|
||||||
|
|
||||||
|
#flush() {
|
||||||
|
this.#flushing = false;
|
||||||
|
const commands = this.#queued;
|
||||||
|
this.#queued = [];
|
||||||
|
const listener = this.listener.command();
|
||||||
|
const listener_key = JSON.stringify(listener);
|
||||||
|
if (listener_key !== this.#last_listener) {
|
||||||
|
this.#last_listener = listener_key;
|
||||||
|
commands.push(listener);
|
||||||
|
}
|
||||||
|
for (const source of playing.values()) {
|
||||||
|
if (source.context !== this) continue;
|
||||||
|
const settings = source_settings(source);
|
||||||
|
if (!source.sent) {
|
||||||
|
const buffer = source.buffer;
|
||||||
|
if (!buffer) continue;
|
||||||
|
if (buffer.id === undefined) {
|
||||||
|
buffer.id = next_id++;
|
||||||
|
const channels = Array.from(
|
||||||
|
{ length: buffer.numberOfChannels },
|
||||||
|
(_, i) => buffer.getChannelData(i),
|
||||||
|
);
|
||||||
|
commands.push({ op: "buffer", id: buffer.id, channels, sample_rate: buffer.sampleRate });
|
||||||
|
}
|
||||||
|
commands.push({
|
||||||
|
op: "play",
|
||||||
|
id: source.id,
|
||||||
|
buffer: buffer.id,
|
||||||
|
loop: source.loop,
|
||||||
|
offset: source.offset,
|
||||||
|
settings,
|
||||||
|
});
|
||||||
|
} else if (!same_settings(source.sent, settings)) {
|
||||||
|
commands.push({ op: "set", id: source.id, settings });
|
||||||
|
}
|
||||||
|
source.sent = settings;
|
||||||
|
}
|
||||||
|
if (commands.length) send(commands);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the gains between source and destination multiplied, and the panner in between if there's one. silent when it
|
||||||
|
// isn't connected all the way
|
||||||
|
function source_settings(source: BufferSource): SourceSettings {
|
||||||
|
let gain = 1;
|
||||||
|
let panner: Panner | undefined;
|
||||||
|
let node = source.output;
|
||||||
|
while (node && !(node instanceof Destination)) {
|
||||||
|
if (node instanceof Gain) gain *= node.gain.value;
|
||||||
|
else if (node instanceof Panner) panner ??= node;
|
||||||
|
node = node.output;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
gain: node ? gain : 0,
|
||||||
|
pitch: source.playbackRate.value,
|
||||||
|
at: panner && [panner.positionX.value, panner.positionY.value, panner.positionZ.value],
|
||||||
|
ref_distance: panner?.refDistance ?? 1,
|
||||||
|
max_distance: panner?.maxDistance ?? 1,
|
||||||
|
rolloff: panner?.rolloffFactor ?? 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function same_settings(a: SourceSettings, b: SourceSettings) {
|
||||||
|
return a.gain === b.gain && a.pitch === b.pitch && a.at?.join() === b.at?.join() &&
|
||||||
|
a.ref_distance === b.ref_distance && a.max_distance === b.max_distance && a.rolloff === b.rolloff;
|
||||||
|
}
|
||||||
|
|
||||||
|
// makes AudioContext and its nodes globals, with to_window sending the window what to play
|
||||||
|
export function install_web_audio(to_window: (commands: AudioCommand[]) => void) {
|
||||||
|
send = to_window;
|
||||||
|
Object.assign(globalThis, {
|
||||||
|
AudioContext: Context,
|
||||||
|
GainNode: Gain,
|
||||||
|
PannerNode: Panner,
|
||||||
|
AudioBufferSourceNode: BufferSource,
|
||||||
|
AudioBuffer: Buffer,
|
||||||
|
AudioParam: Param,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// the window says these played to their end
|
||||||
|
export function sources_ended(ids: number[]) {
|
||||||
|
for (const id of ids) playing.get(id)?.end();
|
||||||
|
}
|
||||||
+8
-3
@@ -1,9 +1,11 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } from "$/common/protocol.ts";
|
import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } from "@/common/protocol.ts";
|
||||||
import type { ModListing } from "$/common/mod_loader.ts";
|
import type { ModListing } from "@/common/mod_loader.ts";
|
||||||
|
import { WorldShape } from "@/common/world_shape.ts";
|
||||||
import type { Join, ServerSocket, Welcome } from "./handshake.ts";
|
import type { Join, ServerSocket, Welcome } from "./handshake.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
export class Connection {
|
export class Connection {
|
||||||
#server: ServerSocket;
|
#server: ServerSocket;
|
||||||
@@ -12,6 +14,8 @@ export class Connection {
|
|||||||
mods: ModListing[];
|
mods: ModListing[];
|
||||||
// the server's block id for each of its numeric ids, for reading chunks
|
// the server's block id for each of its numeric ids, for reading chunks
|
||||||
server_blocks: string[];
|
server_blocks: string[];
|
||||||
|
// the dimension's height and sky light
|
||||||
|
shape: WorldShape;
|
||||||
spawn: { x: number; y: number; z: number; yaw: number; pitch: number };
|
spawn: { x: number; y: number; z: number; yaw: number; pitch: number };
|
||||||
selected_slot: number;
|
selected_slot: number;
|
||||||
// the slots mods added to menu 0
|
// the slots mods added to menu 0
|
||||||
@@ -27,6 +31,7 @@ export class Connection {
|
|||||||
this.name = join.name;
|
this.name = join.name;
|
||||||
this.mods = welcome.mods;
|
this.mods = welcome.mods;
|
||||||
this.server_blocks = join.blocks;
|
this.server_blocks = join.blocks;
|
||||||
|
this.shape = new WorldShape(join.shape);
|
||||||
this.spawn = join.spawn;
|
this.spawn = join.spawn;
|
||||||
this.selected_slot = join.selected_slot;
|
this.selected_slot = join.selected_slot;
|
||||||
this.player_menu = join.player_menu;
|
this.player_menu = join.player_menu;
|
||||||
@@ -55,5 +60,5 @@ export class Connection {
|
|||||||
|
|
||||||
// what the name field starts as, from ?name=
|
// what the name field starts as, from ?name=
|
||||||
export function default_player_name(): string {
|
export function default_player_name(): string {
|
||||||
return new URLSearchParams(location.search).get("name") ?? "";
|
return platform.page.searchParams.get("name") ?? "";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,13 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { KeyCode } from "./input_manager.ts";
|
import type { KeyCode } from "./input_manager.ts";
|
||||||
|
import type { Volumes } from "./sounds.ts";
|
||||||
|
|
||||||
// the player's settings, like minecraft's Options and its key mappings
|
// the player's settings, like minecraft's Options and its key mappings
|
||||||
export class Options {
|
export class Options {
|
||||||
render_distance = 16;
|
render_distance = 16;
|
||||||
|
// 0 to 1, each sound category's under master's, see client/sounds.ts
|
||||||
|
volume: Volumes = { master: 1, music: 1, ambient: 1, blocks: 1, entities: 1, players: 1, ui: 1 };
|
||||||
|
|
||||||
key_forward: KeyCode = "KeyW";
|
key_forward: KeyCode = "KeyW";
|
||||||
key_back: KeyCode = "KeyS";
|
key_back: KeyCode = "KeyS";
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { ServerMessage } from "$/common/protocol.ts";
|
import type { ServerMessage } from "@/common/protocol.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { Client } from "./client.ts";
|
import type { Client } from "./client.ts";
|
||||||
import { GuiModMenuScreen } from "./gui/gui_mod_screens.ts";
|
import { GuiModMenuScreen } from "./gui/gui_mod_screens.ts";
|
||||||
import { ClientMenu } from "./menu.ts";
|
import { ClientMenu } from "./menu.ts";
|
||||||
@@ -11,7 +11,8 @@ import { RemotePlayer } from "./entity/remote_player.ts";
|
|||||||
import { ItemEntity } from "./entity/item_entity.ts";
|
import { ItemEntity } from "./entity/item_entity.ts";
|
||||||
import { RemoteEntity } from "./entity/remote_entity.ts";
|
import { RemoteEntity } from "./entity/remote_entity.ts";
|
||||||
import { Player } from "./entity/player.ts";
|
import { Player } from "./entity/player.ts";
|
||||||
import { menu_screens, receive_mod_message } from "./mods.ts";
|
import { menu_screens, receive_mod_message, receive_overlay_message } from "./mods.ts";
|
||||||
|
import { sounds } from "./sounds.ts";
|
||||||
|
|
||||||
// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as
|
// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as
|
||||||
// fit in CHUNK_BUDGET_MS
|
// fit in CHUNK_BUDGET_MS
|
||||||
@@ -95,6 +96,9 @@ export class ClientPacketListener {
|
|||||||
case "flying":
|
case "flying":
|
||||||
client.player.flying = message.flying;
|
client.player.flying = message.flying;
|
||||||
break;
|
break;
|
||||||
|
case "creative":
|
||||||
|
client.player.creative = message.creative;
|
||||||
|
break;
|
||||||
case "effects":
|
case "effects":
|
||||||
client.player.effects = message.effects;
|
client.player.effects = message.effects;
|
||||||
break;
|
break;
|
||||||
@@ -142,7 +146,7 @@ export class ClientPacketListener {
|
|||||||
case "entity_data": {
|
case "entity_data": {
|
||||||
const entity = level.entities.get(message.id);
|
const entity = level.entities.get(message.id);
|
||||||
if (entity instanceof RemoteEntity) {
|
if (entity instanceof RemoteEntity) {
|
||||||
entity.data = message.data;
|
entity.set_data(message.data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -192,6 +196,20 @@ export class ClientPacketListener {
|
|||||||
case "break_progress":
|
case "break_progress":
|
||||||
level.set_break_progress(message.x, message.y, message.z, message.stage);
|
level.set_break_progress(message.x, message.y, message.z, message.stage);
|
||||||
break;
|
break;
|
||||||
|
case "sound": {
|
||||||
|
const at = message.at;
|
||||||
|
try {
|
||||||
|
sounds.play(message.sound, {
|
||||||
|
at: at && { x: at[0], y: at[1], z: at[2] },
|
||||||
|
follow: message.entity,
|
||||||
|
volume: message.volume,
|
||||||
|
pitch: message.pitch,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`the server played a sound this client can't:`, e);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "push": {
|
case "push": {
|
||||||
const player = client.player;
|
const player = client.player;
|
||||||
player.vx += message.motion[0];
|
player.vx += message.motion[0];
|
||||||
@@ -223,7 +241,7 @@ export class ClientPacketListener {
|
|||||||
level.set_center(message.x, message.z);
|
level.set_center(message.x, message.z);
|
||||||
break;
|
break;
|
||||||
case "chat":
|
case "chat":
|
||||||
if (message.overlay) client.game_renderer.hud.show_overlay(message.text);
|
if (message.overlay) receive_overlay_message(message.text);
|
||||||
else client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
|
else client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
|
||||||
break;
|
break;
|
||||||
case "suggestions":
|
case "suggestions":
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// what the client needs from where it runs: a browser page (browser_platform.ts), or the desktop app's window, where
|
||||||
|
// it runs in deno with no browser (native/). the entry point sets it before anything else runs
|
||||||
|
import type { GuiScreen } from "./gui/gui_screen.ts";
|
||||||
|
|
||||||
|
export interface Platform {
|
||||||
|
// the page's address. its query has the options (?server=, ?name=, ?singleplayer), and the client's own files
|
||||||
|
// (/assets/) and the desktop app's requests (/desktop/) are relative to it
|
||||||
|
page: URL;
|
||||||
|
// starts the client over at url, like loading the page again. a server's mods can't be taken back out once
|
||||||
|
// they're loaded, so leaving a server does this
|
||||||
|
restart(url: URL): void;
|
||||||
|
// calls frame once it's time for the next frame, with the time like performance.now()
|
||||||
|
request_frame(frame: (time: number) => void): void;
|
||||||
|
// calls shown when the game can be seen again after being hidden, there are no frames meanwhile. returns what
|
||||||
|
// stops calling it
|
||||||
|
on_shown(shown: () => void): () => void;
|
||||||
|
// what's remembered from one time to the next, like the servers whose mods the player trusts. it can throw, like a
|
||||||
|
// browser's in a private window
|
||||||
|
storage: Pick<Storage, "getItem" | "setItem">;
|
||||||
|
// while playing, leaving asks first
|
||||||
|
confirm_leaving(confirm: boolean): void;
|
||||||
|
// replaces the game with a message, for when it can't go on
|
||||||
|
show_fatal_error(message: string): void;
|
||||||
|
// who made what: the engine's assets/ASSETS.md, then each loaded mod's credits file
|
||||||
|
credits_screen(on_back: () => void): GuiScreen;
|
||||||
|
read_clipboard(): Promise<string>;
|
||||||
|
write_clipboard(text: string): Promise<void>;
|
||||||
|
// while the mouse is grabbed it turns the camera and there's no cursor
|
||||||
|
set_mouse_grabbed(grab: boolean): void;
|
||||||
|
is_mouse_grabbed(): boolean;
|
||||||
|
// whether the mouse was let go by something other than the game since the last call, like switching windows
|
||||||
|
take_lost_mouse(): boolean;
|
||||||
|
toggle_fullscreen(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export let platform: Platform;
|
||||||
|
|
||||||
|
export function set_platform(chosen: Platform) {
|
||||||
|
platform = chosen;
|
||||||
|
}
|
||||||
+176
@@ -0,0 +1,176 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// png decoding, for textures, skins and the gui. the desktop app's client runs without a browser, so it has no image
|
||||||
|
// decoding of its own, and both clients decoding the same way keeps them alike. pixels come out as stored: no color
|
||||||
|
// profile or gamma is applied, like an editor that ignores them
|
||||||
|
import { unzlibSync } from "fflate";
|
||||||
|
|
||||||
|
// rgba, 8 bits a channel, not premultiplied, row by row from the top
|
||||||
|
export interface Pixels {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
data: Uint8ClampedArray<ArrayBuffer>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
|
||||||
|
|
||||||
|
// by color type: gray, rgb, palette, gray and alpha, rgba
|
||||||
|
const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
|
||||||
|
|
||||||
|
// the 7 passes of an interlaced image: the first pixel's x and y, and the steps between pixels
|
||||||
|
const ADAM7 = [
|
||||||
|
[0, 0, 8, 8],
|
||||||
|
[4, 0, 8, 8],
|
||||||
|
[0, 4, 4, 8],
|
||||||
|
[2, 0, 4, 4],
|
||||||
|
[0, 2, 2, 4],
|
||||||
|
[1, 0, 2, 2],
|
||||||
|
[0, 1, 1, 2],
|
||||||
|
];
|
||||||
|
|
||||||
|
// throws for anything that isn't a png
|
||||||
|
export function decode_png(bytes: Uint8Array): Pixels {
|
||||||
|
if (bytes.length < 8 || SIGNATURE.some((byte, i) => bytes[i] !== byte)) throw new Error("Not a png");
|
||||||
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||||
|
|
||||||
|
let width = 0;
|
||||||
|
let height = 0;
|
||||||
|
let depth = 0;
|
||||||
|
let color_type = -1;
|
||||||
|
let interlaced = false;
|
||||||
|
let palette: Uint8Array | undefined;
|
||||||
|
// the alpha of each palette entry, or the one gray or rgb value that's see-through
|
||||||
|
let transparency: Uint8Array | undefined;
|
||||||
|
const compressed: Uint8Array[] = [];
|
||||||
|
|
||||||
|
let pos = 8;
|
||||||
|
while (pos + 8 <= bytes.length) {
|
||||||
|
const length = view.getUint32(pos);
|
||||||
|
const type = String.fromCharCode(...bytes.subarray(pos + 4, pos + 8));
|
||||||
|
const start = pos + 8;
|
||||||
|
const data = bytes.subarray(start, start + length);
|
||||||
|
pos = start + length + 4;
|
||||||
|
if (type === "IHDR") {
|
||||||
|
width = view.getUint32(start);
|
||||||
|
height = view.getUint32(start + 4);
|
||||||
|
depth = data[8];
|
||||||
|
color_type = data[9];
|
||||||
|
interlaced = data[12] === 1;
|
||||||
|
} else if (type === "PLTE") {
|
||||||
|
palette = data;
|
||||||
|
} else if (type === "tRNS") {
|
||||||
|
transparency = data;
|
||||||
|
} else if (type === "IDAT") {
|
||||||
|
compressed.push(data);
|
||||||
|
} else if (type === "IEND") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const channels = CHANNELS[color_type];
|
||||||
|
if (!channels || !width || !height || ![1, 2, 4, 8, 16].includes(depth)) throw new Error("Not a png");
|
||||||
|
if (color_type === 3 && !palette) throw new Error("A palette png without a palette");
|
||||||
|
|
||||||
|
const raw = unzlibSync(concat(compressed));
|
||||||
|
const pixels = new Uint8ClampedArray(width * height * 4);
|
||||||
|
const bits_per_pixel = channels * depth;
|
||||||
|
// filters work on whole bytes, a pixel's or 1 for pixels smaller than a byte
|
||||||
|
const filter_step = Math.max(1, bits_per_pixel >> 3);
|
||||||
|
// a sample at depth, scaled to 0-255
|
||||||
|
const max = (1 << depth) - 1;
|
||||||
|
const sample = (line: Uint8Array, index: number) => {
|
||||||
|
if (depth === 8) return line[index];
|
||||||
|
if (depth === 16) return (line[index * 2] << 8) | line[index * 2 + 1];
|
||||||
|
const bit = index * depth;
|
||||||
|
return (line[bit >> 3] >> (8 - depth - (bit & 7))) & max;
|
||||||
|
};
|
||||||
|
const to_byte = (value: number) => depth === 16 ? value >> 8 : depth === 8 ? value : Math.round(value * 255 / max);
|
||||||
|
const see_through = (value: number, channel: number) =>
|
||||||
|
(transparency![channel * 2] << 8 | transparency![channel * 2 + 1]) === value;
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
for (const [first_x, first_y, step_x, step_y] of interlaced ? ADAM7 : [[0, 0, 1, 1]]) {
|
||||||
|
const pass_width = Math.ceil((width - first_x) / step_x);
|
||||||
|
const pass_height = Math.ceil((height - first_y) / step_y);
|
||||||
|
if (pass_width <= 0 || pass_height <= 0) continue;
|
||||||
|
const stride = Math.ceil(pass_width * bits_per_pixel / 8);
|
||||||
|
let previous = new Uint8Array(stride);
|
||||||
|
for (let y = 0; y < pass_height; y++) {
|
||||||
|
if (offset + 1 + stride > raw.length) throw new Error("A png with too little image data");
|
||||||
|
const line = raw.slice(offset + 1, offset + 1 + stride);
|
||||||
|
unfilter(raw[offset], line, previous, filter_step);
|
||||||
|
offset += 1 + stride;
|
||||||
|
previous = line;
|
||||||
|
|
||||||
|
for (let x = 0; x < pass_width; x++) {
|
||||||
|
const out = ((first_y + y * step_y) * width + first_x + x * step_x) * 4;
|
||||||
|
const s = x * channels;
|
||||||
|
if (color_type === 3) {
|
||||||
|
const entry = sample(line, x);
|
||||||
|
pixels[out] = palette![entry * 3];
|
||||||
|
pixels[out + 1] = palette![entry * 3 + 1];
|
||||||
|
pixels[out + 2] = palette![entry * 3 + 2];
|
||||||
|
pixels[out + 3] = transparency && entry < transparency.length ? transparency[entry] : 255;
|
||||||
|
} else if (color_type === 0 || color_type === 4) {
|
||||||
|
const gray = sample(line, s);
|
||||||
|
pixels[out] = pixels[out + 1] = pixels[out + 2] = to_byte(gray);
|
||||||
|
pixels[out + 3] = color_type === 4
|
||||||
|
? to_byte(sample(line, s + 1))
|
||||||
|
: transparency && see_through(gray, 0)
|
||||||
|
? 0
|
||||||
|
: 255;
|
||||||
|
} else {
|
||||||
|
const [r, g, b] = [sample(line, s), sample(line, s + 1), sample(line, s + 2)];
|
||||||
|
pixels[out] = to_byte(r);
|
||||||
|
pixels[out + 1] = to_byte(g);
|
||||||
|
pixels[out + 2] = to_byte(b);
|
||||||
|
pixels[out + 3] = color_type === 6
|
||||||
|
? to_byte(sample(line, s + 3))
|
||||||
|
: transparency && see_through(r, 0) && see_through(g, 1) && see_through(b, 2)
|
||||||
|
? 0
|
||||||
|
: 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { width, height, data: pixels };
|
||||||
|
}
|
||||||
|
|
||||||
|
// undoes a line's filter in place, previous is the line above it, already undone
|
||||||
|
function unfilter(filter: number, line: Uint8Array, previous: Uint8Array, step: number) {
|
||||||
|
switch (filter) {
|
||||||
|
case 0:
|
||||||
|
return;
|
||||||
|
case 1:
|
||||||
|
for (let i = step; i < line.length; i++) line[i] += line[i - step];
|
||||||
|
return;
|
||||||
|
case 2:
|
||||||
|
for (let i = 0; i < line.length; i++) line[i] += previous[i];
|
||||||
|
return;
|
||||||
|
case 3:
|
||||||
|
for (let i = 0; i < line.length; i++) line[i] += ((i >= step ? line[i - step] : 0) + previous[i]) >> 1;
|
||||||
|
return;
|
||||||
|
case 4:
|
||||||
|
for (let i = 0; i < line.length; i++) {
|
||||||
|
const left = i >= step ? line[i - step] : 0;
|
||||||
|
const up = previous[i];
|
||||||
|
const up_left = i >= step ? previous[i - step] : 0;
|
||||||
|
const p = left + up - up_left;
|
||||||
|
const [pa, pb, pc] = [Math.abs(p - left), Math.abs(p - up), Math.abs(p - up_left)];
|
||||||
|
line[i] += pa <= pb && pa <= pc ? left : pb <= pc ? up : up_left;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
throw new Error("A png with an unknown filter");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function concat(parts: Uint8Array[]) {
|
||||||
|
const all = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
||||||
|
let at = 0;
|
||||||
|
for (const part of parts) {
|
||||||
|
all.set(part, at);
|
||||||
|
at += part.length;
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
}
|
||||||
+85
-17
@@ -3,12 +3,24 @@
|
|||||||
|
|
||||||
import type { Camera } from "../camera.ts";
|
import type { Camera } from "../camera.ts";
|
||||||
import { mat4 } from "gl-matrix";
|
import { mat4 } from "gl-matrix";
|
||||||
import type { RenderLayer } from "$/common/everything_registry.ts";
|
import type { RenderLayer } from "@/common/everything_registry.ts";
|
||||||
import { TERRAIN_VERTEX_BYTES } from "../workers/chunk_messages.ts";
|
import { TERRAIN_VERTEX_BYTES } from "../workers/chunk_messages.ts";
|
||||||
import { GpuTimer } from "./gpu_timing.ts";
|
import { GpuTimer } from "./gpu_timing.ts";
|
||||||
|
|
||||||
|
// what frames are drawn on: the page's canvas, or the desktop app's window (deno's UnsafeWindowSurface). setting
|
||||||
|
// width and height resizes it, like a canvas
|
||||||
|
export interface DrawSurface {
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
getContext(id: "webgpu"): unknown;
|
||||||
|
// shows what was drawn, the window's needs it after every frame, a canvas does it by itself
|
||||||
|
present?(): void;
|
||||||
|
// a canvas is shown scaled when its size is fixed, see set_canvas_size
|
||||||
|
style?: { width: string; height: string };
|
||||||
|
}
|
||||||
|
|
||||||
export let device: GPUDevice;
|
export let device: GPUDevice;
|
||||||
export let canvas: HTMLCanvasElement;
|
export let canvas: DrawSurface;
|
||||||
|
|
||||||
const MAX_SPRITES = 100000;
|
const MAX_SPRITES = 100000;
|
||||||
const VERTS_PER_SPRITE = 6;
|
const VERTS_PER_SPRITE = 6;
|
||||||
@@ -42,6 +54,8 @@ let canvas_format: GPUTextureFormat;
|
|||||||
|
|
||||||
let pipeline_2d: GPURenderPipeline;
|
let pipeline_2d: GPURenderPipeline;
|
||||||
let pipeline_3d: GPURenderPipeline;
|
let pipeline_3d: GPURenderPipeline;
|
||||||
|
// the same, drawing both sides of each face, see set_face_culling
|
||||||
|
let pipeline_3d_no_cull: GPURenderPipeline;
|
||||||
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
|
let terrain_pipelines: Record<RenderLayer, GPURenderPipeline>;
|
||||||
let instance_pipelines: { cutout: GPURenderPipeline; translucent: GPURenderPipeline };
|
let instance_pipelines: { cutout: GPURenderPipeline; translucent: GPURenderPipeline };
|
||||||
// 0 1 2 0 2 3 for every quad, shared by all solid and cutout chunk meshes
|
// 0 1 2 0 2 3 for every quad, shared by all solid and cutout chunk meshes
|
||||||
@@ -76,6 +90,7 @@ let current_texture: GPUTexture | null = null;
|
|||||||
export let white_tex: GPUTexture | null = null;
|
export let white_tex: GPUTexture | null = null;
|
||||||
|
|
||||||
let mode3d = false;
|
let mode3d = false;
|
||||||
|
let cull_faces = true;
|
||||||
|
|
||||||
let camera: Camera | undefined;
|
let camera: Camera | undefined;
|
||||||
|
|
||||||
@@ -100,8 +115,9 @@ let pending_destroy: GPUBuffer[] = [];
|
|||||||
// switches for finding out what a frame costs, see the f3 performance window. msaa is changed at the start of the next
|
// switches for finding out what a frame costs, see the f3 performance window. msaa is changed at the start of the next
|
||||||
// frame. split_passes gives each section (see gpu_section) passes of its own so the gpu times them apart, which costs
|
// frame. split_passes gives each section (see gpu_section) passes of its own so the gpu times them apart, which costs
|
||||||
// a little since every pass loads and stores the render targets. uncapped starts frames back to back instead of with
|
// a little since every pass loads and stores the render targets. uncapped starts frames back to back instead of with
|
||||||
// the display's refresh, see the game loop in main.ts
|
// the display's refresh, see the game loop in main.ts. render_regions draws terrain by region, see
|
||||||
export const render_debug = { msaa: false, split_passes: false, uncapped: false };
|
// ClientLevel.use_render_regions
|
||||||
|
export const render_debug = { msaa: false, split_passes: false, uncapped: false, render_regions: false };
|
||||||
// what was drawn, for the last whole frame
|
// what was drawn, for the last whole frame
|
||||||
export interface RenderStats {
|
export interface RenderStats {
|
||||||
draw_calls: number;
|
draw_calls: number;
|
||||||
@@ -116,6 +132,8 @@ export let gpu_timer: GpuTimer | undefined;
|
|||||||
export let adapter_info: GPUAdapterInfo | undefined;
|
export let adapter_info: GPUAdapterInfo | undefined;
|
||||||
// see set_canvas_size
|
// see set_canvas_size
|
||||||
let fixed_canvas_size: { width: number; height: number } | undefined;
|
let fixed_canvas_size: { width: number; height: number } | undefined;
|
||||||
|
// the space frames are shown in, the page's or the window's, see resize_canvas
|
||||||
|
let view_size = { width: 1800, height: 900 };
|
||||||
let resize_pending = false;
|
let resize_pending = false;
|
||||||
// what the passes starting now are timed as
|
// what the passes starting now are timed as
|
||||||
let gpu_label = "other";
|
let gpu_label = "other";
|
||||||
@@ -283,10 +301,10 @@ fn fs_translucent(in: VertexOut) -> @location(0) vec4<f32> {
|
|||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export async function init_window(canvas_element: HTMLCanvasElement) {
|
export async function init_window(surface: DrawSurface) {
|
||||||
canvas = canvas_element;
|
canvas = surface;
|
||||||
canvas.width = 1800;
|
canvas.width = view_size.width;
|
||||||
canvas.height = 900;
|
canvas.height = view_size.height;
|
||||||
|
|
||||||
if (!navigator.gpu) {
|
if (!navigator.gpu) {
|
||||||
throw new Error("WebGPU not supported");
|
throw new Error("WebGPU not supported");
|
||||||
@@ -409,6 +427,7 @@ export function end_drawing() {
|
|||||||
gpu_timer?.resolve(encoder!);
|
gpu_timer?.resolve(encoder!);
|
||||||
device.queue.submit([encoder!.finish()]);
|
device.queue.submit([encoder!.finish()]);
|
||||||
encoder = undefined;
|
encoder = undefined;
|
||||||
|
canvas.present?.();
|
||||||
gpu_timer?.read();
|
gpu_timer?.read();
|
||||||
|
|
||||||
for (const buffer of pending_destroy) {
|
for (const buffer of pending_destroy) {
|
||||||
@@ -495,6 +514,14 @@ export function set_render_time(ticks: number) {
|
|||||||
render_time = ticks % RENDER_TIME_PERIOD;
|
render_time = ticks % RENDER_TIME_PERIOD;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// whether 3d drawing leaves out faces seen from behind, true unless turned off. off draws both sides, like entity
|
||||||
|
// models do, where a flat cube's one face is seen from either side and an open box shows its inside
|
||||||
|
export function set_face_culling(cull: boolean) {
|
||||||
|
if (cull_faces === cull) return;
|
||||||
|
flush_batch();
|
||||||
|
cull_faces = cull;
|
||||||
|
}
|
||||||
|
|
||||||
export function end_mode_3d() {
|
export function end_mode_3d() {
|
||||||
if (!mode3d) {
|
if (!mode3d) {
|
||||||
return;
|
return;
|
||||||
@@ -539,7 +566,9 @@ export function flush_batch() {
|
|||||||
|
|
||||||
// what's bound for terrain draws in the current pass, so drawing hundreds of chunks doesn't bind the same things
|
// what's bound for terrain draws in the current pass, so drawing hundreds of chunks doesn't bind the same things
|
||||||
// again for each one. cleared whenever the pipeline changes
|
// again for each one. cleared whenever the pipeline changes
|
||||||
let terrain_binds: { slot: number; texture: GPUTexture; index_buffer: GPUBuffer } | undefined;
|
let terrain_binds:
|
||||||
|
| { slot: number; texture: GPUTexture; index_buffer: GPUBuffer; vertex_buffer: GPUBuffer }
|
||||||
|
| undefined;
|
||||||
|
|
||||||
// draws quads first to first + quad_count of a chunk mesh (4 vertices each). without an index buffer the quads are
|
// draws quads first to first + quad_count of a chunk mesh (4 vertices each). without an index buffer the quads are
|
||||||
// drawn in order
|
// drawn in order
|
||||||
@@ -578,9 +607,11 @@ export function draw_terrain(
|
|||||||
if (terrain_binds?.index_buffer !== index_buffer) {
|
if (terrain_binds?.index_buffer !== index_buffer) {
|
||||||
render_pass.setIndexBuffer(index_buffer, "uint32");
|
render_pass.setIndexBuffer(index_buffer, "uint32");
|
||||||
}
|
}
|
||||||
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer };
|
if (terrain_binds?.vertex_buffer !== vertex_buffer) {
|
||||||
|
|
||||||
render_pass.setVertexBuffer(0, vertex_buffer);
|
render_pass.setVertexBuffer(0, vertex_buffer);
|
||||||
|
}
|
||||||
|
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer, vertex_buffer };
|
||||||
|
|
||||||
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
|
render_pass.drawIndexed(quad_count * 6, 1, first * 6);
|
||||||
frame_stats.draw_calls += 1;
|
frame_stats.draw_calls += 1;
|
||||||
frame_stats.quads[layer] += quad_count;
|
frame_stats.quads[layer] += quad_count;
|
||||||
@@ -618,7 +649,13 @@ export function draw_instances(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// copies data into part of a buffer made with create_vertex_buffer, from data's first to last element
|
// copies data into part of a buffer made with create_vertex_buffer, from data's first to last element
|
||||||
export function write_buffer(buffer: GPUBuffer, byte_offset: number, data: Float32Array, first: number, count: number) {
|
export function write_buffer(
|
||||||
|
buffer: GPUBuffer,
|
||||||
|
byte_offset: number,
|
||||||
|
data: Float32Array | Uint8Array<ArrayBuffer>,
|
||||||
|
first: number,
|
||||||
|
count: number,
|
||||||
|
) {
|
||||||
device.queue.writeBuffer(buffer, byte_offset, data, first, count);
|
device.queue.writeBuffer(buffer, byte_offset, data, first, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -636,6 +673,25 @@ export function create_vertex_buffer(vertices: Float32Array<ArrayBuffer> | Uint8
|
|||||||
return buffer;
|
return buffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// an empty vertex buffer of size bytes that copy_buffer can copy from and to
|
||||||
|
export function create_copyable_vertex_buffer(size: number): GPUBuffer {
|
||||||
|
return device.createBuffer({
|
||||||
|
size: Math.max(4, size),
|
||||||
|
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// copies ranges of from into to on the gpu, as from offset, to offset and size in bytes, three numbers each. the copies
|
||||||
|
// happen before any later draw or write_buffer
|
||||||
|
export function copy_buffer(from: GPUBuffer, to: GPUBuffer, ranges: number[]) {
|
||||||
|
if (ranges.length === 0) return;
|
||||||
|
const copies = device.createCommandEncoder();
|
||||||
|
for (let i = 0; i < ranges.length; i += 3) {
|
||||||
|
copies.copyBufferToBuffer(from, ranges[i], to, ranges[i + 1], ranges[i + 2]);
|
||||||
|
}
|
||||||
|
device.queue.submit([copies.finish()]);
|
||||||
|
}
|
||||||
|
|
||||||
export function create_index_buffer(indices: Uint32Array): GPUBuffer {
|
export function create_index_buffer(indices: Uint32Array): GPUBuffer {
|
||||||
const buffer = device.createBuffer({
|
const buffer = device.createBuffer({
|
||||||
size: Math.max(4, indices.byteLength),
|
size: Math.max(4, indices.byteLength),
|
||||||
@@ -654,19 +710,23 @@ export function destroy_buffer(buffer: GPUBuffer) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resize_canvas() {
|
// the space frames are shown in changed to view_width × view_height, or the fixed size did
|
||||||
const width = fixed_canvas_size?.width ?? self.innerWidth;
|
export function resize_canvas(view_width = view_size.width, view_height = view_size.height) {
|
||||||
const height = fixed_canvas_size?.height ?? self.innerHeight;
|
view_size = { width: view_width, height: view_height };
|
||||||
|
const width = fixed_canvas_size?.width ?? view_width;
|
||||||
|
const height = fixed_canvas_size?.height ?? view_height;
|
||||||
// a fixed size is shown as big as it fits in the window
|
// a fixed size is shown as big as it fits in the window
|
||||||
const scale = Math.min(self.innerWidth / width, self.innerHeight / height);
|
const scale = Math.min(view_width / width, view_height / height);
|
||||||
|
|
||||||
if (canvas.width !== width || canvas.height !== height) {
|
if (canvas.width !== width || canvas.height !== height) {
|
||||||
canvas.width = width;
|
canvas.width = width;
|
||||||
canvas.height = height;
|
canvas.height = height;
|
||||||
// render targets get recreated at the start of the next frame
|
// render targets get recreated at the start of the next frame
|
||||||
}
|
}
|
||||||
|
if (canvas.style) {
|
||||||
canvas.style.width = width * scale + "px";
|
canvas.style.width = width * scale + "px";
|
||||||
canvas.style.height = height * scale + "px";
|
canvas.style.height = height * scale + "px";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// frames are drawn at this size whatever the window's, like the benchmark's, or at the window's again when it's
|
// frames are drawn at this size whatever the window's, like the benchmark's, or at the window's again when it's
|
||||||
@@ -802,7 +862,7 @@ function draw(buffer: GPUBuffer, offset: number, vertex_count: number) {
|
|||||||
|
|
||||||
const render_pass = ensure_pass();
|
const render_pass = ensure_pass();
|
||||||
|
|
||||||
const pipeline = mode3d ? pipeline_3d : pipeline_2d;
|
const pipeline = mode3d ? (cull_faces ? pipeline_3d : pipeline_3d_no_cull) : pipeline_2d;
|
||||||
if (current_pipeline !== pipeline) {
|
if (current_pipeline !== pipeline) {
|
||||||
render_pass.setPipeline(pipeline);
|
render_pass.setPipeline(pipeline);
|
||||||
current_pipeline = pipeline;
|
current_pipeline = pipeline;
|
||||||
@@ -1005,6 +1065,14 @@ function create_pipelines() {
|
|||||||
primitive: primitive_3d,
|
primitive: primitive_3d,
|
||||||
depthStencil: depth_3d,
|
depthStencil: depth_3d,
|
||||||
});
|
});
|
||||||
|
pipeline_3d_no_cull = device.createRenderPipeline({
|
||||||
|
layout,
|
||||||
|
vertex,
|
||||||
|
fragment,
|
||||||
|
multisample,
|
||||||
|
primitive: { ...primitive_3d, cullMode: "none" },
|
||||||
|
depthStencil: depth_3d,
|
||||||
|
});
|
||||||
|
|
||||||
const terrain_module = device.createShaderModule({ code: terrain_shader_src });
|
const terrain_module = device.createShaderModule({ code: terrain_shader_src });
|
||||||
const terrain_layout = device.createPipelineLayout({
|
const terrain_layout = device.createPipelineLayout({
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ let font_texture: Texture;
|
|||||||
let font_fnt: FntFont;
|
let font_fnt: FntFont;
|
||||||
|
|
||||||
export function init_font() {
|
export function init_font() {
|
||||||
font_texture = AssetManager.instance.get<Texture>("bworld:m6x11");
|
font_texture = AssetManager.instance.get<Texture>("cubi:m6x11");
|
||||||
|
|
||||||
font_fnt = parse_fnt(AssetManager.instance.get("bworld:m6x11_fnt"));
|
font_fnt = parse_fnt(AssetManager.instance.get("cubi:m6x11_fnt"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// bmfont's text format. glyphs in the image have transparent padding around them, which their offsets don't count, so
|
// bmfont's text format. glyphs in the image have transparent padding around them, which their offsets don't count, so
|
||||||
|
|||||||
@@ -3,10 +3,11 @@
|
|||||||
|
|
||||||
import { create_texture, device, push_quad, push_quad_vertices, use_texture } from "./core.ts";
|
import { create_texture, device, push_quad, push_quad_vertices, use_texture } from "./core.ts";
|
||||||
import { Texture } from "./types.ts";
|
import { Texture } from "./types.ts";
|
||||||
|
import type { Pixels } from "../png.ts";
|
||||||
|
|
||||||
export function load_texture(image: HTMLImageElement | ImageBitmap): Texture {
|
export function load_texture(image: Pixels): Texture {
|
||||||
const texture = create_texture(image.width, image.height);
|
const texture = create_texture(image.width, image.height);
|
||||||
device.queue.copyExternalImageToTexture({ source: image }, { texture }, [image.width, image.height]);
|
device.queue.writeTexture({ texture }, image.data, { bytesPerRow: image.width * 4 }, [image.width, image.height]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
tex: texture,
|
tex: texture,
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// playing clips (see ClipJson): what one does to the bones it moves at a time into it, sampled the way blockbench's
|
||||||
|
// timeline does a bedrock animation. what the format means comes from ports/blockbench: reading a file in
|
||||||
|
// js/formats/bedrock/bedrock_animation.js, picking and blending the keyframes around a time in
|
||||||
|
// js/animations/timeline_animators.js's interpolate(), the curves in js/animations/keyframe.js, and what that does to
|
||||||
|
// a bone in displayRotation/Position/Scale. no drawing here, so tests can use it
|
||||||
|
import type { ClipJson, ClipKeyframe } from "@/common/mod_data.ts";
|
||||||
|
import { lerp } from "@/common/worldgen/noise.ts";
|
||||||
|
import type { BoneOffsets, Vec3 } from "./model_math.ts";
|
||||||
|
|
||||||
|
// a keyframe this close to the time is the one it's on, in seconds
|
||||||
|
const ON_KEYFRAME = 1 / 1200;
|
||||||
|
|
||||||
|
// a bone nothing has moved
|
||||||
|
export function rest_offsets(): BoneOffsets {
|
||||||
|
return { rotation: [0, 0, 0], position: [0, 0, 0], scale: [1, 1, 1] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// adds what clip does seconds into it to each bone's offsets, scaled by weight: rotation and position times weight,
|
||||||
|
// scale weight of the way from 1. a clip that loops wraps around its length, one that doesn't stays on its last frame
|
||||||
|
export function sample_clip(clip: ClipJson, seconds: number, offsets: Map<string, BoneOffsets>, weight = 1) {
|
||||||
|
const time = clip.loop && clip.length > 0 ? ((seconds % clip.length) + clip.length) % clip.length : seconds;
|
||||||
|
for (const [bone, channels] of Object.entries(clip.bones)) {
|
||||||
|
let offset = offsets.get(bone);
|
||||||
|
if (!offset) {
|
||||||
|
offset = rest_offsets();
|
||||||
|
offsets.set(bone, offset);
|
||||||
|
}
|
||||||
|
for (const channel of ["rotation", "position"] as const) {
|
||||||
|
const keyframes = channels[channel];
|
||||||
|
if (!keyframes) continue;
|
||||||
|
const value = sample_channel(keyframes, time, clip.loop);
|
||||||
|
for (let i = 0; i < 3; i++) offset[channel][i] += value[i] * weight;
|
||||||
|
}
|
||||||
|
if (channels.scale) {
|
||||||
|
const value = sample_channel(channels.scale, time, clip.loop);
|
||||||
|
for (let i = 0; i < 3; i++) offset.scale[i] *= 1 + (value[i] - 1) * weight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a channel's value at time, from the keyframes around it. on a keyframe it's what it comes in at, and before the
|
||||||
|
// first or after the last it's that keyframe's
|
||||||
|
export function sample_channel(keyframes: ClipKeyframe[], time: number, loop: boolean): Vec3 {
|
||||||
|
let after = keyframes.findIndex((keyframe) => keyframe.time >= time);
|
||||||
|
if (after === -1) after = keyframes.length;
|
||||||
|
const from = keyframes[after - 1];
|
||||||
|
const to = keyframes[after];
|
||||||
|
if (from && time - from.time < ON_KEYFRAME) return from.pre;
|
||||||
|
if (to && to.time - time < ON_KEYFRAME) return to.pre;
|
||||||
|
if (!to) return from.post;
|
||||||
|
if (!from) return to.pre;
|
||||||
|
|
||||||
|
const t = (time - from.time) / (to.time - from.time);
|
||||||
|
if (!from.smooth && !to.smooth) return [0, 1, 2].map((i) => lerp(t, from.post[i], to.pre[i])) as Vec3;
|
||||||
|
// through the keyframes either side too, wrapping around a loop of three or more, whose first and last are the same
|
||||||
|
// moment. where there's none, or the one next to it jumps, the curve starts or ends at the next one's value again
|
||||||
|
let before: ClipKeyframe | undefined = keyframes[after - 2];
|
||||||
|
let beyond: ClipKeyframe | undefined = keyframes[after + 1];
|
||||||
|
if (loop && keyframes.length >= 3) {
|
||||||
|
before ??= keyframes.at(-2);
|
||||||
|
beyond ??= keyframes[1];
|
||||||
|
}
|
||||||
|
const p0 = before && same(from.pre, from.post) ? before.post : from.post;
|
||||||
|
const p3 = beyond && same(to.pre, to.post) ? beyond.pre : to.pre;
|
||||||
|
return [0, 1, 2].map((i) => catmullrom(t, p0[i], from.post[i], to.pre[i], p3[i])) as Vec3;
|
||||||
|
}
|
||||||
|
|
||||||
|
function same(a: Vec3, b: Vec3) {
|
||||||
|
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
|
||||||
|
}
|
||||||
|
|
||||||
|
// a uniform catmull-rom spline from p1 at t 0 to p2 at t 1
|
||||||
|
function catmullrom(t: number, p0: number, p1: number, p2: number, p3: number) {
|
||||||
|
const v0 = (p2 - p0) / 2;
|
||||||
|
const v1 = (p3 - p1) / 2;
|
||||||
|
return (2 * p1 - 2 * p2 + v0 + v1) * t ** 3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t ** 2 + v0 * t + p1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// mods' entity animators, see ClientRender.register_entity_animator and docs/modding/entities/index.md#animators. each
|
||||||
|
// entity of a type with one gets its own, made with the entity, which says what its model's bones do every frame it's
|
||||||
|
// drawn
|
||||||
|
import type { AnimatedEntity, Clip, EntityAnimator, EntityPose } from "@/common/mod_api/client.ts";
|
||||||
|
import type { ClipJson } from "@/common/mod_data.ts";
|
||||||
|
import type { EntityData } from "@/common/protocol.ts";
|
||||||
|
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import { wrap_angle } from "@/common/utils.ts";
|
||||||
|
import { rest_offsets, sample_clip } from "./animation.ts";
|
||||||
|
import type { BoneOffsets } from "./model_math.ts";
|
||||||
|
|
||||||
|
export interface AnimatorRegistration {
|
||||||
|
mod: string;
|
||||||
|
create: (entity: AnimatedEntity) => EntityAnimator;
|
||||||
|
}
|
||||||
|
|
||||||
|
// by entity type
|
||||||
|
export const entity_animators = new Map<string, AnimatorRegistration>();
|
||||||
|
|
||||||
|
// what an animator reads of its entity, a RemoteEntity's
|
||||||
|
export interface AnimatorSource {
|
||||||
|
readonly id: string;
|
||||||
|
readonly type: string;
|
||||||
|
readonly data: EntityData;
|
||||||
|
// ticks since this client got it
|
||||||
|
readonly age: number;
|
||||||
|
readonly yaw: number;
|
||||||
|
readonly head_yaw: number;
|
||||||
|
readonly pitch: number;
|
||||||
|
walk_animation(partial_tick: number): { position: number; speed: number };
|
||||||
|
attack_animation(partial_tick: number): number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEGREES = 180 / Math.PI;
|
||||||
|
|
||||||
|
// one entity's animator, undefined for a type without one
|
||||||
|
export function animation_for(source: AnimatorSource): EntityAnimation | undefined {
|
||||||
|
const registration = entity_animators.get(source.type);
|
||||||
|
return registration && new EntityAnimation(source, registration);
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EntityAnimation {
|
||||||
|
#source: AnimatorSource;
|
||||||
|
#mod: string;
|
||||||
|
#entity: AnimatedEntity;
|
||||||
|
#animator: EntityAnimator | undefined;
|
||||||
|
|
||||||
|
constructor(source: AnimatorSource, { mod, create }: AnimatorRegistration) {
|
||||||
|
this.#source = source;
|
||||||
|
this.#mod = mod;
|
||||||
|
this.#entity = animated_entity(source);
|
||||||
|
this.#run("create", () => this.#animator = create(this.#entity));
|
||||||
|
for (const field of Object.keys(client_data(source.data))) this.#on_data(field);
|
||||||
|
}
|
||||||
|
|
||||||
|
// its client data was before and is now the source's
|
||||||
|
data_changed(before: EntityData) {
|
||||||
|
const old = client_data(before);
|
||||||
|
const now = client_data(this.#source.data);
|
||||||
|
for (const field of new Set([...Object.keys(old), ...Object.keys(now)])) {
|
||||||
|
if (JSON.stringify(old[field]) !== JSON.stringify(now[field])) this.#on_data(field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// what the animator does to the bones at time, undefined when there's no animator (anymore)
|
||||||
|
pose(time: number): Map<string, BoneOffsets> | undefined {
|
||||||
|
const animator = this.#animator;
|
||||||
|
if (!animator) return undefined;
|
||||||
|
const offsets = new Map<string, BoneOffsets>();
|
||||||
|
const posed = this.#run("pose", () => animator.pose(entity_pose(offsets, this.#entity), time));
|
||||||
|
return posed ? offsets : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the sound its next step makes, what the animator says when it has a step_sound, own otherwise
|
||||||
|
step_sound(own: string | undefined): string | undefined {
|
||||||
|
const animator = this.#animator;
|
||||||
|
if (!animator?.step_sound) return own;
|
||||||
|
let sound: string | undefined;
|
||||||
|
return this.#run("step_sound", () => sound = animator.step_sound!()) ? sound : own;
|
||||||
|
}
|
||||||
|
|
||||||
|
#on_data(field: string) {
|
||||||
|
const animator = this.#animator;
|
||||||
|
if (animator?.on_data) this.#run("on_data", () => animator.on_data!(field, this.#source.age));
|
||||||
|
}
|
||||||
|
|
||||||
|
// false when it threw, which is logged with the mod and the entity, and the animator is gone
|
||||||
|
#run(what: string, fn: () => void) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
const { type, id } = this.#source;
|
||||||
|
console.error(`[${this.#mod}] the animator of ${type} ${id} threw in ${what}, it's removed:`, e);
|
||||||
|
this.#animator = undefined;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function client_data(data: EntityData): Record<string, unknown> {
|
||||||
|
return (data.client_data ?? {}) as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function animated_entity(source: AnimatorSource): AnimatedEntity {
|
||||||
|
// time is in ticks with the part of the next one, the source's walk and attack take that part
|
||||||
|
const partial = (time: number) => Math.min(Math.max(time - source.age, 0), 1);
|
||||||
|
return {
|
||||||
|
get id() {
|
||||||
|
return source.id;
|
||||||
|
},
|
||||||
|
get type() {
|
||||||
|
return source.type;
|
||||||
|
},
|
||||||
|
get_client_data: (field) => structuredClone(client_data(source.data)[field]) as never,
|
||||||
|
walk_position: (time) => source.walk_animation(partial(time)).position,
|
||||||
|
walk_speed: (time) => source.walk_animation(partial(time)).speed,
|
||||||
|
attack_progress: (time) => source.attack_animation(partial(time)),
|
||||||
|
// mirrored like a model's rotations, see model_math's own_matrix
|
||||||
|
get head_pitch() {
|
||||||
|
return -source.pitch * DEGREES;
|
||||||
|
},
|
||||||
|
get head_yaw() {
|
||||||
|
return -wrap_angle(source.head_yaw - source.yaw) * DEGREES;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// a clip by what ClientRender.clip gave
|
||||||
|
function clip_json(clip: Clip): ClipJson {
|
||||||
|
const json = EverythingRegistry.get<ClipJson>("animations", clip?.id);
|
||||||
|
if (!json) throw new Error(`${clip?.id} isn't a clip, see ctx.render.clip`);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
function entity_pose(offsets: Map<string, BoneOffsets>, entity: AnimatedEntity): EntityPose {
|
||||||
|
const offset = (bone: string) => {
|
||||||
|
let found = offsets.get(bone);
|
||||||
|
if (!found) {
|
||||||
|
found = rest_offsets();
|
||||||
|
offsets.set(bone, found);
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
};
|
||||||
|
const pose: EntityPose = {
|
||||||
|
play(clip, seconds, weight = 1) {
|
||||||
|
sample_clip(clip_json(clip), seconds, offsets, weight);
|
||||||
|
},
|
||||||
|
play_state(clip, state, time, weight) {
|
||||||
|
if (state.started) pose.play(clip, state.seconds(time), weight);
|
||||||
|
},
|
||||||
|
play_walk(clip, walker, time, speed_scale = 1) {
|
||||||
|
pose.play(clip, walker.walk_position(time) / 20, Math.min(walker.walk_speed(time) * speed_scale, 1));
|
||||||
|
},
|
||||||
|
rotate(bone, x, y, z) {
|
||||||
|
const rotation = offset(bone).rotation;
|
||||||
|
rotation[0] += x;
|
||||||
|
rotation[1] += y;
|
||||||
|
rotation[2] += z;
|
||||||
|
},
|
||||||
|
move(bone, x, y, z) {
|
||||||
|
const position = offset(bone).position;
|
||||||
|
position[0] += x;
|
||||||
|
position[1] += y;
|
||||||
|
position[2] += z;
|
||||||
|
},
|
||||||
|
scale(bone, x, y, z) {
|
||||||
|
const scale = offset(bone).scale;
|
||||||
|
scale[0] *= x;
|
||||||
|
scale[1] *= y;
|
||||||
|
scale[2] *= z;
|
||||||
|
},
|
||||||
|
look(bone) {
|
||||||
|
pose.rotate(bone, entity.head_pitch, entity.head_yaw, 0);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return pose;
|
||||||
|
}
|
||||||
@@ -3,9 +3,9 @@
|
|||||||
|
|
||||||
// lighting entities like minecraft: one light level per entity each frame, at its eyes, looked up in the same lightmap
|
// lighting entities like minecraft: one light level per entity each frame, at its eyes, looked up in the same lightmap
|
||||||
// as terrain and multiplied into its vertex colors. burning ones have full block light
|
// as terrain and multiplied into its vertex colors. burning ones have full block light
|
||||||
import type { Entity } from "$/client/entity/entity.ts";
|
import type { Entity } from "@/client/entity/entity.ts";
|
||||||
import type { ClientLevel } from "$/client/level/client_level.ts";
|
import type { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
import { light_color } from "$/client/renderer/mod.ts";
|
import { light_color } from "@/client/renderer/mod.ts";
|
||||||
import type { Vec3 } from "./player_renderer.ts";
|
import type { Vec3 } from "./player_renderer.ts";
|
||||||
|
|
||||||
// the color for the light at a point, times tint (like the hurt flash)
|
// the color for the light at a point, times tint (like the hurt flash)
|
||||||
|
|||||||
@@ -1,22 +1,25 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. there are no
|
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. the model
|
||||||
// animation files yet: the model turns to the entity's yaw, a bone named "head" to where it looks, and bones named
|
// turns to the entity's yaw, and its bones are posed by its type's animator from a mod (see entity_animators.ts). without
|
||||||
// like minecraft's humanoid ones (right_arm, left_arm, right_leg, left_leg) swing as it walks, the right arm when it
|
// one, a bone named "head" turns to where it looks, and bones named like minecraft's humanoid ones (right_arm, left_arm,
|
||||||
// attacks too. entities without a model are their texture facing the camera, like minecraft's fishing hook
|
// right_leg, left_leg) swing as it walks, the right arm when it attacks too. entities without a model are their texture
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
// facing the camera, like minecraft's fishing hook, and objects without one are the item they hold
|
||||||
import type { Camera } from "$/client/camera.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import type { RemoteEntity } from "$/client/entity/remote_entity.ts";
|
import type { Camera } from "@/client/camera.ts";
|
||||||
import { push_vertex, type Texture } from "$/client/renderer/mod.ts";
|
import type { RemoteEntity } from "@/client/entity/remote_entity.ts";
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { push_vertex, type Texture } from "@/client/renderer/mod.ts";
|
||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts";
|
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import type { EntityBoneJson, EntityJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
import { HURT_TINT } from "./player_renderer.ts";
|
import { HURT_TINT } from "./player_renderer.ts";
|
||||||
import { IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
import { bone_matrices, IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
||||||
import { push_model } from "./model_renderer.ts";
|
import { push_model } from "./model_renderer.ts";
|
||||||
import { entity_tint } from "./entity_light.ts";
|
import { entity_tint } from "./entity_light.ts";
|
||||||
|
import { push_item, synced_stack } from "./item_renderer.ts";
|
||||||
|
import type { ItemData } from "@/common/inventory.ts";
|
||||||
|
|
||||||
// models are in texture pixels, 16 to a block
|
// models are in texture pixels, 16 to a block
|
||||||
const PIXEL = 1 / 16;
|
const PIXEL = 1 / 16;
|
||||||
@@ -25,27 +28,47 @@ const PIXEL = 1 / 16;
|
|||||||
export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_tick: number) {
|
export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_tick: number) {
|
||||||
const json = EverythingRegistry.get<EntityJson>("entities", entity.type);
|
const json = EverythingRegistry.get<EntityJson>("entities", entity.type);
|
||||||
if (!json) return;
|
if (!json) return;
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
const region = get_sprite_region(json.texture);
|
|
||||||
const hurt = entity.hurt_time > 0 || entity.dead ? HURT_TINT : undefined;
|
const hurt = entity.hurt_time > 0 || entity.dead ? HURT_TINT : undefined;
|
||||||
const tint = entity_tint(entity, partial_tick, hurt, entity.data.on_fire === true);
|
const tint = entity_tint(entity, partial_tick, hurt, entity.data.on_fire === true);
|
||||||
|
const scale = json.scale ?? 1;
|
||||||
if (json.model === undefined) {
|
if (json.model === undefined) {
|
||||||
render_sprite(entity, camera, atlas, region, partial_tick, tint);
|
// an object is the item it holds, the size the item's model is made
|
||||||
|
const item = entity.data.item as ItemData | undefined;
|
||||||
|
if (json.behavior === "object") {
|
||||||
|
if (item) push_item(atlas, synced_stack(item), turned_with(entity, partial_tick, scale), tint);
|
||||||
|
} else if (json.texture !== undefined) {
|
||||||
|
render_sprite(entity, camera, atlas, get_sprite_region(json.texture), scale, partial_tick, tint);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const model = EverythingRegistry.get<EntityModelJson>("entity_models", json.model);
|
const model = EverythingRegistry.get<EntityModelJson>("entity_models", json.model);
|
||||||
if (!model) return;
|
if (!model || json.texture === undefined) return;
|
||||||
|
|
||||||
|
const placed = turned_with(entity, partial_tick, scale);
|
||||||
|
const to_world = (px: number, py: number, pz: number) => placed(px * PIXEL, py * PIXEL, pz * PIXEL);
|
||||||
|
const offsets = entity.animation?.pose(entity.age + partial_tick);
|
||||||
|
const pose = offsets ? () => IDENTITY : default_pose(entity, partial_tick);
|
||||||
|
const region = get_sprite_region(json.texture);
|
||||||
|
push_model(model, bone_matrices(model, pose, offsets), atlas, region, to_world, tint);
|
||||||
|
}
|
||||||
|
|
||||||
|
// from blocks around the entity's feet, its own way round, to the world: sized by scale and turned to its yaw
|
||||||
|
function turned_with(entity: RemoteEntity, partial_tick: number, scale: number) {
|
||||||
const { x, y, z } = entity.render_position(partial_tick);
|
const { x, y, z } = entity.render_position(partial_tick);
|
||||||
const yaw_sin = Math.sin(entity.yaw);
|
const yaw_sin = Math.sin(entity.yaw) * scale;
|
||||||
const yaw_cos = Math.cos(entity.yaw);
|
const yaw_cos = Math.cos(entity.yaw) * scale;
|
||||||
const to_world = (px: number, py: number, pz: number): Vec3 => {
|
return (bx: number, by: number, bz: number): Vec3 => [
|
||||||
const [mx, my, mz] = [px * PIXEL, py * PIXEL, pz * PIXEL];
|
x + bx * yaw_cos + bz * yaw_sin,
|
||||||
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
|
y + by * scale,
|
||||||
};
|
z - bx * yaw_sin + bz * yaw_cos,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// the head looking and the humanoid swing, for an entity without an animator
|
||||||
|
function default_pose(entity: RemoteEntity, partial_tick: number) {
|
||||||
const limbs = limb_angles(entity, partial_tick);
|
const limbs = limb_angles(entity, partial_tick);
|
||||||
const pose = (bone: EntityBoneJson) => {
|
return (bone: EntityBoneJson) => {
|
||||||
let matrix = IDENTITY;
|
let matrix = IDENTITY;
|
||||||
if (bone.name === "head") {
|
if (bone.name === "head") {
|
||||||
matrix = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0);
|
matrix = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0);
|
||||||
@@ -54,7 +77,6 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_
|
|||||||
if (limb) matrix = multiply(rotation_around(model_pivot(bone), limb, 0, 0), matrix);
|
if (limb) matrix = multiply(rotation_around(model_pivot(bone), limb, 0, 0), matrix);
|
||||||
return matrix;
|
return matrix;
|
||||||
};
|
};
|
||||||
push_model(model, pose, atlas, region, to_world, tint);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// how far each humanoid limb turns forward (radians), like minecraft's HumanoidModel.setupAnim: arms and legs swing
|
// how far each humanoid limb turns forward (radians), like minecraft's HumanoidModel.setupAnim: arms and legs swing
|
||||||
@@ -79,14 +101,15 @@ function render_sprite(
|
|||||||
camera: Camera,
|
camera: Camera,
|
||||||
atlas: Texture,
|
atlas: Texture,
|
||||||
region: SpriteRegion,
|
region: SpriteRegion,
|
||||||
|
scale: number,
|
||||||
partial_tick: number,
|
partial_tick: number,
|
||||||
[r, g, b]: Vec3,
|
[r, g, b]: Vec3,
|
||||||
) {
|
) {
|
||||||
const { x, y, z } = entity.render_position(partial_tick);
|
const { x, y, z } = entity.render_position(partial_tick);
|
||||||
const cy = y + entity.height / 2;
|
const cy = y + entity.height / 2;
|
||||||
// the camera's right and up, halved to the sprite's size
|
// the camera's right and up, halved to the sprite's size
|
||||||
const half_width = region.width * PIXEL / 2;
|
const half_width = region.width * PIXEL * scale / 2;
|
||||||
const half_height = region.height * PIXEL / 2;
|
const half_height = region.height * PIXEL * scale / 2;
|
||||||
const [yaw_sin, yaw_cos] = [Math.sin(camera.yaw), Math.cos(camera.yaw)];
|
const [yaw_sin, yaw_cos] = [Math.sin(camera.yaw), Math.cos(camera.yaw)];
|
||||||
const [pitch_sin, pitch_cos] = [Math.sin(camera.pitch), Math.cos(camera.pitch)];
|
const [pitch_sin, pitch_cos] = [Math.sin(camera.pitch), Math.cos(camera.pitch)];
|
||||||
const right: Vec3 = [yaw_cos * half_width, 0, -yaw_sin * half_width];
|
const right: Vec3 = [yaw_cos * half_width, 0, -yaw_sin * half_width];
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { Client } from "$/client/client.ts";
|
import type { Client } from "@/client/client.ts";
|
||||||
import type { Camera } from "$/client/camera.ts";
|
import type { Camera } from "@/client/camera.ts";
|
||||||
import type { ClientLevel } from "$/client/level/client_level.ts";
|
import type { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
import {
|
import {
|
||||||
begin_mode_3d,
|
begin_mode_3d,
|
||||||
canvas,
|
canvas,
|
||||||
@@ -12,14 +12,14 @@ import {
|
|||||||
end_mode_3d,
|
end_mode_3d,
|
||||||
set_render_time,
|
set_render_time,
|
||||||
update_lightmap,
|
update_lightmap,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { daylight } from "$/common/time.ts";
|
import { daylight } from "@/common/time.ts";
|
||||||
import { Hud } from "$/client/gui/hud.ts";
|
import { Hud } from "@/client/gui/hud.ts";
|
||||||
import { DebugOverlay } from "$/client/gui/debug_overlay.ts";
|
import { DebugOverlay } from "@/client/gui/debug_overlay.ts";
|
||||||
import { LevelRenderer } from "./level_renderer.ts";
|
import { LevelRenderer } from "./level_renderer.ts";
|
||||||
import { HandRenderer } from "./hand_renderer.ts";
|
import { HandRenderer } from "./hand_renderer.ts";
|
||||||
import { render_nameplates } from "./nameplate_renderer.ts";
|
import { render_nameplates } from "./nameplate_renderer.ts";
|
||||||
import { profiler } from "$/client/profiler.ts";
|
import { profiler } from "@/client/profiler.ts";
|
||||||
|
|
||||||
// the sky at noon and in the middle of the night
|
// the sky at noon and in the middle of the night
|
||||||
const DAY_SKY = [0.69, 0.8, 1];
|
const DAY_SKY = [0.69, 0.8, 1];
|
||||||
@@ -56,7 +56,7 @@ export class GameRenderer {
|
|||||||
const { x, y, z } = client.camera;
|
const { x, y, z } = client.camera;
|
||||||
const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
|
const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
|
||||||
if (!client.level.is_fluid(bx, by, bz)) return;
|
if (!client.level.is_fluid(bx, by, bz)) return;
|
||||||
const color = client.level.water_color(bx, bz);
|
const color = client.level.water_color(bx, by, bz);
|
||||||
draw_rect(0, 0, canvas.width, canvas.height, [
|
draw_rect(0, 0, canvas.width, canvas.height, [
|
||||||
(color >> 16) / 255,
|
(color >> 16) / 255,
|
||||||
((color >> 8) & 0xff) / 255,
|
((color >> 8) & 0xff) / 255,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// they wear, like their curios. the gui has no depth buffer, so the faces are drawn back to front with the ones facing
|
// they wear, like their curios. the gui has no depth buffer, so the faces are drawn back to front with the ones facing
|
||||||
// away left out, like 3d items in slots
|
// away left out, like 3d items in slots
|
||||||
import { push_vertex, type Texture, use_texture } from "../renderer/mod.ts";
|
import { push_vertex, type Texture, use_texture } from "../renderer/mod.ts";
|
||||||
import type { ItemStack } from "$/common/inventory.ts";
|
import type { ItemStack } from "@/common/inventory.ts";
|
||||||
import { AssetManager } from "../assets.ts";
|
import { AssetManager } from "../assets.ts";
|
||||||
import { rotation_around } from "./model_math.ts";
|
import { rotation_around } from "./model_math.ts";
|
||||||
import { part_point, PARTS, type PlayerPose, pose_at, pose_to_world, SLIM_PARTS } from "./player_model.ts";
|
import { part_point, PARTS, type PlayerPose, pose_at, pose_to_world, SLIM_PARTS } from "./player_model.ts";
|
||||||
@@ -70,7 +70,7 @@ export function gui_player_faces(skin: Texture, slim: boolean, dx: number, dy: n
|
|||||||
push_cube(skin, part, part.overlay, part.inflate, transform, undefined, emit_skin);
|
push_cube(skin, part, part.overlay, part.inflate, transform, undefined, emit_skin);
|
||||||
}
|
}
|
||||||
if (worn.length > 0) {
|
if (worn.length > 0) {
|
||||||
push_worn(worn, pose, undefined, collect(AssetManager.instance.get<Texture>("bworld:textures")));
|
push_worn(worn, pose, undefined, collect(AssetManager.instance.get<Texture>("cubi:textures")));
|
||||||
}
|
}
|
||||||
|
|
||||||
return faces
|
return faces
|
||||||
|
|||||||
@@ -5,9 +5,9 @@
|
|||||||
// ItemInHandRenderer. with empty hands it's their right arm, in their skin, like minecraft's
|
// ItemInHandRenderer. with empty hands it's their right arm, in their skin, like minecraft's
|
||||||
// FirstPersonHandsAndItemsRenderer.renderPlayerArm
|
// FirstPersonHandsAndItemsRenderer.renderPlayerArm
|
||||||
import { mat4, vec3 } from "gl-matrix";
|
import { mat4, vec3 } from "gl-matrix";
|
||||||
import type { ItemStack } from "$/common/inventory.ts";
|
import type { ItemStack } from "@/common/inventory.ts";
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import type { LocalPlayer } from "$/client/entity/local_player.ts";
|
import type { LocalPlayer } from "@/client/entity/local_player.ts";
|
||||||
import {
|
import {
|
||||||
begin_view_model,
|
begin_view_model,
|
||||||
end_mode_3d,
|
end_mode_3d,
|
||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
set_current_texture,
|
set_current_texture,
|
||||||
Texture,
|
Texture,
|
||||||
use_texture,
|
use_texture,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { display_transform, drawn_as_model, item_model_of, push_item } from "./item_renderer.ts";
|
import { display_transform, drawn_as_model, item_model_of, push_item } from "./item_renderer.ts";
|
||||||
import { push_cube, type Vec3 } from "./player_renderer.ts";
|
import { push_cube, type Vec3 } from "./player_renderer.ts";
|
||||||
import { right_arm } from "./player_model.ts";
|
import { right_arm } from "./player_model.ts";
|
||||||
@@ -64,7 +64,7 @@ export class HandRenderer {
|
|||||||
const tint = entity_tint(player, partial_tick);
|
const tint = entity_tint(player, partial_tick);
|
||||||
begin_view_model(FOV);
|
begin_view_model(FOV);
|
||||||
if (item) {
|
if (item) {
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
set_current_texture(atlas.tex);
|
set_current_texture(atlas.tex);
|
||||||
const display = item_model_of(item)?.display.firstperson_righthand;
|
const display = item_model_of(item)?.display.firstperson_righthand;
|
||||||
const transform = display
|
const transform = display
|
||||||
@@ -72,7 +72,7 @@ export class HandRenderer {
|
|||||||
: pose(item, (1 - equip) * 0.6, Math.sin(swing_progress * Math.PI));
|
: pose(item, (1 - equip) * 0.6, Math.sin(swing_progress * Math.PI));
|
||||||
push_item(atlas, item, transform, tint);
|
push_item(atlas, item, transform, tint);
|
||||||
} else {
|
} else {
|
||||||
const skin = player.skin ?? AssetManager.instance.get<Texture>("bworld:skin");
|
const skin = player.skin ?? AssetManager.instance.get<Texture>("cubi:skin");
|
||||||
const arm = right_arm(player.slim);
|
const arm = right_arm(player.slim);
|
||||||
const transform = arm_pose(arm.pivot, 1 - equip, swing_progress);
|
const transform = arm_pose(arm.pivot, 1 - equip, swing_progress);
|
||||||
set_current_texture(skin.tex);
|
set_current_texture(skin.tex);
|
||||||
@@ -80,7 +80,7 @@ export class HandRenderer {
|
|||||||
push_cube(skin, arm, arm.overlay, arm.inflate, transform, tint);
|
push_cube(skin, arm, arm.overlay, arm.inflate, transform, tint);
|
||||||
// what's worn on it goes over it, from the atlas
|
// what's worn on it goes over it, from the atlas
|
||||||
if (player.worn.length > 0) {
|
if (player.worn.length > 0) {
|
||||||
use_texture(AssetManager.instance.get<Texture>("bworld:textures").tex);
|
use_texture(AssetManager.instance.get<Texture>("cubi:textures").tex);
|
||||||
render_worn_arm(player, transform, tint);
|
render_worn_arm(player, transform, tint);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
|
|
||||||
// the 3d model of a flat item, like minecraft's item/generated: its sprite on the front and back, one pixel apart, with
|
// the 3d model of a flat item, like minecraft's item/generated: its sprite on the front and back, one pixel apart, with
|
||||||
// a side face along every edge between a pixel that can be seen and one that can't (or the sprite's border)
|
// a side face along every edge between a pixel that can be seen and one that can't (or the sprite's border)
|
||||||
import { TEXTURE_SIZE } from "$/common/constants.ts";
|
import { TEXTURE_SIZE } from "@/common/constants.ts";
|
||||||
import { opaque_pixels, type OpaqueMask } from "$/client/atlas.ts";
|
import { opaque_pixels, type OpaqueMask } from "@/client/atlas.ts";
|
||||||
|
|
||||||
export interface ItemQuad {
|
export interface ItemQuad {
|
||||||
// 4 corners counter clockwise seen from outside. x from -0.5 to 0.5 and y from 0 to 1 across the sprite, z its
|
// 4 corners counter clockwise seen from outside. x from -0.5 to 0.5 and y from 0 to 1 across the sprite, z its
|
||||||
|
|||||||
@@ -2,20 +2,21 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { mat4, vec3 } from "gl-matrix";
|
import { mat4, vec3 } from "gl-matrix";
|
||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
import { BlockRegistry, EverythingRegistry, type ItemLayer, ItemRegistry } from "$/common/everything_registry.ts";
|
import { BlockRegistry, EverythingRegistry, type ItemLayer, ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import type { ItemEntity } from "$/client/entity/item_entity.ts";
|
import type { ItemEntity } from "@/client/entity/item_entity.ts";
|
||||||
import { contained_fluid, type ItemData, ItemStack } from "$/common/inventory.ts";
|
import { contained_fluid, type ItemData, ItemStack } from "@/common/inventory.ts";
|
||||||
import type { FluidVariant } from "$/common/mod_api/shared.ts";
|
import type { FluidVariant } from "@/common/mod_api/shared.ts";
|
||||||
import type { FluidJson } from "$/common/mod_data.ts";
|
import type { EntityModelJson, FluidJson } from "@/common/mod_data.ts";
|
||||||
import { light_color, push_vertex, Texture } from "$/client/renderer/mod.ts";
|
import { light_color, push_vertex, Texture } from "@/client/renderer/mod.ts";
|
||||||
import {
|
import {
|
||||||
bake_model,
|
bake_model,
|
||||||
type BakedQuad,
|
type BakedQuad,
|
||||||
block_item_texture,
|
block_item_texture,
|
||||||
block_variant,
|
block_variant,
|
||||||
|
classify_quad,
|
||||||
cube_face_texture,
|
cube_face_texture,
|
||||||
cube_face_tint,
|
cube_face_tint,
|
||||||
type DisplayTransform,
|
type DisplayTransform,
|
||||||
@@ -24,15 +25,17 @@ import {
|
|||||||
item_tint,
|
item_tint,
|
||||||
type ModelDisplay,
|
type ModelDisplay,
|
||||||
type ModelJson,
|
type ModelJson,
|
||||||
} from "$/common/block_models.ts";
|
} from "@/common/block_models.ts";
|
||||||
import { item_model, type ItemQuad } from "./item_model.ts";
|
import { item_model, type ItemQuad } from "./item_model.ts";
|
||||||
import { get_state_value, item_texture } from "$/common/utils.ts";
|
import { get_state_value, item_texture } from "@/common/utils.ts";
|
||||||
import { ID_MASK, TEXTURE_SIZE } from "$/common/constants.ts";
|
import { ID_MASK, TEXTURE_SIZE } from "@/common/constants.ts";
|
||||||
import type { ClientLevel } from "$/client/level/client_level.ts";
|
import type { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
import { entity_tint } from "./entity_light.ts";
|
import { entity_tint } from "./entity_light.ts";
|
||||||
|
import { bone_matrices, IDENTITY } from "./model_math.ts";
|
||||||
|
import { push_model } from "./model_renderer.ts";
|
||||||
import type { Vec3 } from "./player_renderer.ts";
|
import type { Vec3 } from "./player_renderer.ts";
|
||||||
import { fluid_rules } from "$/client/fluid_rules.ts";
|
import { fluid_rules } from "@/client/fluid_rules.ts";
|
||||||
import { color_rgb, tint_without_biome, type TintColor } from "$/common/worldgen/biome_colors.ts";
|
import { color_rgb, tint_without_biome, type TintColor } from "@/common/worldgen/biome_colors.ts";
|
||||||
|
|
||||||
// how big items on the ground are drawn, minecraft's ground transform
|
// how big items on the ground are drawn, minecraft's ground transform
|
||||||
const BLOCK_SCALE = 0.25;
|
const BLOCK_SCALE = 0.25;
|
||||||
@@ -92,7 +95,7 @@ export function ground_transform(item: ItemStack): ItemTransform {
|
|||||||
|
|
||||||
// the atlas has to be the current texture
|
// the atlas has to be the current texture
|
||||||
export function render_item_entity(entity: ItemEntity, partial_tick: number) {
|
export function render_item_entity(entity: ItemEntity, partial_tick: number) {
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
|
|
||||||
// spinning and bobbing, like minecraft's ItemEntityRenderer
|
// spinning and bobbing, like minecraft's ItemEntityRenderer
|
||||||
const time = entity.age + partial_tick;
|
const time = entity.age + partial_tick;
|
||||||
@@ -124,13 +127,22 @@ export function render_item_entity(entity: ItemEntity, partial_tick: number) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// the stacks shown items are drawn as, by their "item" client data, which is replaced whenever it changes
|
// the stack an item synced to clients is drawn as, like a shown item's "item" client data or an object's. made once
|
||||||
const shown_stacks = new WeakMap<ItemData, ItemStack>();
|
// for each, since the data is replaced whenever it changes
|
||||||
|
export function synced_stack(data: ItemData): ItemStack {
|
||||||
|
let stack = synced_stacks.get(data);
|
||||||
|
if (!stack) {
|
||||||
|
stack = ItemStack.from_data(data);
|
||||||
|
synced_stacks.set(data, stack);
|
||||||
|
}
|
||||||
|
return stack;
|
||||||
|
}
|
||||||
|
const synced_stacks = new WeakMap<ItemData, ItemStack>();
|
||||||
|
|
||||||
// every item blocks with item_display show on top of them, their "item" client data, see BlockRegistry.item_display.
|
// every item blocks with item_display show on top of them, their "item" client data, see BlockRegistry.item_display.
|
||||||
// the atlas has to be the current texture
|
// the atlas has to be the current texture
|
||||||
export function render_block_items(level: ClientLevel) {
|
export function render_block_items(level: ClientLevel) {
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
|
||||||
for (const in_chunk of level.block_data.values()) {
|
for (const in_chunk of level.block_data.values()) {
|
||||||
for (const { x, y, z, data } of in_chunk.values()) {
|
for (const { x, y, z, data } of in_chunk.values()) {
|
||||||
@@ -140,11 +152,7 @@ export function render_block_items(level: ClientLevel) {
|
|||||||
const value = level.get_block_value(x, y, z);
|
const value = level.get_block_value(x, y, z);
|
||||||
const block = blocks[value & ID_MASK];
|
const block = blocks[value & ID_MASK];
|
||||||
if (!block?.item_display) continue;
|
if (!block?.item_display) continue;
|
||||||
let item = shown_stacks.get(shown);
|
const item = synced_stack(shown);
|
||||||
if (!item) {
|
|
||||||
item = ItemStack.from_data(shown);
|
|
||||||
shown_stacks.set(shown, item);
|
|
||||||
}
|
|
||||||
// the block's own light, or the one above for blocks light doesn't get into, since the items sit on top
|
// the block's own light, or the one above for blocks light doesn't get into, since the items sit on top
|
||||||
const here = level.get_light(x, y, z);
|
const here = level.get_light(x, y, z);
|
||||||
const above = level.get_light(x, y + 1, z);
|
const above = level.get_light(x, y + 1, z);
|
||||||
@@ -249,11 +257,15 @@ export interface ItemModel {
|
|||||||
block?: BlockRegistry;
|
block?: BlockRegistry;
|
||||||
}
|
}
|
||||||
|
|
||||||
// an item's own model, or its block's item_model with the block's textures, baked the first time it's drawn. undefined
|
// an item's own model, or its block's item_model with the block's textures, baked the first time it's drawn. an item's
|
||||||
// for items drawn as a cube or as their sprite
|
// own can be an entity model, drawn in the item's texture. undefined for items drawn as a cube or as their sprite
|
||||||
export function item_model_of(item: ItemStack): ItemModel | undefined {
|
export function item_model_of(item: ItemStack): ItemModel | undefined {
|
||||||
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||||
if (info?.model !== undefined) return baked_item_model(info, info.model);
|
if (info?.model !== undefined) {
|
||||||
|
const entity_model = EverythingRegistry.get<EntityModelJson>("entity_models", info.model);
|
||||||
|
if (entity_model) return baked_entity_item_model(entity_model, item_texture(item, info));
|
||||||
|
return baked_item_model(info, info.model);
|
||||||
|
}
|
||||||
const block = placed_block(item);
|
const block = placed_block(item);
|
||||||
if (block?.item_model !== undefined) return baked_item_model(block, block.item_model, block);
|
if (block?.item_model !== undefined) return baked_item_model(block, block.item_model, block);
|
||||||
return undefined;
|
return undefined;
|
||||||
@@ -270,6 +282,54 @@ function baked_item_model(key: ItemRegistry | BlockRegistry, id: string, block?:
|
|||||||
}
|
}
|
||||||
const baked_items = new WeakMap<ItemRegistry | BlockRegistry, ItemModel>();
|
const baked_items = new WeakMap<ItemRegistry | BlockRegistry, ItemModel>();
|
||||||
|
|
||||||
|
// by texture, since an item's texture can change with its data
|
||||||
|
function baked_entity_item_model(model: EntityModelJson, texture: string): ItemModel {
|
||||||
|
let by_texture = baked_entity_items.get(model);
|
||||||
|
if (!by_texture) {
|
||||||
|
by_texture = new Map();
|
||||||
|
baked_entity_items.set(model, by_texture);
|
||||||
|
}
|
||||||
|
let baked = by_texture.get(texture);
|
||||||
|
if (!baked) {
|
||||||
|
baked = { quads: entity_model_quads(model, texture), display: model.display ?? {} };
|
||||||
|
by_texture.set(texture, baked);
|
||||||
|
}
|
||||||
|
return baked;
|
||||||
|
}
|
||||||
|
const baked_entity_items = new WeakMap<EntityModelJson, Map<string, ItemModel>>();
|
||||||
|
|
||||||
|
// an entity model as a block model's quads, standing on the block's bottom in its middle like it stands on the ground,
|
||||||
|
// 16 of its pixels across the block. its uvs are pixels of the texture, 0 to 16 like a block model's
|
||||||
|
export function entity_model_quads(model: EntityModelJson, texture: string): BakedQuad[] {
|
||||||
|
const vertices: number[][] = [];
|
||||||
|
const pixels = { width: 1, height: 1 } as Texture;
|
||||||
|
const whole_texture = { x: 0, y: 0, width: TEXTURE_SIZE, height: TEXTURE_SIZE };
|
||||||
|
const to_block = (x: number, y: number, z: number): Vec3 => [x / 16 + 0.5, y / 16, z / 16 + 0.5];
|
||||||
|
push_model(model, bone_matrices(model, () => IDENTITY), pixels, whole_texture, to_block, undefined, undefined, (
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
z,
|
||||||
|
u,
|
||||||
|
v,
|
||||||
|
) => vertices.push([x, y, z, u, v]));
|
||||||
|
const quads: BakedQuad[] = [];
|
||||||
|
// two triangles a box face, its corners 0 1 2 and 0 2 3
|
||||||
|
for (let i = 0; i < vertices.length; i += 6) {
|
||||||
|
const corners = [vertices[i], vertices[i + 1], vertices[i + 2], vertices[i + 5]];
|
||||||
|
const positions = corners.flatMap(([x, y, z]) => [x, y, z]);
|
||||||
|
quads.push({
|
||||||
|
positions,
|
||||||
|
uvs: corners.flatMap(([, , , u, v]) => [u, v]),
|
||||||
|
texture,
|
||||||
|
variables: [],
|
||||||
|
...classify_quad(positions),
|
||||||
|
cull: -1,
|
||||||
|
shade: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return quads;
|
||||||
|
}
|
||||||
|
|
||||||
// whether an item is drawn as a block or a model rather than its sprite, which decides how big it's drawn and how it's
|
// whether an item is drawn as a block or a model rather than its sprite, which decides how big it's drawn and how it's
|
||||||
// held when its model has no display transform for that
|
// held when its model has no display transform for that
|
||||||
export function drawn_as_model(item: ItemStack) {
|
export function drawn_as_model(item: ItemStack) {
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "$/client/level/client_level.ts";
|
import {
|
||||||
import { profiler } from "$/client/profiler.ts";
|
type Chunk,
|
||||||
import { Camera } from "$/client/camera.ts";
|
CHUNK_SIZE,
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
type ChunkMesh,
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
ClientLevel,
|
||||||
import type { MultiPlayerGameMode } from "$/client/game_mode.ts";
|
type RenderSection,
|
||||||
import type { Entity } from "$/client/entity/entity.ts";
|
} from "@/client/level/client_level.ts";
|
||||||
import { RemotePlayer } from "$/client/entity/remote_player.ts";
|
import { profiler } from "@/client/profiler.ts";
|
||||||
import { ItemEntity } from "$/client/entity/item_entity.ts";
|
import { Camera } from "@/client/camera.ts";
|
||||||
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
|
import type { MultiPlayerGameMode } from "@/client/game_mode.ts";
|
||||||
|
import type { Entity } from "@/client/entity/entity.ts";
|
||||||
|
import { RemotePlayer } from "@/client/entity/remote_player.ts";
|
||||||
|
import { ItemEntity } from "@/client/entity/item_entity.ts";
|
||||||
import { render_block_items, render_item_entity } from "./item_renderer.ts";
|
import { render_block_items, render_item_entity } from "./item_renderer.ts";
|
||||||
import { HURT_TINT, player_pose, render_player } from "./player_renderer.ts";
|
import { HURT_TINT, player_pose, render_player } from "./player_renderer.ts";
|
||||||
import { render_worn } from "./worn_renderer.ts";
|
import { render_worn } from "./worn_renderer.ts";
|
||||||
@@ -17,40 +23,51 @@ import type { PlayerPose } from "./player_model.ts";
|
|||||||
import type { Vec3 } from "./model_math.ts";
|
import type { Vec3 } from "./model_math.ts";
|
||||||
import { render_mod_entity } from "./entity_renderer.ts";
|
import { render_mod_entity } from "./entity_renderer.ts";
|
||||||
import { entity_tint } from "./entity_light.ts";
|
import { entity_tint } from "./entity_light.ts";
|
||||||
import { RemoteEntity } from "$/client/entity/remote_entity.ts";
|
import { RemoteEntity } from "@/client/entity/remote_entity.ts";
|
||||||
import {
|
import {
|
||||||
draw_terrain,
|
draw_terrain,
|
||||||
flush_batch,
|
flush_batch,
|
||||||
get_current_texture,
|
get_current_texture,
|
||||||
push_vertex,
|
push_vertex,
|
||||||
|
render_debug,
|
||||||
set_current_texture,
|
set_current_texture,
|
||||||
|
set_face_culling,
|
||||||
Texture,
|
Texture,
|
||||||
use_texture,
|
use_texture,
|
||||||
view_projection,
|
view_projection,
|
||||||
white_tex,
|
white_tex,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { type BlockRegistry, EverythingRegistry, type RenderLayer } from "$/common/everything_registry.ts";
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, type ModelJson } from "$/common/block_models.ts";
|
import { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, type ModelJson } from "@/common/block_models.ts";
|
||||||
import { BREAK_STAGES, ID_MASK } from "$/common/constants.ts";
|
import { BREAK_STAGES, ID_MASK } from "@/common/constants.ts";
|
||||||
import { type Shape, shape_at } from "$/common/block_shapes.ts";
|
import { type Shape, shape_at } from "@/common/block_shapes.ts";
|
||||||
import type { BlockHitResult } from "$/client/level/client_level.ts";
|
import type { BlockHitResult } from "@/client/level/client_level.ts";
|
||||||
import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts";
|
import { FACE_GROUPS, UNALIGNED_GROUP } from "@/client/workers/chunk_messages.ts";
|
||||||
import { FACE_AXIS, FACE_NORMALS } from "$/client/workers/translucent_sort.ts";
|
import { FACE_AXIS, FACE_NORMALS } from "@/client/workers/translucent_sort.ts";
|
||||||
import { Frustum } from "./frustum.ts";
|
import { Frustum } from "./frustum.ts";
|
||||||
import { draw_visuals } from "./visuals.ts";
|
import { draw_visuals } from "./visuals.ts";
|
||||||
|
import { reachable_sections } from "./occlusion.ts";
|
||||||
|
import { REGION_LAYERS, type RegionLayer, type RenderRegion } from "@/client/level/render_region.ts";
|
||||||
|
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||||
|
|
||||||
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
|
// draws the level, like minecraft's LevelRenderer: terrain in layers, block breaking and entities
|
||||||
export class LevelRenderer {
|
export class LevelRenderer {
|
||||||
frustum = new Frustum();
|
frustum = new Frustum();
|
||||||
// chunks in view this frame, worked out once for all the layers
|
// sections in view this frame, near to far, worked out once for all the layers
|
||||||
#visible: Chunk[] = [];
|
#visible: RenderSection[] = [];
|
||||||
|
// the chunks they're in, and the regions with the ones in each, the regions near to far too
|
||||||
|
#visible_chunks = new Set<Chunk>();
|
||||||
|
#visible_regions = new Map<RenderRegion, RenderSection[]>();
|
||||||
|
// what the camera could see the last time it was searched for, which only changes when it moves to another section
|
||||||
|
// or the sections change, see occlusion.ts
|
||||||
|
#reachable: { sections: RenderSection[] | undefined; level: ClientLevel; version: number; key: string } | undefined;
|
||||||
// what to draw, switched off in the f3 performance window to see what each costs
|
// what to draw, switched off in the f3 performance window to see what each costs
|
||||||
draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
|
draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
|
||||||
|
|
||||||
// entities drawn this frame, for the f3 performance window
|
// entities drawn this frame, for the f3 performance window
|
||||||
#drawn_entities = 0;
|
#drawn_entities = 0;
|
||||||
|
|
||||||
get visible_chunks() {
|
get visible_sections() {
|
||||||
return this.#visible.length;
|
return this.#visible.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,65 +79,79 @@ export class LevelRenderer {
|
|||||||
render_opaque(level: ClientLevel, camera: Camera) {
|
render_opaque(level: ClientLevel, camera: Camera) {
|
||||||
profiler.section("chunk upkeep", () => this.#find_visible(level, camera));
|
profiler.section("chunk upkeep", () => this.#find_visible(level, camera));
|
||||||
set_current_texture(level.image.tex);
|
set_current_texture(level.image.tex);
|
||||||
for (const layer of ["solid", "cutout"] as const) {
|
for (const layer of REGION_LAYERS) {
|
||||||
if (!this.draw[layer]) continue;
|
if (!this.draw[layer]) continue;
|
||||||
profiler.section(layer, () => {
|
profiler.section(layer, () => {
|
||||||
for (const chunk of this.#visible) {
|
for (const section of this.#visible) {
|
||||||
const mesh = chunk.meshes[layer];
|
const mesh = section.meshes[layer];
|
||||||
if (mesh) {
|
if (mesh?.vertex_buffer) draw_facing_camera(layer, mesh.vertex_buffer, mesh, camera);
|
||||||
draw_facing_camera(layer, mesh, camera);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
for (const [region, sections] of this.#visible_regions) draw_region(layer, region, sections, camera);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// asks for meshes and sorting, then works out which chunks are in view, near to far
|
// asks for meshes and sorting, then works out which sections are in view, near to far like sodium, so what's in
|
||||||
|
// front fills the depth buffer first and the gpu can skip shading what's behind it
|
||||||
#find_visible(level: ClientLevel, camera: Camera) {
|
#find_visible(level: ClientLevel, camera: Camera) {
|
||||||
level.request_meshes(camera);
|
level.request_meshes(camera);
|
||||||
level.update_translucent_sorting(camera);
|
level.update_translucent_sorting(camera);
|
||||||
|
|
||||||
|
level.use_render_regions(render_debug.render_regions);
|
||||||
|
level.update_regions();
|
||||||
this.frustum.update(view_projection());
|
this.frustum.update(view_projection());
|
||||||
this.#visible.length = 0;
|
this.#visible_chunks.clear();
|
||||||
for (const chunk of level.chunks.values()) {
|
this.#visible_regions.clear();
|
||||||
const drawn = Object.keys(chunk.meshes).length > 0 || level.visuals.has(chunk.x, chunk.z);
|
const reachable = this.#reachable_sections(level, camera);
|
||||||
if (drawn && this.#in_view(chunk)) {
|
if (reachable) {
|
||||||
this.#visible.push(chunk);
|
this.#visible = reachable.filter((section) => this.#in_view(section));
|
||||||
|
} else {
|
||||||
|
// the camera's chunk isn't loaded, so there's nothing to search from
|
||||||
|
this.#visible = [...level.drawn].filter((section) => this.#in_view(section))
|
||||||
|
.map((section) => ({ section, distance: distance_sq(section, camera) }))
|
||||||
|
.sort((a, b) => a.distance - b.distance)
|
||||||
|
.map(({ section }) => section);
|
||||||
}
|
}
|
||||||
|
for (const section of this.#visible) {
|
||||||
|
this.#visible_chunks.add(section.chunk);
|
||||||
|
const in_region = this.#visible_regions.get(section.region);
|
||||||
|
if (in_region) in_region.push(section);
|
||||||
|
else this.#visible_regions.set(section.region, [section]);
|
||||||
}
|
}
|
||||||
// near to far, like sodium, so what's in front fills the depth buffer first and the gpu can skip shading what's
|
|
||||||
// behind it
|
|
||||||
const distance_sq = (chunk: Chunk) => {
|
|
||||||
const dx = (chunk.x + 0.5) * CHUNK_SIZE - camera.x;
|
|
||||||
const dz = (chunk.z + 0.5) * CHUNK_SIZE - camera.z;
|
|
||||||
return dx * dx + dz * dz;
|
|
||||||
};
|
|
||||||
this.#visible.sort((a, b) => distance_sq(a) - distance_sq(b));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// translucent terrain, drawn after entities so they show through water and glass.
|
#reachable_sections(level: ClientLevel, camera: Camera) {
|
||||||
// chunks go back to front, and each chunk's quads are already sorted back to front
|
const key = `${Math.floor(camera.x / CHUNK_SIZE)},${Math.floor(camera.y / SECTION_HEIGHT)},${
|
||||||
|
Math.floor(camera.z / CHUNK_SIZE)
|
||||||
|
}`;
|
||||||
|
const last = this.#reachable;
|
||||||
|
if (last?.level === level && last.version === level.sections_version && last.key === key) return last.sections;
|
||||||
|
const sections = profiler.section(
|
||||||
|
"occlusion",
|
||||||
|
() => reachable_sections(level, camera.x, camera.y, camera.z),
|
||||||
|
);
|
||||||
|
this.#reachable = { sections, level, version: level.sections_version, key };
|
||||||
|
return sections;
|
||||||
|
}
|
||||||
|
|
||||||
|
// translucent terrain, drawn after entities so they show through water and glass. sections go back to front, and
|
||||||
|
// each section's quads are already sorted back to front
|
||||||
render_translucent(_level: ClientLevel, camera: Camera) {
|
render_translucent(_level: ClientLevel, camera: Camera) {
|
||||||
if (!this.draw.translucent) return;
|
if (!this.draw.translucent) return;
|
||||||
const distance_sq = (x: number, z: number) => {
|
const sections = this.#visible
|
||||||
const dx = (x + 0.5) * CHUNK_SIZE - camera.x;
|
.filter((section) => section.meshes.translucent)
|
||||||
const dz = (z + 0.5) * CHUNK_SIZE - camera.z;
|
.map((section) => ({ mesh: section.meshes.translucent!, distance: distance_sq(section, camera) }))
|
||||||
return dx * dx + dz * dz;
|
|
||||||
};
|
|
||||||
const chunks = this.#visible
|
|
||||||
.filter((chunk) => chunk.meshes.translucent)
|
|
||||||
.map((chunk) => ({ mesh: chunk.meshes.translucent!, distance: distance_sq(chunk.x, chunk.z) }))
|
|
||||||
.sort((a, b) => b.distance - a.distance);
|
.sort((a, b) => b.distance - a.distance);
|
||||||
|
|
||||||
for (const { mesh } of chunks) {
|
for (const { mesh } of sections) {
|
||||||
draw_terrain("translucent", mesh.vertex_buffer, 0, mesh.quad_count, mesh.index_buffer);
|
draw_terrain("translucent", mesh.vertex_buffer!, 0, mesh.quad_count, mesh.index_buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#in_view(chunk: Chunk) {
|
#in_view(section: RenderSection) {
|
||||||
const x = chunk.x * CHUNK_SIZE;
|
const x = section.chunk.x * CHUNK_SIZE;
|
||||||
const z = chunk.z * CHUNK_SIZE;
|
const z = section.chunk.z * CHUNK_SIZE;
|
||||||
return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, z + CHUNK_SIZE);
|
return this.frustum.intersects_box(x, section.min_y, z, x + CHUNK_SIZE, section.max_y, z + CHUNK_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
// every entity in view but the one the camera is in
|
// every entity in view but the one the camera is in
|
||||||
@@ -128,7 +159,7 @@ export class LevelRenderer {
|
|||||||
this.#drawn_entities = 0;
|
this.#drawn_entities = 0;
|
||||||
if (!this.draw.entities) return;
|
if (!this.draw.entities) return;
|
||||||
flush_batch();
|
flush_batch();
|
||||||
const default_skin = AssetManager.instance.get<Texture>("bworld:skin");
|
const default_skin = AssetManager.instance.get<Texture>("cubi:skin");
|
||||||
// what they wear is drawn with the atlas, after every skin
|
// what they wear is drawn with the atlas, after every skin
|
||||||
const posed: { player: RemotePlayer; pose: PlayerPose; tint: Vec3 }[] = [];
|
const posed: { player: RemotePlayer; pose: PlayerPose; tint: Vec3 }[] = [];
|
||||||
for (const entity of level.entities.values()) {
|
for (const entity of level.entities.values()) {
|
||||||
@@ -150,10 +181,15 @@ export class LevelRenderer {
|
|||||||
for (const entity of level.entities.values()) {
|
for (const entity of level.entities.values()) {
|
||||||
if (entity instanceof ItemEntity && this.#entity_in_view(entity, partial_tick)) {
|
if (entity instanceof ItemEntity && this.#entity_in_view(entity, partial_tick)) {
|
||||||
render_item_entity(entity, partial_tick);
|
render_item_entity(entity, partial_tick);
|
||||||
} else if (entity instanceof RemoteEntity && this.#entity_in_view(entity, partial_tick)) {
|
}
|
||||||
|
}
|
||||||
|
set_face_culling(false);
|
||||||
|
for (const entity of level.entities.values()) {
|
||||||
|
if (entity instanceof RemoteEntity && this.#entity_in_view(entity, partial_tick)) {
|
||||||
render_mod_entity(entity, camera, partial_tick);
|
render_mod_entity(entity, camera, partial_tick);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
set_face_culling(true);
|
||||||
render_block_items(level);
|
render_block_items(level);
|
||||||
flush_batch();
|
flush_batch();
|
||||||
}
|
}
|
||||||
@@ -178,7 +214,7 @@ export class LevelRenderer {
|
|||||||
// blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first
|
// blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first
|
||||||
render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) {
|
render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) {
|
||||||
if (!this.draw.visuals) return;
|
if (!this.draw.visuals) return;
|
||||||
level.visuals.frame(this.#visible, level.ticks + partial_tick);
|
level.visuals.frame(this.#visible_chunks, level.ticks + partial_tick);
|
||||||
flush_batch();
|
flush_batch();
|
||||||
set_current_texture(level.image.tex);
|
set_current_texture(level.image.tex);
|
||||||
draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]);
|
draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]);
|
||||||
@@ -203,7 +239,7 @@ export class LevelRenderer {
|
|||||||
if (!info) {
|
if (!info) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const tex = AssetManager.instance.get<Texture>("bworld:textures");
|
const tex = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
const region = get_sprite_region(`cubi:break_${stage}`);
|
const region = get_sprite_region(`cubi:break_${stage}`);
|
||||||
for (const quad of this.#destroy_quads(info, value)) {
|
for (const quad of this.#destroy_quads(info, value)) {
|
||||||
push_decal_quad(tex, quad, x, y, z, region);
|
push_decal_quad(tex, quad, x, y, z, region);
|
||||||
@@ -251,6 +287,14 @@ export class LevelRenderer {
|
|||||||
#baked = new Map<number, BakedQuad[]>();
|
#baked = new Map<number, BakedQuad[]>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// from the camera to the middle of the section's bounds, squared
|
||||||
|
function distance_sq(section: RenderSection, camera: Camera) {
|
||||||
|
const dx = (section.chunk.x + 0.5) * CHUNK_SIZE - camera.x;
|
||||||
|
const dy = (section.min_y + section.max_y) / 2 - camera.y;
|
||||||
|
const dz = (section.chunk.z + 0.5) * CHUNK_SIZE - camera.z;
|
||||||
|
return dx * dx + dy * dy + dz * dz;
|
||||||
|
}
|
||||||
|
|
||||||
// how far models can stick out of their entity's box, like a swinging arm or a dropped item bobbing
|
// how far models can stick out of their entity's box, like a swinging arm or a dropped item bobbing
|
||||||
const ENTITY_CULL_MARGIN = 0.5;
|
const ENTITY_CULL_MARGIN = 0.5;
|
||||||
|
|
||||||
@@ -384,12 +428,8 @@ function decal_uv(face: number, x: number, y: number, z: number): [number, numbe
|
|||||||
|
|
||||||
// only the face groups that can face the camera: quads facing +x can only be seen from beyond the lowest x plane any
|
// only the face groups that can face the camera: quads facing +x can only be seen from beyond the lowest x plane any
|
||||||
// of them lie on. neighboring groups that are both drawn go in one draw call
|
// of them lie on. neighboring groups that are both drawn go in one draw call
|
||||||
function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera) {
|
function draw_facing_camera(layer: RegionLayer, buffer: GPUBuffer, mesh: ChunkMesh, camera: Camera) {
|
||||||
const groups = mesh.groups;
|
const groups = mesh.groups!;
|
||||||
if (!groups) {
|
|
||||||
draw_terrain(layer, mesh.vertex_buffer, 0, mesh.quad_count);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let start = 0;
|
let start = 0;
|
||||||
let end = 0;
|
let end = 0;
|
||||||
for (let g = 0; g < FACE_GROUPS; g++) {
|
for (let g = 0; g < FACE_GROUPS; g++) {
|
||||||
@@ -398,12 +438,37 @@ function draw_facing_camera(layer: RenderLayer, mesh: ChunkMesh, camera: Camera)
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (group.first !== end) {
|
if (group.first !== end) {
|
||||||
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
|
draw_terrain(layer, buffer, start, end - start);
|
||||||
start = group.first;
|
start = group.first;
|
||||||
}
|
}
|
||||||
end = group.first + group.count;
|
end = group.first + group.count;
|
||||||
}
|
}
|
||||||
draw_terrain(layer, mesh.vertex_buffer, start, end - start);
|
draw_terrain(layer, buffer, start, end - start);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a region's sections in view, a face group at a time (see render_region.ts), only where the group can face the camera:
|
||||||
|
// quads facing +x can only be seen from beyond the lowest x plane any of them lie on. sections next to each other in the
|
||||||
|
// buffer that are both drawn go in one draw call
|
||||||
|
function draw_region(layer: RegionLayer, region: RenderRegion, in_view: RenderSection[], camera: Camera) {
|
||||||
|
const buffer = region.layers[layer].buffer;
|
||||||
|
if (!buffer) return;
|
||||||
|
// in the order they're in the buffer
|
||||||
|
const sections = in_view.filter((section) => section.meshes[layer]?.slot !== undefined)
|
||||||
|
.sort((a, b) => a.meshes[layer]!.slot! - b.meshes[layer]!.slot!);
|
||||||
|
for (let g = 0; g < FACE_GROUPS; g++) {
|
||||||
|
let start = 0;
|
||||||
|
let end = 0;
|
||||||
|
for (const section of sections) {
|
||||||
|
const group = section.meshes[layer]!.groups![g];
|
||||||
|
if (group.count === 0 || !group_faces_camera(g, group.min, group.max, camera)) continue;
|
||||||
|
if (group.first !== end) {
|
||||||
|
draw_terrain(layer, buffer, start, end - start);
|
||||||
|
start = group.first;
|
||||||
|
}
|
||||||
|
end = group.first + group.count;
|
||||||
|
}
|
||||||
|
draw_terrain(layer, buffer, start, end - start);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function group_faces_camera(
|
export function group_faces_camera(
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
// turning and moving the parts of models: entity models' bones, the player's parts and what's worn on them. no
|
// turning and moving the parts of models: entity models' bones, the player's parts and what's worn on them. no
|
||||||
// drawing here, so tests can use it
|
// drawing here, so tests can use it
|
||||||
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
|
import type { EntityBoneJson, EntityCubeJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
|
|
||||||
export type Vec3 = [number, number, number];
|
export type Vec3 = [number, number, number];
|
||||||
|
|
||||||
@@ -17,19 +17,43 @@ export function model_pivot(bone: EntityBoneJson): Vec3 {
|
|||||||
return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]];
|
return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]];
|
||||||
}
|
}
|
||||||
|
|
||||||
// its own rotation around its pivot. mirroring x turns x and y rotations the other way
|
// what animation does to a bone, in the model's bedrock space like its own pivot and rotation: degrees added to its
|
||||||
export function bone_matrix(bone: EntityBoneJson): Matrix {
|
// rotation, pixels it moves and how much it's scaled, around its pivot
|
||||||
if (!bone.rotation) return IDENTITY;
|
export type BoneOffsets = { rotation: Vec3; position: Vec3; scale: Vec3 };
|
||||||
const [rx, ry, rz] = bone.rotation.map((degrees) => degrees * Math.PI / 180);
|
|
||||||
return rotation_around(model_pivot(bone), -rx, -ry, rz);
|
// a bone's or a cube's own rotation around its pivot. mirroring x turns x and y rotations the other way
|
||||||
|
export function own_matrix(part: EntityBoneJson | EntityCubeJson): Matrix {
|
||||||
|
if (!part.rotation) return IDENTITY;
|
||||||
|
return turn_around(part.pivot ?? [0, 0, 0], part.rotation);
|
||||||
}
|
}
|
||||||
|
|
||||||
// every bone's matrix: its own rotation, then pose's for it (like a head looking or a limb swinging), then its
|
function turn_around([px, py, pz]: Vec3, degrees: Vec3): Matrix {
|
||||||
// parent's. parents come before their children in the model
|
const [rx, ry, rz] = degrees.map((n) => n * Math.PI / 180);
|
||||||
export function bone_matrices(model: EntityModelJson, pose: (bone: EntityBoneJson) => Matrix): Map<string, Matrix> {
|
return rotation_around([-px, py, pz], -rx, -ry, rz);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a bone's own rotation with what animation does to it: moved, then turned and scaled around its pivot
|
||||||
|
function animated_matrix(bone: EntityBoneJson, { rotation, position, scale }: BoneOffsets): Matrix {
|
||||||
|
const [rx, ry, rz] = bone.rotation ?? [0, 0, 0];
|
||||||
|
const turned = turn_around(bone.pivot, [rx + rotation[0], ry + rotation[1], rz + rotation[2]]);
|
||||||
|
const [px, py, pz] = model_pivot(bone);
|
||||||
|
const [sx, sy, sz] = scale;
|
||||||
|
const scaled = [sx, 0, 0, px - px * sx, 0, sy, 0, py - py * sy, 0, 0, sz, pz - pz * sz];
|
||||||
|
const moved = [1, 0, 0, -position[0], 0, 1, 0, position[1], 0, 0, 1, position[2]];
|
||||||
|
return multiply(moved, multiply(turned, scaled));
|
||||||
|
}
|
||||||
|
|
||||||
|
// every bone's matrix: its own rotation (with offsets' for it, from animation), then pose's for it (like a head
|
||||||
|
// looking or a limb swinging), then its parent's. parents come before their children in the model
|
||||||
|
export function bone_matrices(
|
||||||
|
model: EntityModelJson,
|
||||||
|
pose: (bone: EntityBoneJson) => Matrix,
|
||||||
|
offsets?: Map<string, BoneOffsets>,
|
||||||
|
): Map<string, Matrix> {
|
||||||
const bones = new Map<string, Matrix>();
|
const bones = new Map<string, Matrix>();
|
||||||
for (const bone of model.bones) {
|
for (const bone of model.bones) {
|
||||||
let matrix = multiply(pose(bone), bone_matrix(bone));
|
const offset = offsets?.get(bone.name);
|
||||||
|
let matrix = multiply(pose(bone), offset ? animated_matrix(bone, offset) : own_matrix(bone));
|
||||||
if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix);
|
if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix);
|
||||||
bones.set(bone.name, matrix);
|
bones.set(bone.name, matrix);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,18 +2,18 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// entity models' boxes, for mod entities and for what players wear. the atlas has to be the current texture
|
// entity models' boxes, for mod entities and for what players wear. the atlas has to be the current texture
|
||||||
import type { Texture } from "$/client/renderer/mod.ts";
|
import type { Texture } from "@/client/renderer/mod.ts";
|
||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
|
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
import { apply, bone_matrices, type Matrix, type Vec3 } from "./model_math.ts";
|
import { apply, type Matrix, multiply, own_matrix, type Vec3 } from "./model_math.ts";
|
||||||
import { push_box, type VertexSink } from "./player_renderer.ts";
|
import { push_box, type VertexSink } from "./player_renderer.ts";
|
||||||
|
|
||||||
// pose is each bone's turn before its parent's, like a head looking or a limb swinging. to_world takes the model's
|
// bones is each bone's matrix, see bone_matrices. to_world takes the model's pixels, after the bones are turned, to the
|
||||||
// pixels, after the bones are turned, to the world. the texture is region of the atlas, stretched to the model's
|
// world. the texture is region of the atlas, stretched to the model's texture size. only picks the bones drawn, all of
|
||||||
// texture size. only picks the bones drawn, all of them when not given. emit gets the vertices, the batch by default
|
// them when not given. emit gets the vertices, the batch by default
|
||||||
export function push_model(
|
export function push_model(
|
||||||
model: EntityModelJson,
|
model: EntityModelJson,
|
||||||
pose: (bone: EntityBoneJson) => Matrix,
|
bones: Map<string, Matrix>,
|
||||||
atlas: Texture,
|
atlas: Texture,
|
||||||
region: SpriteRegion,
|
region: SpriteRegion,
|
||||||
to_world: (x: number, y: number, z: number) => Vec3,
|
to_world: (x: number, y: number, z: number) => Vec3,
|
||||||
@@ -25,12 +25,11 @@ export function push_model(
|
|||||||
(region.x + u * region.width / model.texture_width) / atlas.width,
|
(region.x + u * region.width / model.texture_width) / atlas.width,
|
||||||
(region.y + v * region.height / model.texture_height) / atlas.height,
|
(region.y + v * region.height / model.texture_height) / atlas.height,
|
||||||
];
|
];
|
||||||
const matrices = bone_matrices(model, pose);
|
|
||||||
for (const bone of model.bones) {
|
for (const bone of model.bones) {
|
||||||
if (only && !only(bone)) continue;
|
if (only && !only(bone)) continue;
|
||||||
const matrix = matrices.get(bone.name)!;
|
|
||||||
const transform = (px: number, py: number, pz: number) => to_world(...apply(matrix, px, py, pz));
|
|
||||||
for (const cube of bone.cubes) {
|
for (const cube of bone.cubes) {
|
||||||
|
const matrix = multiply(bones.get(bone.name)!, own_matrix(cube));
|
||||||
|
const transform = (px: number, py: number, pz: number) => to_world(...apply(matrix, px, py, pz));
|
||||||
const inflate = cube.inflate ?? 0;
|
const inflate = cube.inflate ?? 0;
|
||||||
const [ox, oy, oz] = cube.origin;
|
const [ox, oy, oz] = cube.origin;
|
||||||
const [w, h, d] = cube.size;
|
const [w, h, d] = cube.size;
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { Camera } from "$/client/camera.ts";
|
import type { Camera } from "@/client/camera.ts";
|
||||||
import type { Entity } from "$/client/entity/entity.ts";
|
import type { Entity } from "@/client/entity/entity.ts";
|
||||||
import type { ClientLevel } from "$/client/level/client_level.ts";
|
import type { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
import { RemotePlayer } from "$/client/entity/remote_player.ts";
|
import { RemotePlayer } from "@/client/entity/remote_player.ts";
|
||||||
import { draw_rect_3d, draw_text_3d, flush_batch, measure_text, type Plane3d } from "$/client/renderer/mod.ts";
|
import { draw_rect_3d, draw_text_3d, flush_batch, measure_text, type Plane3d } from "@/client/renderer/mod.ts";
|
||||||
|
|
||||||
// how big a font pixel is, in blocks. m6x11's letters are 11 pixels tall, so about a quarter of a block
|
// how big a font pixel is, in blocks. m6x11's letters are 11 pixels tall, so about a quarter of a block
|
||||||
const SCALE = 0.022;
|
const SCALE = 0.022;
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// occlusion culling, like sodium's OcclusionCuller but simpler: which sections the camera can see into, going out
|
||||||
|
// from its own section a face at a time. a section is only left through faces that see the ones it was entered
|
||||||
|
// through (see client/workers/visibility.ts), and never back towards the camera, so caves under the ground and the
|
||||||
|
// inside of hills aren't drawn
|
||||||
|
import { type Chunk, CHUNK_SIZE, type ClientLevel, type RenderSection } from "@/client/level/client_level.ts";
|
||||||
|
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||||
|
import { ALL_DIRECTIONS, exits } from "@/client/workers/visibility.ts";
|
||||||
|
|
||||||
|
// tells searches apart, so sections don't need clearing between them
|
||||||
|
let searches = 0;
|
||||||
|
|
||||||
|
// the sections with something to draw the camera at x y z can see, near to far: in the order the search reaches them,
|
||||||
|
// a step at a time. undefined when the camera's chunk isn't loaded
|
||||||
|
export function reachable_sections(level: ClientLevel, x: number, y: number, z: number) {
|
||||||
|
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||||
|
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||||
|
const chunk = level.get_chunk(chunk_x, chunk_z);
|
||||||
|
if (!chunk) return undefined;
|
||||||
|
// above or below the world, from the section nearest to the camera
|
||||||
|
const count = chunk.sections.length;
|
||||||
|
const index = Math.min(count - 1, Math.max(0, Math.floor((y - level.shape.min_y) / SECTION_HEIGHT)));
|
||||||
|
|
||||||
|
// the loaded chunks in a grid, since looking each step's up in the level's map is most of what a search costs
|
||||||
|
let min_x = chunk_x, max_x = chunk_x, min_z = chunk_z, max_z = chunk_z;
|
||||||
|
for (const { x, z } of level.chunks.values()) {
|
||||||
|
min_x = Math.min(min_x, x);
|
||||||
|
max_x = Math.max(max_x, x);
|
||||||
|
min_z = Math.min(min_z, z);
|
||||||
|
max_z = Math.max(max_z, z);
|
||||||
|
}
|
||||||
|
const width = max_x - min_x + 1;
|
||||||
|
const depth = max_z - min_z + 1;
|
||||||
|
const grid: (Chunk | undefined)[] = new Array(width * depth);
|
||||||
|
for (const chunk of level.chunks.values()) grid[(chunk.x - min_x) * depth + chunk.z - min_z] = chunk;
|
||||||
|
const chunk_at = (x: number, z: number) =>
|
||||||
|
x < min_x || x > max_x || z < min_z || z > max_z ? undefined : grid[(x - min_x) * depth + z - min_z];
|
||||||
|
|
||||||
|
const search = ++searches;
|
||||||
|
const start = chunk.sections[index];
|
||||||
|
start.search = search;
|
||||||
|
const queue = [start];
|
||||||
|
const found: RenderSection[] = [];
|
||||||
|
// adds the section a step goes into, entered through the face opposite the step's direction
|
||||||
|
const step = (neighbor: RenderSection | undefined, direction: number) => {
|
||||||
|
if (!neighbor) return;
|
||||||
|
// every step goes one further from the camera's section, so all the ways into a section are known by the time
|
||||||
|
// it's taken from the queue
|
||||||
|
if (neighbor.search !== search) {
|
||||||
|
neighbor.search = search;
|
||||||
|
neighbor.incoming = 0;
|
||||||
|
queue.push(neighbor);
|
||||||
|
}
|
||||||
|
neighbor.incoming |= 1 << (direction ^ 1);
|
||||||
|
};
|
||||||
|
for (let i = 0; i < queue.length; i++) {
|
||||||
|
const section = queue[i];
|
||||||
|
// with no quads or visuals its bounds are empty, see ClientLevel.drawn
|
||||||
|
if (section.min_y <= section.max_y) found.push(section);
|
||||||
|
|
||||||
|
// the camera's section can be left any way, even when the camera is inside a block
|
||||||
|
let out = section === start ? ALL_DIRECTIONS : exits(section.visibility, section.incoming);
|
||||||
|
if (!out) continue;
|
||||||
|
// away from the camera's section on every axis
|
||||||
|
const { x, z, sections } = section.chunk;
|
||||||
|
const dx = x - chunk_x;
|
||||||
|
const dy = section.index - index;
|
||||||
|
const dz = z - chunk_z;
|
||||||
|
out &= (dx <= 0 ? 1 : 0) | (dx >= 0 ? 2 : 0) | (dy <= 0 ? 4 : 0) | (dy >= 0 ? 8 : 0) | (dz <= 0 ? 16 : 0) |
|
||||||
|
(dz >= 0 ? 32 : 0);
|
||||||
|
if (out & 1) step(chunk_at(x - 1, z)?.sections[section.index], 0);
|
||||||
|
if (out & 2) step(chunk_at(x + 1, z)?.sections[section.index], 1);
|
||||||
|
if (out & 4) step(sections[section.index - 1], 2);
|
||||||
|
if (out & 8) step(sections[section.index + 1], 3);
|
||||||
|
if (out & 16) step(chunk_at(x, z - 1)?.sections[section.index], 4);
|
||||||
|
if (out & 32) step(chunk_at(x, z + 1)?.sections[section.index], 5);
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
@@ -3,9 +3,9 @@
|
|||||||
|
|
||||||
// minecraft's player model and how it's posed each frame, for drawing players and what they wear. no drawing here, so
|
// minecraft's player model and how it's posed each frame, for drawing players and what they wear. no drawing here, so
|
||||||
// tests can use it
|
// tests can use it
|
||||||
import { PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT } from "$/common/constants.ts";
|
import { PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT } from "@/common/constants.ts";
|
||||||
import { PLAYER_PARTS, type WornProperties } from "$/common/everything_registry.ts";
|
import { PLAYER_PARTS, type WornProperties } from "@/common/everything_registry.ts";
|
||||||
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
|
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
import { apply, IDENTITY, type Matrix, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
import { apply, IDENTITY, type Matrix, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
||||||
|
|
||||||
export type PartName = typeof PLAYER_PARTS[number];
|
export type PartName = typeof PLAYER_PARTS[number];
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { Player } from "$/client/entity/player.ts";
|
import type { Player } from "@/client/entity/player.ts";
|
||||||
import { push_vertex, type Texture } from "$/client/renderer/mod.ts";
|
import { push_vertex, type Texture } from "@/client/renderer/mod.ts";
|
||||||
|
import type { FaceUvs } from "@/common/mod_data.ts";
|
||||||
import type { Vec3 } from "./model_math.ts";
|
import type { Vec3 } from "./model_math.ts";
|
||||||
import {
|
import {
|
||||||
type ModelPart,
|
type ModelPart,
|
||||||
@@ -24,40 +25,52 @@ const UV_INSET = 0.01;
|
|||||||
|
|
||||||
// a box's faces, like minecraft's ModelPart.Cube. `rect` is where the face is in the box's texture, which is laid
|
// a box's faces, like minecraft's ModelPart.Cube. `rect` is where the face is in the box's texture, which is laid
|
||||||
// out as in a skin: the top and bottom above the sides (right, front, left, back). corners go counter clockwise from
|
// out as in a skin: the top and bottom above the sides (right, front, left, back). corners go counter clockwise from
|
||||||
// outside as [x, y, z, u, v], 0 for the low end and 1 for the high one
|
// outside as [x, y, z, u, v], 0 for the low end and 1 for the high one. `name` is the face's in a bedrock model's per
|
||||||
const FACES: { rect: (w: number, h: number, d: number) => number[]; corners: number[][]; shade: number }[] = [
|
// face uvs, which go where its box uv would put it except the bottom, which is upside down
|
||||||
|
const FACES: {
|
||||||
|
name: keyof FaceUvs;
|
||||||
|
rect: (w: number, h: number, d: number) => number[];
|
||||||
|
corners: number[][];
|
||||||
|
shade: number;
|
||||||
|
}[] = [
|
||||||
// top
|
// top
|
||||||
{
|
{
|
||||||
|
name: "up",
|
||||||
rect: (w, _h, d) => [d, 0, w, d],
|
rect: (w, _h, d) => [d, 0, w, d],
|
||||||
corners: [[1, 1, 0, 0, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1, 0], [1, 1, 1, 0, 0]],
|
corners: [[1, 1, 0, 0, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1, 0], [1, 1, 1, 0, 0]],
|
||||||
shade: 1.0,
|
shade: 1.0,
|
||||||
},
|
},
|
||||||
// bottom, the same way around as the top so it's mirrored from below like in minecraft
|
// bottom, the same way around as the top so it's mirrored from below like in minecraft
|
||||||
{
|
{
|
||||||
|
name: "down",
|
||||||
rect: (w, _h, d) => [d + w, 0, w, d],
|
rect: (w, _h, d) => [d + w, 0, w, d],
|
||||||
corners: [[1, 0, 0, 0, 1], [1, 0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 1, 1]],
|
corners: [[1, 0, 0, 0, 1], [1, 0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 1, 1]],
|
||||||
shade: 0.5,
|
shade: 0.5,
|
||||||
},
|
},
|
||||||
// right
|
// right
|
||||||
{
|
{
|
||||||
|
name: "east",
|
||||||
rect: (_w, h, d) => [0, d, d, h],
|
rect: (_w, h, d) => [0, d, d, h],
|
||||||
corners: [[1, 0, 1, 0, 1], [1, 0, 0, 1, 1], [1, 1, 0, 1, 0], [1, 1, 1, 0, 0]],
|
corners: [[1, 0, 1, 0, 1], [1, 0, 0, 1, 1], [1, 1, 0, 1, 0], [1, 1, 1, 0, 0]],
|
||||||
shade: 0.6,
|
shade: 0.6,
|
||||||
},
|
},
|
||||||
// front
|
// front
|
||||||
{
|
{
|
||||||
|
name: "north",
|
||||||
rect: (w, h, d) => [d, d, w, h],
|
rect: (w, h, d) => [d, d, w, h],
|
||||||
corners: [[1, 0, 0, 0, 1], [0, 0, 0, 1, 1], [0, 1, 0, 1, 0], [1, 1, 0, 0, 0]],
|
corners: [[1, 0, 0, 0, 1], [0, 0, 0, 1, 1], [0, 1, 0, 1, 0], [1, 1, 0, 0, 0]],
|
||||||
shade: 0.8,
|
shade: 0.8,
|
||||||
},
|
},
|
||||||
// left
|
// left
|
||||||
{
|
{
|
||||||
|
name: "west",
|
||||||
rect: (w, h, d) => [d + w, d, d, h],
|
rect: (w, h, d) => [d + w, d, d, h],
|
||||||
corners: [[0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 0, 0, 0]],
|
corners: [[0, 0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 0, 0, 0]],
|
||||||
shade: 0.6,
|
shade: 0.6,
|
||||||
},
|
},
|
||||||
// back
|
// back
|
||||||
{
|
{
|
||||||
|
name: "south",
|
||||||
rect: (w, h, d) => [2 * d + w, d, w, h],
|
rect: (w, h, d) => [2 * d + w, d, w, h],
|
||||||
corners: [[0, 0, 1, 0, 1], [1, 0, 1, 1, 1], [1, 1, 1, 1, 0], [0, 1, 1, 0, 0]],
|
corners: [[0, 0, 1, 0, 1], [1, 0, 1, 1, 1], [1, 1, 1, 1, 0], [0, 1, 1, 0, 0]],
|
||||||
shade: 0.8,
|
shade: 0.8,
|
||||||
@@ -87,6 +100,18 @@ export function render_player(skin: Texture, pose: PlayerPose, tint?: Vec3) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// where a face is in the texture as [u, v, width, height] in pixels, undefined when per face uvs leave it out
|
||||||
|
function face_rect(face: typeof FACES[number], [w, h, d]: Vec3, uv: [number, number] | FaceUvs) {
|
||||||
|
if (Array.isArray(uv)) {
|
||||||
|
const [rx, ry, rw, rh] = face.rect(w, h, d);
|
||||||
|
return [uv[0] + rx, uv[1] + ry, rw, rh];
|
||||||
|
}
|
||||||
|
const own = uv[face.name];
|
||||||
|
if (!own) return undefined;
|
||||||
|
const [[u, v], [rw, rh]] = [own.uv, own.uv_size];
|
||||||
|
return face.name === "down" ? [u, v + rh, rw, -rh] : [u, v, rw, rh];
|
||||||
|
}
|
||||||
|
|
||||||
// what a box's vertices go to: the batch, or something collecting them, like the player in the inventory
|
// what a box's vertices go to: the batch, or something collecting them, like the player in the inventory
|
||||||
export type VertexSink = typeof push_vertex;
|
export type VertexSink = typeof push_vertex;
|
||||||
|
|
||||||
@@ -105,13 +130,14 @@ export function push_cube(
|
|||||||
push_box(part.size, low, high, uv, (u, v) => [u / skin.width, v / skin.height], transform, tint, emit);
|
push_box(part.size, low, high, uv, (u, v) => [u / skin.width, v / skin.height], transform, tint, emit);
|
||||||
}
|
}
|
||||||
|
|
||||||
// a box of a model, from low to high, textured like minecraft's box uv from [u, v] for a box of size (in texture
|
// a box of a model, from low to high, textured from uv: minecraft's box uv from [u, v] for a box of size (in texture
|
||||||
// pixels). to_uv turns texture pixels into the current texture's coordinates, tint multiplies its colors
|
// pixels), or a bedrock model's per face uvs. to_uv turns texture pixels into the current texture's coordinates, tint
|
||||||
|
// multiplies its colors
|
||||||
export function push_box(
|
export function push_box(
|
||||||
size: Vec3,
|
size: Vec3,
|
||||||
low: Vec3,
|
low: Vec3,
|
||||||
high: Vec3,
|
high: Vec3,
|
||||||
[u, v]: [number, number],
|
uv: [number, number] | FaceUvs,
|
||||||
to_uv: (u: number, v: number) => [number, number],
|
to_uv: (u: number, v: number) => [number, number],
|
||||||
transform: (x: number, y: number, z: number) => Vec3,
|
transform: (x: number, y: number, z: number) => Vec3,
|
||||||
tint: Vec3 = [1, 1, 1],
|
tint: Vec3 = [1, 1, 1],
|
||||||
@@ -125,9 +151,14 @@ export function push_box(
|
|||||||
points.push(transform(i & 4 ? high[0] : low[0], i & 2 ? high[1] : low[1], i & 1 ? high[2] : low[2]));
|
points.push(transform(i & 4 ? high[0] : low[0], i & 2 ? high[1] : low[1], i & 1 ? high[2] : low[2]));
|
||||||
}
|
}
|
||||||
for (const face of FACES) {
|
for (const face of FACES) {
|
||||||
const [rx, ry, rw, rh] = face.rect(w, h, d);
|
const rect = face_rect(face, size, uv);
|
||||||
const [u0, v0] = to_uv(u + rx + UV_INSET, v + ry + UV_INSET);
|
if (!rect) continue;
|
||||||
const [u1, v1] = to_uv(u + rx + rw - UV_INSET, v + ry + rh - UV_INSET);
|
const [rx, ry, rw, rh] = rect;
|
||||||
|
// inward, which is backwards on a flipped face
|
||||||
|
const inset_u = Math.sign(rw) * UV_INSET;
|
||||||
|
const inset_v = Math.sign(rh) * UV_INSET;
|
||||||
|
const [u0, v0] = to_uv(rx + inset_u, ry + inset_v);
|
||||||
|
const [u1, v1] = to_uv(rx + rw - inset_u, ry + rh - inset_v);
|
||||||
const r = tint[0] * face.shade;
|
const r = tint[0] * face.shade;
|
||||||
const g = tint[1] * face.shade;
|
const g = tint[1] * face.shade;
|
||||||
const b = tint[2] * face.shade;
|
const b = tint[2] * face.shade;
|
||||||
|
|||||||
@@ -2,20 +2,20 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { mat4, vec3 } from "gl-matrix";
|
import { mat4, vec3 } from "gl-matrix";
|
||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
import { SLOT_SIZE } from "@/common/constants.ts";
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { FluidVariant } from "$/common/mod_api/shared.ts";
|
import type { FluidVariant } from "@/common/mod_api/shared.ts";
|
||||||
import { item_texture } from "$/common/utils.ts";
|
import { item_texture } from "@/common/utils.ts";
|
||||||
import {
|
import {
|
||||||
cube_face_texture,
|
cube_face_texture,
|
||||||
cube_face_tint,
|
cube_face_tint,
|
||||||
type DisplayTransform,
|
type DisplayTransform,
|
||||||
ITEM_FACE_SHADE,
|
ITEM_FACE_SHADE,
|
||||||
item_tint,
|
item_tint,
|
||||||
} from "$/common/block_models.ts";
|
} from "@/common/block_models.ts";
|
||||||
import {
|
import {
|
||||||
display_matrix,
|
display_matrix,
|
||||||
fluid_look,
|
fluid_look,
|
||||||
@@ -34,7 +34,7 @@ import {
|
|||||||
push_vertex,
|
push_vertex,
|
||||||
Texture,
|
Texture,
|
||||||
use_texture,
|
use_texture,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
|
|
||||||
// the corners keep their size (times scale), the edges stretch along and the middle fills the rest, like minecraft's
|
// the corners keep their size (times scale), the edges stretch along and the middle fills the rest, like minecraft's
|
||||||
// nine slice gui sprites. borders are in source pixels
|
// nine slice gui sprites. borders are in source pixels
|
||||||
@@ -142,7 +142,7 @@ function draw_item_item(item: ItemStack, item_info: ItemRegistry, x: number, y:
|
|||||||
const draw = (texture_id: string, [r, g, b] = [1, 1, 1]) => {
|
const draw = (texture_id: string, [r, g, b] = [1, 1, 1]) => {
|
||||||
const sprite_region = get_sprite_region(texture_id);
|
const sprite_region = get_sprite_region(texture_id);
|
||||||
draw_texture_region(
|
draw_texture_region(
|
||||||
AssetManager.instance.get("bworld:textures"),
|
AssetManager.instance.get("cubi:textures"),
|
||||||
sprite_region.x,
|
sprite_region.x,
|
||||||
sprite_region.y,
|
sprite_region.y,
|
||||||
sprite_region.width,
|
sprite_region.width,
|
||||||
@@ -172,7 +172,7 @@ export function draw_fluid(fluid: FluidVariant, x: number, y: number, filled = 1
|
|||||||
const region = get_sprite_region(texture);
|
const region = get_sprite_region(texture);
|
||||||
const size = SLOT_SIZE - 6;
|
const size = SLOT_SIZE - 6;
|
||||||
draw_texture_region(
|
draw_texture_region(
|
||||||
AssetManager.instance.get("bworld:textures"),
|
AssetManager.instance.get("cubi:textures"),
|
||||||
region.x,
|
region.x,
|
||||||
region.y + region.height * (1 - done),
|
region.y + region.height * (1 - done),
|
||||||
region.width,
|
region.width,
|
||||||
@@ -212,7 +212,7 @@ const model_icons = new WeakMap<ItemModel, Float32Array>();
|
|||||||
|
|
||||||
// an item's model in a slot: its faces that face the viewer, back to front
|
// an item's model in a slot: its faces that face the viewer, back to front
|
||||||
function draw_item_model(model: ItemModel, x: number, y: number) {
|
function draw_item_model(model: ItemModel, x: number, y: number) {
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
use_texture(atlas.tex);
|
use_texture(atlas.tex);
|
||||||
let icon = model_icons.get(model);
|
let icon = model_icons.get(model);
|
||||||
if (!icon) {
|
if (!icon) {
|
||||||
@@ -277,7 +277,7 @@ function draw_item_block(block_info: BlockRegistry, x: number, y: number) {
|
|||||||
const front_texture = cube_face_texture(block_info, "front");
|
const front_texture = cube_face_texture(block_info, "front");
|
||||||
const left_texture = cube_face_texture(block_info, "side");
|
const left_texture = cube_face_texture(block_info, "side");
|
||||||
|
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
|
|
||||||
const top = get_sprite_region(top_texture);
|
const top = get_sprite_region(top_texture);
|
||||||
const front = get_sprite_region(front_texture);
|
const front = get_sprite_region(front_texture);
|
||||||
|
|||||||
+45
-31
@@ -2,8 +2,8 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// blocks drawn with code, like a shaft that turns, see ctx.render.register_visual. like flywheel's visuals: one per
|
// blocks drawn with code, like a shaft that turns, see ctx.render.register_visual. like flywheel's visuals: one per
|
||||||
// block, made when its chunk is meshed and kept by chunk. what they draw are instances of models, and every instance of
|
// block, made when its section is meshed and kept by chunk. what they draw are instances of models, and every instance
|
||||||
// a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in
|
// of a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in
|
||||||
// client/renderer/core.ts). the gpu turns rotating ones by the time, so a shaft that keeps turning costs nothing per
|
// client/renderer/core.ts). the gpu turns rotating ones by the time, so a shaft that keeps turning costs nothing per
|
||||||
// frame. an item is a model too, one per way an item can look, and a fluid's box is a model of its own
|
// frame. an item is a model too, one per way an item can look, and a fluid's box is a model of its own
|
||||||
import { mat4, vec3 } from "gl-matrix";
|
import { mat4, vec3 } from "gl-matrix";
|
||||||
@@ -16,8 +16,8 @@ import type {
|
|||||||
TransformedInstance,
|
TransformedInstance,
|
||||||
Visual,
|
Visual,
|
||||||
VisualBlock,
|
VisualBlock,
|
||||||
} from "$/common/mod_api/client.ts";
|
} from "@/common/mod_api/client.ts";
|
||||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import {
|
import {
|
||||||
bake_block,
|
bake_block,
|
||||||
bake_model,
|
bake_model,
|
||||||
@@ -27,11 +27,12 @@ import {
|
|||||||
type ModelElementJson,
|
type ModelElementJson,
|
||||||
type ModelJson,
|
type ModelJson,
|
||||||
states_of,
|
states_of,
|
||||||
} from "$/common/block_models.ts";
|
} from "@/common/block_models.ts";
|
||||||
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
|
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||||
import type { ModelFace } from "$/common/mod_data.ts";
|
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import type { ModelFace } from "@/common/mod_data.ts";
|
||||||
import { chunk_key, item_texture } from "$/common/utils.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
|
import { chunk_key, item_texture } from "@/common/utils.ts";
|
||||||
import {
|
import {
|
||||||
create_vertex_buffer,
|
create_vertex_buffer,
|
||||||
destroy_buffer,
|
destroy_buffer,
|
||||||
@@ -40,8 +41,8 @@ import {
|
|||||||
MODEL_VERTEX_BYTES,
|
MODEL_VERTEX_BYTES,
|
||||||
type Texture,
|
type Texture,
|
||||||
write_buffer,
|
write_buffer,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { fluid_look, ground_transform, item_layers, push_item, sprite_u, sprite_v } from "./item_renderer.ts";
|
import { fluid_look, ground_transform, item_layers, push_item, sprite_u, sprite_v } from "./item_renderer.ts";
|
||||||
|
|
||||||
export interface VisualRegistration {
|
export interface VisualRegistration {
|
||||||
@@ -186,7 +187,7 @@ interface Entry {
|
|||||||
|
|
||||||
// a level's visuals
|
// a level's visuals
|
||||||
export class Visuals {
|
export class Visuals {
|
||||||
// by chunk_key, then the block's index in its chunk
|
// by chunk_key, then the block's index in its chunk counted from y 0, see #index
|
||||||
#chunks = new Map<number, Map<number, Entry>>();
|
#chunks = new Map<number, Map<number, Entry>>();
|
||||||
#level: VisualsLevel;
|
#level: VisualsLevel;
|
||||||
// baked once per level, since a level's mods don't change
|
// baked once per level, since a level's mods don't change
|
||||||
@@ -213,31 +214,41 @@ export class Visuals {
|
|||||||
yield* this.#fluid_groups;
|
yield* this.#fluid_groups;
|
||||||
}
|
}
|
||||||
|
|
||||||
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals
|
// the blocks with visuals a chunk's section was meshed with, as pairs of the block's index in the section (see
|
||||||
// for blocks that are gone or changed go, and new ones are made. the chunk's light came with its mesh, so the ones
|
// section_index) and its value. bottom is the section's lowest y. visuals in it for blocks that are gone or
|
||||||
// that stay take it
|
// changed go, and new ones are made. the section's light came with its mesh, so the ones that stay take it
|
||||||
meshed(chunk_x: number, chunk_z: number, found: Uint32Array) {
|
meshed(chunk_x: number, chunk_z: number, bottom: number, found: Uint32Array) {
|
||||||
const key = chunk_key(chunk_x, chunk_z);
|
const key = chunk_key(chunk_x, chunk_z);
|
||||||
const old = this.#chunks.get(key) ?? new Map<number, Entry>();
|
const entries = this.#chunks.get(key) ?? new Map<number, Entry>();
|
||||||
const kept = new Map<number, Entry>();
|
const old = new Map<number, Entry>();
|
||||||
|
for (const [index, entry] of entries) {
|
||||||
|
if (entry.y >= bottom && entry.y < bottom + SECTION_HEIGHT) old.set(index, entry);
|
||||||
|
}
|
||||||
for (let i = 0; i < found.length; i += 2) {
|
for (let i = 0; i < found.length; i += 2) {
|
||||||
const index = found[i];
|
const local = found[i];
|
||||||
|
const x = chunk_x * CHUNK_SIZE + (local & 15);
|
||||||
|
const y = bottom + (local >> 8);
|
||||||
|
const z = chunk_z * CHUNK_SIZE + ((local >> 4) & 15);
|
||||||
|
const index = this.#index(x, y, z);
|
||||||
const value = found[i + 1];
|
const value = found[i + 1];
|
||||||
const entry = old.get(index);
|
const entry = old.get(index);
|
||||||
old.delete(index);
|
old.delete(index);
|
||||||
if (entry?.value === value) {
|
if (entry?.value === value) {
|
||||||
this.#relight(entry);
|
this.#relight(entry);
|
||||||
kept.set(index, entry);
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (entry) this.#delete(entry);
|
if (entry) {
|
||||||
const x = chunk_x * CHUNK_SIZE + (index % CHUNK_SIZE);
|
this.#delete(entry);
|
||||||
const z = chunk_z * CHUNK_SIZE + Math.floor(index / CHUNK_SIZE) % CHUNK_SIZE;
|
entries.delete(index);
|
||||||
const made = this.#create(x, Math.floor(index / CHUNK_AREA), z, value);
|
|
||||||
if (made) kept.set(index, made);
|
|
||||||
}
|
}
|
||||||
for (const entry of old.values()) this.#delete(entry);
|
const made = this.#create(x, y, z, value);
|
||||||
if (kept.size > 0) this.#chunks.set(key, kept);
|
if (made) entries.set(index, made);
|
||||||
|
}
|
||||||
|
for (const [index, entry] of old) {
|
||||||
|
this.#delete(entry);
|
||||||
|
entries.delete(index);
|
||||||
|
}
|
||||||
|
if (entries.size > 0) this.#chunks.set(key, entries);
|
||||||
else this.#chunks.delete(key);
|
else this.#chunks.delete(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -279,10 +290,13 @@ export class Visuals {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#entry(x: number, y: number, z: number) {
|
#entry(x: number, y: number, z: number) {
|
||||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
|
||||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
return this.#chunks.get(key)?.get(this.#index(x, y, z));
|
||||||
const index = y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
|
}
|
||||||
return this.#chunks.get(chunk_key(chunk_x, chunk_z))?.get(index);
|
|
||||||
|
// a block's place in its chunk's map
|
||||||
|
#index(x: number, y: number, z: number) {
|
||||||
|
return y * CHUNK_AREA + (z & 15) * CHUNK_SIZE + (x & 15);
|
||||||
}
|
}
|
||||||
|
|
||||||
#create(x: number, y: number, z: number, value: number): Entry | undefined {
|
#create(x: number, y: number, z: number, value: number): Entry | undefined {
|
||||||
|
|||||||
@@ -4,14 +4,14 @@
|
|||||||
// what players wear, like curios' render layer: each worn item's model (see WornProperties) on the player, its bones
|
// what players wear, like curios' render layer: each worn item's model (see WornProperties) on the player, its bones
|
||||||
// named like the player's parts turned the way those parts are, so it moves with them like minecraft's
|
// named like the player's parts turned the way those parts are, so it moves with them like minecraft's
|
||||||
// TransformCopyingHumanoidModel. see docs/modding/items/index.md
|
// TransformCopyingHumanoidModel. see docs/modding/items/index.md
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import type { Player } from "$/client/entity/player.ts";
|
import type { Player } from "@/client/entity/player.ts";
|
||||||
import type { ItemStack } from "$/common/inventory.ts";
|
import type { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { Texture } from "$/client/renderer/mod.ts";
|
import type { Texture } from "@/client/renderer/mod.ts";
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
|
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
import { IDENTITY, type Vec3 } from "./model_math.ts";
|
import { bone_matrices, IDENTITY, type Vec3 } from "./model_math.ts";
|
||||||
import { push_model } from "./model_renderer.ts";
|
import { push_model } from "./model_renderer.ts";
|
||||||
import type { VertexSink } from "./player_renderer.ts";
|
import type { VertexSink } from "./player_renderer.ts";
|
||||||
import { on_part, type PlayerPose, pose_to_world, right_arm, worn_bone_pose, worn_look } from "./player_model.ts";
|
import { on_part, type PlayerPose, pose_to_world, right_arm, worn_bone_pose, worn_look } from "./player_model.ts";
|
||||||
@@ -24,7 +24,7 @@ export function render_worn(player: Player, pose: PlayerPose, tint?: Vec3) {
|
|||||||
// what's worn on a player in that pose, its vertices to emit, the batch by default, like the player in the inventory
|
// what's worn on a player in that pose, its vertices to emit, the batch by default, like the player in the inventory
|
||||||
export function push_worn(worn_items: ItemStack[], pose: PlayerPose, tint?: Vec3, emit?: VertexSink) {
|
export function push_worn(worn_items: ItemStack[], pose: PlayerPose, tint?: Vec3, emit?: VertexSink) {
|
||||||
if (worn_items.length === 0) return;
|
if (worn_items.length === 0) return;
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
const to_world = pose_to_world(pose);
|
const to_world = pose_to_world(pose);
|
||||||
for (const stack of worn_items) {
|
for (const stack of worn_items) {
|
||||||
const worn = EverythingRegistry.get<ItemRegistry>("items", stack.type_id)?.worn;
|
const worn = EverythingRegistry.get<ItemRegistry>("items", stack.type_id)?.worn;
|
||||||
@@ -34,7 +34,7 @@ export function push_worn(worn_items: ItemStack[], pose: PlayerPose, tint?: Vec3
|
|||||||
if (!model) continue;
|
if (!model) continue;
|
||||||
push_model(
|
push_model(
|
||||||
model,
|
model,
|
||||||
worn_bone_pose(pose),
|
bone_matrices(model, worn_bone_pose(pose)),
|
||||||
atlas,
|
atlas,
|
||||||
get_sprite_region(look.texture),
|
get_sprite_region(look.texture),
|
||||||
to_world,
|
to_world,
|
||||||
@@ -48,7 +48,7 @@ export function push_worn(worn_items: ItemStack[], pose: PlayerPose, tint?: Vec3
|
|||||||
// what's worn on a player's right arm, in first person, like artifacts' renderFirstPersonArm. transform is the arm's,
|
// what's worn on a player's right arm, in first person, like artifacts' renderFirstPersonArm. transform is the arm's,
|
||||||
// from points around its pivot (see hand_renderer's arm_pose). the atlas has to be the current texture
|
// from points around its pivot (see hand_renderer's arm_pose). the atlas has to be the current texture
|
||||||
export function render_worn_arm(player: Player, transform: (x: number, y: number, z: number) => Vec3, tint?: Vec3) {
|
export function render_worn_arm(player: Player, transform: (x: number, y: number, z: number) => Vec3, tint?: Vec3) {
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
const [px, py, pz] = right_arm(player.slim).pivot;
|
const [px, py, pz] = right_arm(player.slim).pivot;
|
||||||
// the model's pixels, standing still, to around the arm's pivot
|
// the model's pixels, standing still, to around the arm's pivot
|
||||||
const to_arm = (x: number, y: number, z: number) => transform(x - px, y - py, z - pz);
|
const to_arm = (x: number, y: number, z: number) => transform(x - px, y - py, z - pz);
|
||||||
@@ -59,6 +59,7 @@ export function render_worn_arm(player: Player, transform: (x: number, y: number
|
|||||||
const model = EverythingRegistry.get<EntityModelJson>("entity_models", look.model);
|
const model = EverythingRegistry.get<EntityModelJson>("entity_models", look.model);
|
||||||
if (!model) continue;
|
if (!model) continue;
|
||||||
const only = (bone: EntityBoneJson) => on_part(model, bone, "right_arm");
|
const only = (bone: EntityBoneJson) => on_part(model, bone, "right_arm");
|
||||||
push_model(model, () => IDENTITY, atlas, get_sprite_region(look.texture), to_arm, tint, only);
|
const bones = bone_matrices(model, () => IDENTITY);
|
||||||
|
push_model(model, bones, atlas, get_sprite_region(look.texture), to_arm, tint, only);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-11
@@ -2,19 +2,14 @@
|
|||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { load_texture, type Texture } from "./renderer/mod.ts";
|
import { load_texture, type Texture } from "./renderer/mod.ts";
|
||||||
|
import { decode_png } from "./png.ts";
|
||||||
|
|
||||||
// a player's skin as the server sends it (a base64 64x64 png), undefined when it can't be decoded
|
// a player's skin as the server sends it (a base64 64x64 png), undefined when it can't be decoded. pixels are as
|
||||||
export async function decode_skin(skin: string): Promise<Texture | undefined> {
|
// stored, so pngs with a color profile look the same as in an editor that ignores it
|
||||||
|
export function decode_skin(skin: string): Texture | undefined {
|
||||||
try {
|
try {
|
||||||
const bytes = Uint8Array.from(atob(skin), (char) => char.charCodeAt(0));
|
const image = decode_png(Uint8Array.from(atob(skin), (char) => char.charCodeAt(0)));
|
||||||
// as stored, so pngs with a color profile look the same as in an editor that ignores it, like minecraft
|
return image.width === 64 && image.height === 64 ? load_texture(image) : undefined;
|
||||||
const image = await createImageBitmap(new Blob([bytes], { type: "image/png" }), {
|
|
||||||
colorSpaceConversion: "none",
|
|
||||||
premultiplyAlpha: "none",
|
|
||||||
});
|
|
||||||
const texture = image.width === 64 && image.height === 64 ? load_texture(image) : undefined;
|
|
||||||
image.close();
|
|
||||||
return texture;
|
|
||||||
} catch {
|
} catch {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// what sounds play on this client, and where from: ctx.sounds.play for client phases. the sounds are the mods'
|
||||||
|
// sounds.json, see docs/modding/resources/sounds.md. this decides what plays, an output (client/audio_output.ts in the
|
||||||
|
// browser) plays it
|
||||||
|
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import { sound_of, sound_range, sound_to_play, type SoundCategory, type SoundJson } from "@/common/mod_data.ts";
|
||||||
|
import type { ClientPlayOptions, PlayingSound } from "@/common/mod_api/client.ts";
|
||||||
|
import type { Position } from "@/common/mod_api/shared.ts";
|
||||||
|
|
||||||
|
export type Volumes = Record<"master" | SoundCategory, number>;
|
||||||
|
|
||||||
|
// sounds playing at once at most. past that a new one is dropped, and loops wait for room
|
||||||
|
const MAX_VOICES = 64;
|
||||||
|
|
||||||
|
// what sounds come out of: web audio in the browser, a list in tests
|
||||||
|
export interface SoundOutput {
|
||||||
|
// starts a file playing. undefined when nothing can play now, like before the player's first click
|
||||||
|
start(file: SoundFile, settings: VoiceSettings): Voice | undefined;
|
||||||
|
// where the player hears from, and which way they look, in radians like the camera
|
||||||
|
listen(x: number, y: number, z: number, yaw: number, pitch: number): void;
|
||||||
|
set_volumes(volumes: Volumes): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a mod's file, by "<mod id>:<path in its sounds/>"
|
||||||
|
export interface SoundFile {
|
||||||
|
readonly id: string;
|
||||||
|
readonly bytes: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VoiceSettings {
|
||||||
|
// only master's volume when not given
|
||||||
|
category: SoundCategory | undefined;
|
||||||
|
// heard as it is when not given
|
||||||
|
at: Position | undefined;
|
||||||
|
// where it's faded to nothing
|
||||||
|
range: number;
|
||||||
|
// over 1 is heard further, which range has already, not louder
|
||||||
|
volume: number;
|
||||||
|
pitch: number;
|
||||||
|
loop: boolean;
|
||||||
|
// seconds into the file it starts at, for one played with an offset or a loop coming back partway. past the file's
|
||||||
|
// length a loop goes around, and anything else has finished
|
||||||
|
offset: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// one file playing
|
||||||
|
export interface Voice {
|
||||||
|
// it played to its end
|
||||||
|
readonly ended: boolean;
|
||||||
|
move(at: Position): void;
|
||||||
|
set(volume: number, pitch: number, range: number): void;
|
||||||
|
stop(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// where the player hears from, like the camera
|
||||||
|
export interface Listener extends Position {
|
||||||
|
yaw: number;
|
||||||
|
pitch: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Playing implements PlayingSound {
|
||||||
|
voice: Voice | undefined;
|
||||||
|
done = false;
|
||||||
|
#volume: number;
|
||||||
|
#pitch: number;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
readonly json: SoundJson,
|
||||||
|
readonly file: SoundFile,
|
||||||
|
readonly options: ClientPlayOptions,
|
||||||
|
readonly started: number,
|
||||||
|
public at: Position | undefined,
|
||||||
|
) {
|
||||||
|
this.#volume = options.volume ?? 1;
|
||||||
|
this.#pitch = options.pitch ?? 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
get playing() {
|
||||||
|
return !this.done;
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.done = true;
|
||||||
|
this.voice?.stop();
|
||||||
|
this.voice = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
get volume() {
|
||||||
|
return this.#volume;
|
||||||
|
}
|
||||||
|
|
||||||
|
set volume(volume: number) {
|
||||||
|
this.#volume = volume;
|
||||||
|
this.voice?.set(this.total_volume, this.total_pitch, this.range);
|
||||||
|
}
|
||||||
|
|
||||||
|
get pitch() {
|
||||||
|
return this.#pitch;
|
||||||
|
}
|
||||||
|
|
||||||
|
set pitch(pitch: number) {
|
||||||
|
this.#pitch = pitch;
|
||||||
|
this.voice?.set(this.total_volume, this.total_pitch, this.range);
|
||||||
|
}
|
||||||
|
|
||||||
|
get total_volume() {
|
||||||
|
return (this.json.volume ?? 1) * this.#volume;
|
||||||
|
}
|
||||||
|
|
||||||
|
get total_pitch() {
|
||||||
|
return (this.json.pitch ?? 1) * this.#pitch;
|
||||||
|
}
|
||||||
|
|
||||||
|
get range() {
|
||||||
|
return sound_range(this.json, this.#volume);
|
||||||
|
}
|
||||||
|
|
||||||
|
// whether the listener is close enough to hear it, always for one heard as it is
|
||||||
|
in_range(listener: Position) {
|
||||||
|
if (!this.at) return true;
|
||||||
|
const { x, y, z } = this.at;
|
||||||
|
return Math.hypot(x - listener.x, y - listener.y, z - listener.z) < this.range;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Sounds {
|
||||||
|
#output: SoundOutput | undefined;
|
||||||
|
// the mods' files, by "<mod id>:<path>"
|
||||||
|
#files = new Map<string, SoundFile>();
|
||||||
|
#playing: Playing[] = [];
|
||||||
|
#listener: Position = { x: 0, y: 0, z: 0 };
|
||||||
|
#entity_position: (id: string) => Position | undefined = () => undefined;
|
||||||
|
|
||||||
|
// seconds, for how far a loop has got
|
||||||
|
constructor(readonly clock = () => performance.now() / 1000) {}
|
||||||
|
|
||||||
|
set_output(output: SoundOutput) {
|
||||||
|
this.#output = output;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the loaded mods' sound files, in place of the last server's
|
||||||
|
set_files(mods: { id: string; sounds?: Map<string, Uint8Array> }[]) {
|
||||||
|
this.stop_all();
|
||||||
|
this.#files.clear();
|
||||||
|
for (const mod of mods) {
|
||||||
|
for (const [path, bytes] of mod.sounds ?? []) {
|
||||||
|
const id = `${mod.id}:${path}`;
|
||||||
|
this.#files.set(id, { id, bytes });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exists(sound: string) {
|
||||||
|
return EverythingRegistry.get<SoundJson>("sounds", sound) !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
play(sound: string, options: ClientPlayOptions = {}): PlayingSound {
|
||||||
|
const json = sound_to_play(sound, options);
|
||||||
|
const offset = options.offset ?? 0;
|
||||||
|
if (typeof offset !== "number" || !(offset >= 0) || !Number.isFinite(offset)) {
|
||||||
|
throw new Error("a sound's offset must be 0 or more seconds");
|
||||||
|
}
|
||||||
|
const path = json.files[Math.floor(Math.random() * json.files.length)];
|
||||||
|
const file = this.#files.get(`${sound.split(":")[0]}:${path}`);
|
||||||
|
if (!file) throw new Error(`sound ${sound} has no file ${path}`);
|
||||||
|
|
||||||
|
const at = options.follow !== undefined ? this.#entity_position(options.follow) : options.at;
|
||||||
|
const playing = new Playing(json, file, { ...options }, this.clock() - offset, at && { ...at });
|
||||||
|
this.#playing.push(playing);
|
||||||
|
// an entity this client doesn't have yet, like one whose animator is being made, has until the next frame to
|
||||||
|
// turn up
|
||||||
|
if (options.follow !== undefined && !at) return playing;
|
||||||
|
this.#start(playing);
|
||||||
|
if (!playing.voice && !options.loop) playing.done = true;
|
||||||
|
return playing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the sound a block's or entity's "sounds" prefix has for kind, when it has one, see BLOCK_SOUNDS and ENTITY_SOUNDS
|
||||||
|
play_of(prefix: string | undefined, kind: string, options: ClientPlayOptions) {
|
||||||
|
const sound = sound_of(prefix, kind);
|
||||||
|
if (sound) this.play(sound, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
// before each frame: the player hears from listener, sounds following an entity go where it's drawn
|
||||||
|
frame(listener: Listener, entity_position: (id: string) => Position | undefined, volumes: Volumes) {
|
||||||
|
this.#listener = { x: listener.x, y: listener.y, z: listener.z };
|
||||||
|
this.#entity_position = entity_position;
|
||||||
|
this.#output?.listen(listener.x, listener.y, listener.z, listener.yaw, listener.pitch);
|
||||||
|
this.#output?.set_volumes(volumes);
|
||||||
|
|
||||||
|
for (const playing of this.#playing) {
|
||||||
|
if (playing.done) continue;
|
||||||
|
const follow = playing.options.follow;
|
||||||
|
if (follow !== undefined) {
|
||||||
|
const at = entity_position(follow);
|
||||||
|
if (!at) {
|
||||||
|
playing.stop();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
playing.at = { x: at.x, y: at.y, z: at.z };
|
||||||
|
playing.voice?.move(playing.at);
|
||||||
|
}
|
||||||
|
if (playing.voice?.ended) {
|
||||||
|
playing.voice = undefined;
|
||||||
|
if (!playing.options.loop) playing.done = true;
|
||||||
|
}
|
||||||
|
// loops out of range wait without a voice
|
||||||
|
if (playing.voice && playing.options.loop && !playing.in_range(this.#listener)) {
|
||||||
|
playing.voice.stop();
|
||||||
|
playing.voice = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.#playing = this.#playing.filter((playing) => !playing.done);
|
||||||
|
for (const playing of this.#playing) {
|
||||||
|
if (playing.voice) continue;
|
||||||
|
this.#start(playing);
|
||||||
|
// one waiting for its entity that can't play now never will
|
||||||
|
if (!playing.voice && !playing.options.loop) playing.done = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// leaving the server
|
||||||
|
stop_all() {
|
||||||
|
for (const playing of this.#playing) playing.stop();
|
||||||
|
this.#playing = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// how many are playing now, for tests
|
||||||
|
get voices() {
|
||||||
|
return this.#playing.filter((playing) => playing.voice).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
#start(playing: Playing) {
|
||||||
|
if (!this.#output || !playing.in_range(this.#listener) || this.voices >= MAX_VOICES) return;
|
||||||
|
playing.voice = this.#output.start(playing.file, {
|
||||||
|
category: playing.json.category,
|
||||||
|
at: playing.at,
|
||||||
|
range: playing.range,
|
||||||
|
volume: playing.total_volume,
|
||||||
|
pitch: playing.total_pitch,
|
||||||
|
loop: playing.options.loop ?? false,
|
||||||
|
offset: (this.clock() - playing.started) * playing.total_pitch,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the client's, which ctx.sounds plays on
|
||||||
|
export const sounds = new Sounds();
|
||||||
+2
-2
@@ -1,13 +1,13 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { type SpriteRegion, TEXTURE_SIZE } from "$/common/constants.ts";
|
import { type SpriteRegion, TEXTURE_SIZE } from "@/common/constants.ts";
|
||||||
import { AssetManager } from "./assets.ts";
|
import { AssetManager } from "./assets.ts";
|
||||||
|
|
||||||
type TexturesInfo = Record<string, SpriteRegion>;
|
type TexturesInfo = Record<string, SpriteRegion>;
|
||||||
|
|
||||||
export function get_sprite_region(id: string): SpriteRegion {
|
export function get_sprite_region(id: string): SpriteRegion {
|
||||||
const textures_info = AssetManager.instance.get<TexturesInfo>("bworld:textures_info");
|
const textures_info = AssetManager.instance.get<TexturesInfo>("cubi:textures_info");
|
||||||
return textures_info?.[id] ?? textures_info?.["cubi:missing"] ??
|
return textures_info?.[id] ?? textures_info?.["cubi:missing"] ??
|
||||||
{ x: 0, y: 0, width: TEXTURE_SIZE, height: TEXTURE_SIZE };
|
{ x: 0, y: 0, width: TEXTURE_SIZE, height: TEXTURE_SIZE };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
|
|
||||||
// animated textures play like minecraft's: the atlas holds one frame of each, and every tick the ones whose frame
|
// animated textures play like minecraft's: the atlas holds one frame of each, and every tick the ones whose frame
|
||||||
// changed copy the new frame's pixels over it. models never change, only the atlas does
|
// changed copy the new frame's pixels over it. models never change, only the atlas does
|
||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
import type { Animation } from "$/common/texture_animation.ts";
|
import type { Animation } from "@/common/texture_animation.ts";
|
||||||
|
|
||||||
// pixels to copy into a texture's place in the atlas: frame_width × frame_height of them, starting at offset bytes
|
// pixels to copy into a texture's place in the atlas: frame_width × frame_height of them, starting at offset bytes
|
||||||
// into data, rows bytes_per_row apart
|
// into data, rows bytes_per_row apart
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { BlockRegistry } from "$/common/everything_registry.ts";
|
import type { BlockRegistry } from "@/common/everything_registry.ts";
|
||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
import type { ModelJson } from "$/common/block_models.ts";
|
import type { ModelJson } from "@/common/block_models.ts";
|
||||||
|
import type { WorldShapeJson } from "@/common/world_shape.ts";
|
||||||
|
import type { SectionBiomes, SectionData } from "@/common/section.ts";
|
||||||
import type { SortType } from "./translucent_sort.ts";
|
import type { SortType } from "./translucent_sort.ts";
|
||||||
|
|
||||||
// messages between the main thread and the chunk workers
|
// messages between the main thread and the chunk workers
|
||||||
@@ -38,15 +40,27 @@ export type ToChunkWorker =
|
|||||||
// the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see
|
// the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see
|
||||||
// ctx.render.register_visual
|
// ctx.render.register_visual
|
||||||
visuals: [number, boolean][];
|
visuals: [number, boolean][];
|
||||||
|
// the dimension's height and sky light
|
||||||
|
shape: WorldShapeJson;
|
||||||
}
|
}
|
||||||
|
// sections of one chunk to mesh, sent together so they're lit together
|
||||||
| {
|
| {
|
||||||
type: "mesh";
|
type: "mesh";
|
||||||
chunk_x: number;
|
chunk_x: number;
|
||||||
chunk_z: number;
|
chunk_z: number;
|
||||||
version: number;
|
// the sections to mesh, by index from the bottom of the world, and the mesh_version each is meshed for
|
||||||
// copies of the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting
|
sections: { index: number; version: number }[];
|
||||||
chunks: (Uint32Array | null)[];
|
// the index of the lowest section in chunks
|
||||||
// the same chunks' biome colors (see Chunk.biome_colors in client_level.ts), blended across their edges
|
first: number;
|
||||||
|
// the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting. each one's sections from the
|
||||||
|
// one below the lowest to mesh to the one above the highest, as far as the world goes. null for a chunk that
|
||||||
|
// isn't loaded
|
||||||
|
chunks: (SectionData[] | null)[];
|
||||||
|
// the same chunks' sky heights, see column_heights in common/section.ts
|
||||||
|
sky: (Int16Array | null)[];
|
||||||
|
// the same chunks' biome cells, of the same sections as chunks, and their biome palettes' colors (see
|
||||||
|
// Chunk.biome_colors in client_level.ts), blended across their edges
|
||||||
|
biomes: (SectionBiomes[] | null)[];
|
||||||
biome_colors: (Uint32Array | null)[];
|
biome_colors: (Uint32Array | null)[];
|
||||||
// where the camera is, to sort the translucent quads
|
// where the camera is, to sort the translucent quads
|
||||||
camera: number[];
|
camera: number[];
|
||||||
@@ -55,12 +69,18 @@ export type ToChunkWorker =
|
|||||||
type: "sort";
|
type: "sort";
|
||||||
chunk_x: number;
|
chunk_x: number;
|
||||||
chunk_z: number;
|
chunk_z: number;
|
||||||
|
// the section's index in its chunk
|
||||||
|
index: number;
|
||||||
version: number;
|
version: number;
|
||||||
sort_version: number;
|
sort_version: number;
|
||||||
centers: Float32Array;
|
centers: Float32Array;
|
||||||
camera: number[];
|
camera: number[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// a section's light, a byte per block indexed like its blocks (see section_index): block light << 4 | sky light, like
|
||||||
|
// sodium's packed light data. one number when it's the same everywhere, like the open sky above the ground
|
||||||
|
export type SectionLight = number | Uint8Array<ArrayBuffer>;
|
||||||
|
|
||||||
// 4 vertices per quad, TERRAIN_VERTEX_BYTES each
|
// 4 vertices per quad, TERRAIN_VERTEX_BYTES each
|
||||||
export interface LayerMesh {
|
export interface LayerMesh {
|
||||||
vertices: Uint8Array<ArrayBuffer>;
|
vertices: Uint8Array<ArrayBuffer>;
|
||||||
@@ -69,13 +89,12 @@ export interface LayerMesh {
|
|||||||
groups?: FaceGroup[];
|
groups?: FaceGroup[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export type FromChunkWorker =
|
// a section the worker meshed
|
||||||
| {
|
export interface SectionMesh {
|
||||||
type: "meshed";
|
index: number;
|
||||||
chunk_x: number;
|
|
||||||
chunk_z: number;
|
|
||||||
version: number;
|
version: number;
|
||||||
// the lowest and highest y of the chunk's quads, for frustum culling
|
// the lowest and highest y of the section's quads and visuals in the world, for frustum culling. Infinity and
|
||||||
|
// -Infinity when it has none
|
||||||
min_y: number;
|
min_y: number;
|
||||||
max_y: number;
|
max_y: number;
|
||||||
solid: LayerMesh;
|
solid: LayerMesh;
|
||||||
@@ -88,17 +107,29 @@ export type FromChunkWorker =
|
|||||||
centers: Float32Array;
|
centers: Float32Array;
|
||||||
planes: [Float32Array, Float32Array, Float32Array];
|
planes: [Float32Array, Float32Array, Float32Array];
|
||||||
};
|
};
|
||||||
camera: number[];
|
// entities are lit from it
|
||||||
// the chunk's light, one byte per block indexed like its blocks: block light << 4 | sky light, like sodium's
|
light: SectionLight;
|
||||||
// packed light data. entities are lit from it
|
// which of its faces can be seen through from which others, see client/workers/visibility.ts
|
||||||
light: Uint8Array<ArrayBuffer>;
|
visibility: number;
|
||||||
// the blocks in it with visuals, as pairs of the block's index in the chunk (like light's) and its value
|
// the blocks in it with visuals, as pairs of the block's index in the section (see section_index) and its value
|
||||||
visuals: Uint32Array<ArrayBuffer>;
|
visuals: Uint32Array<ArrayBuffer>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type FromChunkWorker =
|
||||||
|
| {
|
||||||
|
type: "meshed";
|
||||||
|
chunk_x: number;
|
||||||
|
chunk_z: number;
|
||||||
|
// the sections asked for, in the same order
|
||||||
|
sections: SectionMesh[];
|
||||||
|
// what the translucent quads were sorted for
|
||||||
|
camera: number[];
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
type: "sorted";
|
type: "sorted";
|
||||||
chunk_x: number;
|
chunk_x: number;
|
||||||
chunk_z: number;
|
chunk_z: number;
|
||||||
|
index: number;
|
||||||
version: number;
|
version: number;
|
||||||
sort_version: number;
|
sort_version: number;
|
||||||
indices: Uint32Array;
|
indices: Uint32Array;
|
||||||
|
|||||||
+160
-81
@@ -8,26 +8,22 @@ import {
|
|||||||
block_light_opacity,
|
block_light_opacity,
|
||||||
type BlockRegistry,
|
type BlockRegistry,
|
||||||
type RenderLayer,
|
type RenderLayer,
|
||||||
} from "$/common/everything_registry.ts";
|
} from "@/common/everything_registry.ts";
|
||||||
import {
|
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK, type SpriteRegion, TEXTURE_SIZE } from "@/common/constants.ts";
|
||||||
AIR,
|
|
||||||
CHUNK_AREA,
|
|
||||||
CHUNK_HEIGHT,
|
|
||||||
CHUNK_SIZE,
|
|
||||||
ID_MASK,
|
|
||||||
type SpriteRegion,
|
|
||||||
TEXTURE_SIZE,
|
|
||||||
} from "$/common/constants.ts";
|
|
||||||
import type { Texture } from "../renderer/types.ts";
|
import type { Texture } from "../renderer/types.ts";
|
||||||
import {
|
import {
|
||||||
FACE_GROUPS,
|
FACE_GROUPS,
|
||||||
type FaceGroup,
|
type FaceGroup,
|
||||||
type FromChunkWorker,
|
type FromChunkWorker,
|
||||||
|
type SectionLight,
|
||||||
|
type SectionMesh,
|
||||||
TERRAIN_QUAD_BYTES,
|
TERRAIN_QUAD_BYTES,
|
||||||
TERRAIN_VERTEX_BYTES,
|
TERRAIN_VERTEX_BYTES,
|
||||||
type ToChunkWorker,
|
type ToChunkWorker,
|
||||||
UNALIGNED_GROUP,
|
UNALIGNED_GROUP,
|
||||||
} from "./chunk_messages.ts";
|
} from "./chunk_messages.ts";
|
||||||
|
import { BIOME_CELL_HEIGHT, Section, section_index, SECTION_VOLUME, type SectionBiomes } from "@/common/section.ts";
|
||||||
|
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||||
import {
|
import {
|
||||||
bake_block,
|
bake_block,
|
||||||
FACE_CORNERS,
|
FACE_CORNERS,
|
||||||
@@ -35,7 +31,7 @@ import {
|
|||||||
is_tinted,
|
is_tinted,
|
||||||
looks_by_state,
|
looks_by_state,
|
||||||
type ModelJson,
|
type ModelJson,
|
||||||
} from "$/common/block_models.ts";
|
} from "@/common/block_models.ts";
|
||||||
import {
|
import {
|
||||||
choose_sort_type,
|
choose_sort_type,
|
||||||
FACE_AXIS,
|
FACE_AXIS,
|
||||||
@@ -56,7 +52,8 @@ import {
|
|||||||
REGION_VOID,
|
REGION_VOID,
|
||||||
} from "./lighting.ts";
|
} from "./lighting.ts";
|
||||||
import { cell_index, fluid_quads, type FluidCell } from "./fluid_mesh.ts";
|
import { cell_index, fluid_quads, type FluidCell } from "./fluid_mesh.ts";
|
||||||
import { fluid_height, fluid_textures } from "$/common/everything_registry.ts";
|
import { ALL_VISIBLE, section_visibility } from "./visibility.ts";
|
||||||
|
import { fluid_height, fluid_textures } from "@/common/everything_registry.ts";
|
||||||
|
|
||||||
type TexturesInfo = Record<string, SpriteRegion>;
|
type TexturesInfo = Record<string, SpriteRegion>;
|
||||||
|
|
||||||
@@ -91,6 +88,8 @@ const block_layers = new Uint8Array(TABLE_SIZE);
|
|||||||
const block_cull_same = new Uint8Array(TABLE_SIZE);
|
const block_cull_same = new Uint8Array(TABLE_SIZE);
|
||||||
// darkens the corners it touches (minecraft's ambient occlusion), full cubes with collision do
|
// darkens the corners it touches (minecraft's ambient occlusion), full cubes with collision do
|
||||||
const block_occludes = new Uint8Array(TABLE_SIZE);
|
const block_occludes = new Uint8Array(TABLE_SIZE);
|
||||||
|
// blocks nothing can be seen through, drawn as whole opaque cubes, see visibility.ts
|
||||||
|
const block_hides_view = new Uint8Array(TABLE_SIZE);
|
||||||
// light can come around a corner past it
|
// light can come around a corner past it
|
||||||
const block_lets_light_by = new Uint8Array(TABLE_SIZE);
|
const block_lets_light_by = new Uint8Array(TABLE_SIZE);
|
||||||
const light_tables: LightTables = { opacity: new Uint8Array(TABLE_SIZE), emission: new Uint8Array(TABLE_SIZE) };
|
const light_tables: LightTables = { opacity: new Uint8Array(TABLE_SIZE), emission: new Uint8Array(TABLE_SIZE) };
|
||||||
@@ -104,7 +103,10 @@ const waterlogged_shift = new Uint8Array(TABLE_SIZE);
|
|||||||
const block_visual = new Uint8Array(TABLE_SIZE);
|
const block_visual = new Uint8Array(TABLE_SIZE);
|
||||||
const HAS_VISUAL = 1;
|
const HAS_VISUAL = 1;
|
||||||
const REPLACED_MODEL = 2;
|
const REPLACED_MODEL = 2;
|
||||||
const region = new LightRegion();
|
// the sections being meshed and the ones around them, made for the dimension's height by "init"
|
||||||
|
let region: LightRegion;
|
||||||
|
// the dimension's min_y, which quads are moved up by to be where they are in the world
|
||||||
|
let world_min_y = 0;
|
||||||
|
|
||||||
// a model's quad ready for the mesher: uvs in the atlas, and for each corner how much of each of the face's
|
// a model's quad ready for the mesher: uvs in the atlas, and for each corner how much of each of the face's
|
||||||
// four corner lights it gets, so faces smaller than the block are lit like minecraft's
|
// four corner lights it gets, so faces smaller than the block are lit like minecraft's
|
||||||
@@ -142,38 +144,43 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
|||||||
block_visual.fill(0);
|
block_visual.fill(0);
|
||||||
for (const [nid, replaces_model] of message.visuals) {
|
for (const [nid, replaces_model] of message.visuals) {
|
||||||
block_visual[nid] = replaces_model ? REPLACED_MODEL : HAS_VISUAL;
|
block_visual[nid] = replaces_model ? REPLACED_MODEL : HAS_VISUAL;
|
||||||
|
if (replaces_model) block_hides_view[nid] = 0;
|
||||||
}
|
}
|
||||||
textures_info = message.textures_info;
|
textures_info = message.textures_info;
|
||||||
image = message.image as Texture;
|
image = message.image as Texture;
|
||||||
|
region = new LightRegion(message.shape);
|
||||||
|
world_min_y = message.shape.min_y;
|
||||||
break;
|
break;
|
||||||
case "mesh": {
|
case "mesh": {
|
||||||
region.fill(message.chunks);
|
const chunks = message.chunks.map((data) => data?.map((section) => new Section(section)) ?? null);
|
||||||
|
// the region's bottom in the world
|
||||||
|
const bottom = world_min_y + message.first * SECTION_HEIGHT;
|
||||||
|
region.fill(chunks, message.sky, bottom);
|
||||||
region.compute(light_tables);
|
region.compute(light_tables);
|
||||||
blend_biome_colors(message.biome_colors);
|
biomes = message.biomes;
|
||||||
const { solid, cutout, translucent, min_y, max_y, visuals } = make_chunk_mesh(
|
biome_colors = message.biome_colors;
|
||||||
message.chunk_x,
|
blended_any = false;
|
||||||
message.chunk_z,
|
const sections: SectionMesh[] = message.sections.map(({ index, version }) => {
|
||||||
message.chunks,
|
// the section's bottom in the region
|
||||||
message.camera,
|
const from = (index - message.first) * SECTION_HEIGHT;
|
||||||
);
|
return {
|
||||||
const light = chunk_light();
|
index,
|
||||||
|
version,
|
||||||
|
...make_section_mesh(message.chunk_x, message.chunk_z, chunks, from, bottom, message.camera),
|
||||||
|
light: section_light(from),
|
||||||
|
visibility: visibility(chunks[4]![from >> 4], from),
|
||||||
|
};
|
||||||
|
});
|
||||||
post(
|
post(
|
||||||
{
|
{
|
||||||
type: "meshed",
|
type: "meshed",
|
||||||
chunk_x: message.chunk_x,
|
chunk_x: message.chunk_x,
|
||||||
chunk_z: message.chunk_z,
|
chunk_z: message.chunk_z,
|
||||||
version: message.version,
|
sections,
|
||||||
min_y,
|
|
||||||
max_y,
|
|
||||||
solid,
|
|
||||||
cutout,
|
|
||||||
translucent,
|
|
||||||
camera: message.camera,
|
camera: message.camera,
|
||||||
light,
|
|
||||||
visuals,
|
|
||||||
},
|
},
|
||||||
[
|
sections.flatMap(({ light, visuals, solid, cutout, translucent }) => [
|
||||||
light.buffer,
|
...typeof light === "number" ? [] : [light.buffer],
|
||||||
visuals.buffer,
|
visuals.buffer,
|
||||||
solid.vertices.buffer,
|
solid.vertices.buffer,
|
||||||
cutout.vertices.buffer,
|
cutout.vertices.buffer,
|
||||||
@@ -181,7 +188,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
|||||||
translucent.indices.buffer,
|
translucent.indices.buffer,
|
||||||
translucent.centers.buffer,
|
translucent.centers.buffer,
|
||||||
...translucent.planes.map((planes) => planes.buffer),
|
...translucent.planes.map((planes) => planes.buffer),
|
||||||
],
|
]),
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -192,6 +199,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
|||||||
type: "sorted",
|
type: "sorted",
|
||||||
chunk_x: message.chunk_x,
|
chunk_x: message.chunk_x,
|
||||||
chunk_z: message.chunk_z,
|
chunk_z: message.chunk_z,
|
||||||
|
index: message.index,
|
||||||
version: message.version,
|
version: message.version,
|
||||||
sort_version: message.sort_version,
|
sort_version: message.sort_version,
|
||||||
indices,
|
indices,
|
||||||
@@ -201,37 +209,83 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// the middle chunk of the light region, packed for the main thread, see "meshed"
|
// the light of the middle chunk's section from this y in the region, packed for the main thread, see SectionLight
|
||||||
function chunk_light() {
|
const packed_light = new Uint8Array(SECTION_VOLUME);
|
||||||
const light = new Uint8Array(CHUNK_AREA * CHUNK_HEIGHT);
|
|
||||||
for (let y = 0; y < CHUNK_HEIGHT; y++) {
|
function section_light(from: number): SectionLight {
|
||||||
|
let same = true;
|
||||||
|
for (let y = 0; y < SECTION_HEIGHT; y++) {
|
||||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||||
const from = y * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
|
const at = (from + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
|
||||||
const to = y * CHUNK_AREA + z * CHUNK_SIZE;
|
const to = (y << 8) | (z << 4);
|
||||||
for (let x = 0; x < CHUNK_SIZE; x++) {
|
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||||
light[to + x] = (region.block_light[from + x] << 4) | region.sky[from + x];
|
const light = (region.block_light[at + x] << 4) | region.sky[at + x];
|
||||||
|
packed_light[to + x] = light;
|
||||||
|
if (light !== packed_light[0]) same = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return light;
|
return same ? packed_light[0] : packed_light.slice();
|
||||||
|
}
|
||||||
|
|
||||||
|
const open_rows = new Uint16Array(256);
|
||||||
|
|
||||||
|
// which faces of the section see each other, see visibility.ts. from is its bottom in the region
|
||||||
|
function visibility(section: Section, from: number) {
|
||||||
|
if (!section.blocks) return block_hides_view[section.value & ID_MASK] ? 0 : ALL_VISIBLE;
|
||||||
|
for (let y = 0; y < SECTION_HEIGHT; y++) {
|
||||||
|
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||||
|
// the middle chunk of the region
|
||||||
|
const row = (from + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
|
||||||
|
let open = 0;
|
||||||
|
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||||
|
if (!block_hides_view[region.blocks[row + x]]) open |= 1 << x;
|
||||||
|
}
|
||||||
|
open_rows[y << 4 | z] = open;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return section_visibility(open_rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
function post(message: FromChunkWorker, transfer: Transferable[]) {
|
function post(message: FromChunkWorker, transfer: Transferable[]) {
|
||||||
self.postMessage(message, transfer);
|
self.postMessage(message, transfer);
|
||||||
}
|
}
|
||||||
|
|
||||||
// like minecraft's biome blend at its default radius: each column's grass, foliage and water color is the average of the 5x5
|
// like minecraft's biome blend at its default radius: each column's grass, foliage and water color is the average of
|
||||||
// columns around it, so biome edges fade instead of being a line. neighbors that aren't there are left out
|
// the 5x5 columns around it at the same height, so biome edges fade instead of being a line. neighbors that aren't
|
||||||
|
// there are left out. colors aren't blended up and down
|
||||||
const BLEND_RADIUS = 2;
|
const BLEND_RADIUS = 2;
|
||||||
// the middle chunk's blended colors, x then z, grass then foliage then water
|
// the 3x3 chunks' biome cells and colors of the request being meshed, see "mesh"
|
||||||
|
let biomes: (SectionBiomes[] | null)[] = [];
|
||||||
|
let biome_colors: (Uint32Array | null)[] = [];
|
||||||
|
// the middle chunk's blended colors at a layer of cells, x then z, grass then foliage then water
|
||||||
const blended = new Uint32Array(CHUNK_AREA * 3);
|
const blended = new Uint32Array(CHUNK_AREA * 3);
|
||||||
|
// the 3x3 chunks' biome palette index of each column at that layer, so a layer with the same biomes as the last one
|
||||||
|
// blended isn't blended again, unless none has been for this request
|
||||||
|
const blended_cells = new Uint8Array(9 * CHUNK_AREA);
|
||||||
|
let blended_any = false;
|
||||||
|
const layer_cells = new Uint8Array(9 * CHUNK_AREA);
|
||||||
// what MeshQuad.tint is for the biome's colors, they aren't colors since those only go up to 0xffffff
|
// what MeshQuad.tint is for the biome's colors, they aren't colors since those only go up to 0xffffff
|
||||||
const GRASS = -1;
|
const GRASS = -1;
|
||||||
const FOLIAGE = -2;
|
const FOLIAGE = -2;
|
||||||
const WATER = -3;
|
const WATER = -3;
|
||||||
|
|
||||||
function blend_biome_colors(colors: (Uint32Array | null)[]) {
|
// blends the colors of the layer of biome cells y is in, in the region's section from (see "mesh")
|
||||||
for (const offset of [0, CHUNK_AREA, CHUNK_AREA * 2]) {
|
function blend_biome_colors(from: number, y: number) {
|
||||||
|
const layer = ((y & 15) >> 2) << 8;
|
||||||
|
for (let i = 0; i < 9; i++) {
|
||||||
|
const cells = biomes[i]?.[from >> 4];
|
||||||
|
if (cells === undefined) continue;
|
||||||
|
if (typeof cells === "number") layer_cells.fill(cells, i * CHUNK_AREA, (i + 1) * CHUNK_AREA);
|
||||||
|
else layer_cells.set(cells.subarray(layer, layer + CHUNK_AREA), i * CHUNK_AREA);
|
||||||
|
}
|
||||||
|
let same = blended_any;
|
||||||
|
for (let i = 0; i < layer_cells.length && same; i++) same = layer_cells[i] === blended_cells[i];
|
||||||
|
if (same) return;
|
||||||
|
blended_cells.set(layer_cells);
|
||||||
|
blended_any = true;
|
||||||
|
|
||||||
|
for (let part = 0; part < 3; part++) {
|
||||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||||
for (let x = 0; x < CHUNK_SIZE; x++) {
|
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||||
let r = 0;
|
let r = 0;
|
||||||
@@ -243,9 +297,12 @@ function blend_biome_colors(colors: (Uint32Array | null)[]) {
|
|||||||
// which of the 3x3 chunks, and where in it
|
// which of the 3x3 chunks, and where in it
|
||||||
const sx = x + dx + CHUNK_SIZE;
|
const sx = x + dx + CHUNK_SIZE;
|
||||||
const sz = z + dz + CHUNK_SIZE;
|
const sz = z + dz + CHUNK_SIZE;
|
||||||
const chunk = colors[Math.floor(sz / CHUNK_SIZE) * 3 + Math.floor(sx / CHUNK_SIZE)];
|
const chunk = Math.floor(sz / CHUNK_SIZE) * 3 + Math.floor(sx / CHUNK_SIZE);
|
||||||
if (!chunk) continue;
|
const colors = biome_colors[chunk];
|
||||||
const color = chunk[offset + (sz % CHUNK_SIZE) * CHUNK_SIZE + (sx % CHUNK_SIZE)];
|
if (!colors || !biomes[chunk]) continue;
|
||||||
|
const cell =
|
||||||
|
layer_cells[chunk * CHUNK_AREA + (sz % CHUNK_SIZE) * CHUNK_SIZE + (sx % CHUNK_SIZE)];
|
||||||
|
const color = colors[cell * 3 + part];
|
||||||
r += color >> 16;
|
r += color >> 16;
|
||||||
g += (color >> 8) & 0xff;
|
g += (color >> 8) & 0xff;
|
||||||
b += color & 0xff;
|
b += color & 0xff;
|
||||||
@@ -255,7 +312,7 @@ function blend_biome_colors(colors: (Uint32Array | null)[]) {
|
|||||||
const color = count === 0
|
const color = count === 0
|
||||||
? 0xffffff
|
? 0xffffff
|
||||||
: (Math.round(r / count) << 16) | (Math.round(g / count) << 8) | Math.round(b / count);
|
: (Math.round(r / count) << 16) | (Math.round(g / count) << 8) | Math.round(b / count);
|
||||||
blended[offset + z * CHUNK_SIZE + x] = color;
|
blended[part * CHUNK_AREA + z * CHUNK_SIZE + x] = color;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -283,6 +340,7 @@ function build_block_tables() {
|
|||||||
block_layers[nid] = layer;
|
block_layers[nid] = layer;
|
||||||
block_cull_same[nid] = (block.cull_same ?? layer === TRANSLUCENT) ? 1 : 0;
|
block_cull_same[nid] = (block.cull_same ?? layer === TRANSLUCENT) ? 1 : 0;
|
||||||
block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT && is_full_cube(block) ? 1 : 0;
|
block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT && is_full_cube(block) ? 1 : 0;
|
||||||
|
block_hides_view[nid] = layer === SOLID && is_full_cube(block) ? 1 : 0;
|
||||||
block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0;
|
block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0;
|
||||||
light_tables.opacity[nid] = opacity;
|
light_tables.opacity[nid] = opacity;
|
||||||
light_tables.emission[nid] = block_light_emission(block);
|
light_tables.emission[nid] = block_light_emission(block);
|
||||||
@@ -543,14 +601,14 @@ function hides_fluid(nid: number) {
|
|||||||
return nid !== AIR && block_layers[nid] === SOLID;
|
return nid !== AIR && block_layers[nid] === SOLID;
|
||||||
}
|
}
|
||||||
|
|
||||||
// a cell's block with its states, from the 3x3 chunks the region was filled from. 0 (air) above the world and for
|
// a cell's block with its states, from the 3x3 chunks' sections the region was filled from. 0 (air) outside them and
|
||||||
// chunks that aren't there
|
// for chunks that aren't there
|
||||||
function region_value(chunks: (Uint32Array | null)[], index: number, y: number) {
|
function region_value(chunks: (Section[] | null)[], index: number, y: number) {
|
||||||
if (y < 0 || y >= CHUNK_HEIGHT) return AIR;
|
if (y < 0 || y >= region.height) return AIR;
|
||||||
const x = index % REGION_SIZE;
|
const x = index % REGION_SIZE;
|
||||||
const z = Math.floor(index / REGION_SIZE) % REGION_SIZE;
|
const z = Math.floor(index / REGION_SIZE) % REGION_SIZE;
|
||||||
const chunk = chunks[Math.floor(z / CHUNK_SIZE) * 3 + Math.floor(x / CHUNK_SIZE)];
|
const chunk = chunks[Math.floor(z / CHUNK_SIZE) * 3 + Math.floor(x / CHUNK_SIZE)];
|
||||||
return chunk ? chunk[y * CHUNK_AREA + (z % CHUNK_SIZE) * CHUNK_SIZE + (x % CHUNK_SIZE)] : AIR;
|
return chunk ? chunk[y >> 4].get(section_index(x, y, z)) : AIR;
|
||||||
}
|
}
|
||||||
|
|
||||||
// the surface of the fluid with this numeric id in a cell, if the cell is that fluid
|
// the surface of the fluid with this numeric id in a cell, if the cell is that fluid
|
||||||
@@ -565,7 +623,7 @@ const fluid_cells: FluidCell[] = Array.from(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// the numeric id of the fluid in a cell: the block, or what it's waterlogged with. 0 for none
|
// the numeric id of the fluid in a cell: the block, or what it's waterlogged with. 0 for none
|
||||||
function cell_fluid(chunks: (Uint32Array | null)[], index: number, y: number) {
|
function cell_fluid(chunks: (Section[] | null)[], index: number, y: number) {
|
||||||
const id = region_block(region, index, y);
|
const id = region_block(region, index, y);
|
||||||
if (fluid_range[id]) return id;
|
if (fluid_range[id]) return id;
|
||||||
const fluid = waterlog_fluid[id];
|
const fluid = waterlog_fluid[id];
|
||||||
@@ -574,7 +632,7 @@ function cell_fluid(chunks: (Uint32Array | null)[], index: number, y: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// the 3x3 cells around the fluid at index and y, see FluidCell. a waterlogged block is a source of its fluid
|
// the 3x3 cells around the fluid at index and y, see FluidCell. a waterlogged block is a source of its fluid
|
||||||
function fill_fluid_cells(chunks: (Uint32Array | null)[], nid: number, index: number, y: number) {
|
function fill_fluid_cells(chunks: (Section[] | null)[], nid: number, index: number, y: number) {
|
||||||
for (let dz = -1; dz <= 1; dz++) {
|
for (let dz = -1; dz <= 1; dz++) {
|
||||||
for (let dx = -1; dx <= 1; dx++) {
|
for (let dx = -1; dx <= 1; dx++) {
|
||||||
const cell = fluid_cells[cell_index(dx, dz)];
|
const cell = fluid_cells[cell_index(dx, dz)];
|
||||||
@@ -639,22 +697,39 @@ function underside(top: MeshQuad): MeshQuad {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// region has to be filled and lit first
|
// quads being built, kept from one section to the next. solid and cutout get a buffer per face group, translucent one
|
||||||
// chunks are the 3x3 chunks' blocks with their states, the middle one's for models that change with them and the
|
// for everything since it's sorted instead
|
||||||
// ones around it for fluids, whose surface follows their neighbors'
|
const opaque = [SOLID, CUTOUT].map(() =>
|
||||||
function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array | null)[], camera: number[]) {
|
|
||||||
const values = chunks[4]!;
|
|
||||||
// solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead
|
|
||||||
const opaque = [SOLID, CUTOUT].map(() =>
|
|
||||||
Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity }))
|
Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity }))
|
||||||
);
|
);
|
||||||
const translucent_quads = new QuadBuffer();
|
const translucent_quads = new QuadBuffer();
|
||||||
|
// for sorting the translucent quads
|
||||||
|
let centers = new Float32Array(256);
|
||||||
|
let faces = new Uint8Array(256);
|
||||||
|
|
||||||
|
// the middle chunk's section from y from in the region, which has to be filled and lit first. bottom is the region's
|
||||||
|
// bottom in the world. chunks are the region's sections with their blocks' states, the middle one's for models that
|
||||||
|
// change with them and the ones around it for fluids, whose surface follows their neighbors'
|
||||||
|
function make_section_mesh(
|
||||||
|
chunk_x: number,
|
||||||
|
chunk_z: number,
|
||||||
|
chunks: (Section[] | null)[],
|
||||||
|
from: number,
|
||||||
|
bottom: number,
|
||||||
|
camera: number[],
|
||||||
|
) {
|
||||||
|
const section = chunks[4]![from >> 4];
|
||||||
|
for (const groups of opaque) {
|
||||||
|
for (const group of groups) {
|
||||||
|
group.buffer.count = 0;
|
||||||
|
group.min = Infinity;
|
||||||
|
group.max = -Infinity;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
translucent_quads.count = 0;
|
||||||
mesh_min_y = Infinity;
|
mesh_min_y = Infinity;
|
||||||
mesh_max_y = -Infinity;
|
mesh_max_y = -Infinity;
|
||||||
// for sorting the translucent quads
|
// the blocks with visuals, see SectionMesh
|
||||||
let centers = new Float32Array(256);
|
|
||||||
let faces = new Uint8Array(256);
|
|
||||||
// the blocks with visuals, see "meshed"
|
|
||||||
const visuals: number[] = [];
|
const visuals: number[] = [];
|
||||||
|
|
||||||
// where the neighbor on each face is, same order as FACE_NORMALS
|
// where the neighbor on each face is, same order as FACE_NORMALS
|
||||||
@@ -663,6 +738,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
|||||||
// adds a lit quad of the block at x y z in the chunk to its layer
|
// adds a lit quad of the block at x y z in the chunk to its layer
|
||||||
const emit = (quad: MeshQuad, layer_id: number, x: number, y: number, z: number, alpha: number) => {
|
const emit = (quad: MeshQuad, layer_id: number, x: number, y: number, z: number, alpha: number) => {
|
||||||
const wx = chunk_x * CHUNK_SIZE + x;
|
const wx = chunk_x * CHUNK_SIZE + x;
|
||||||
|
const wy = bottom + y;
|
||||||
const wz = chunk_z * CHUNK_SIZE + z;
|
const wz = chunk_z * CHUNK_SIZE + z;
|
||||||
const tint = quad.tint === GRASS
|
const tint = quad.tint === GRASS
|
||||||
? blended[z * CHUNK_SIZE + x]
|
? blended[z * CHUNK_SIZE + x]
|
||||||
@@ -674,28 +750,31 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
|||||||
|
|
||||||
if (layer_id !== TRANSLUCENT) {
|
if (layer_id !== TRANSLUCENT) {
|
||||||
const group = opaque[layer_id][quad.group];
|
const group = opaque[layer_id][quad.group];
|
||||||
push_quad(group.buffer, quad, wx, y, wz, alpha, tint);
|
push_quad(group.buffer, quad, wx, wy, wz, alpha, tint);
|
||||||
if (quad.group !== UNALIGNED_GROUP) {
|
if (quad.group !== UNALIGNED_GROUP) {
|
||||||
const axis = FACE_AXIS[quad.face];
|
const axis = FACE_AXIS[quad.face];
|
||||||
const plane = (axis === 0 ? wx : axis === 1 ? y : wz) + quad.positions[axis];
|
const plane = (axis === 0 ? wx : axis === 1 ? wy : wz) + quad.positions[axis];
|
||||||
if (plane < group.min) group.min = plane;
|
if (plane < group.min) group.min = plane;
|
||||||
if (plane > group.max) group.max = plane;
|
if (plane > group.max) group.max = plane;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
push_quad(translucent_quads, quad, wx, y, wz, alpha, tint);
|
push_quad(translucent_quads, quad, wx, wy, wz, alpha, tint);
|
||||||
// sorting treats every quad as facing along an axis, rotated ones too
|
// sorting treats every quad as facing along an axis, rotated ones too
|
||||||
const q = translucent_quads.count - 1;
|
const q = translucent_quads.count - 1;
|
||||||
centers = ensure_capacity(centers, (q + 1) * 3);
|
centers = ensure_capacity(centers, (q + 1) * 3);
|
||||||
faces = ensure_capacity(faces, q + 1);
|
faces = ensure_capacity(faces, q + 1);
|
||||||
const p = quad.positions;
|
const p = quad.positions;
|
||||||
centers[q * 3] = wx + (p[0] + p[6]) / 2;
|
centers[q * 3] = wx + (p[0] + p[6]) / 2;
|
||||||
centers[q * 3 + 1] = y + (p[1] + p[7]) / 2;
|
centers[q * 3 + 1] = wy + (p[1] + p[7]) / 2;
|
||||||
centers[q * 3 + 2] = wz + (p[2] + p[8]) / 2;
|
centers[q * 3 + 2] = wz + (p[2] + p[8]) / 2;
|
||||||
faces[q] = quad.face;
|
faces[q] = quad.face;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
for (let y = 0; y < CHUNK_HEIGHT; y++) {
|
// nothing to mesh in a section of air
|
||||||
|
const air = section.blocks === null && section.value === AIR;
|
||||||
|
for (let y = from; y < from + SECTION_HEIGHT && !air; y++) {
|
||||||
|
if (y % BIOME_CELL_HEIGHT === 0) blend_biome_colors(from, y);
|
||||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||||
for (let x = 0; x < CHUNK_SIZE; x++) {
|
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||||
// the middle chunk of the region
|
// the middle chunk of the region
|
||||||
@@ -739,12 +818,12 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
|||||||
if (fluid_nid === block_nid) continue;
|
if (fluid_nid === block_nid) continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const value = values[y * CHUNK_AREA + z * CHUNK_SIZE + x];
|
const value = section.get(section_index(x, y, z));
|
||||||
if (block_visual[block_nid]) {
|
if (block_visual[block_nid]) {
|
||||||
visuals.push(y * CHUNK_AREA + z * CHUNK_SIZE + x, value);
|
visuals.push(section_index(x, y, z), value);
|
||||||
// with the block above and below, since a visual can reach past its block, like a large cog
|
// with the block above and below, since a visual can reach past its block, like a large cog
|
||||||
if (y - 1 < mesh_min_y) mesh_min_y = y - 1;
|
if (bottom + y - 1 < mesh_min_y) mesh_min_y = bottom + y - 1;
|
||||||
if (y + 2 > mesh_max_y) mesh_max_y = y + 2;
|
if (bottom + y + 2 > mesh_max_y) mesh_max_y = bottom + y + 2;
|
||||||
if (block_visual[block_nid] === REPLACED_MODEL) continue;
|
if (block_visual[block_nid] === REPLACED_MODEL) continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -788,8 +867,8 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
|
|||||||
const [camera_x, camera_y, camera_z] = camera;
|
const [camera_x, camera_y, camera_z] = camera;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
min_y: mesh_min_y === Infinity ? 0 : mesh_min_y,
|
min_y: mesh_min_y,
|
||||||
max_y: mesh_max_y === -Infinity ? 0 : mesh_max_y,
|
max_y: mesh_max_y,
|
||||||
solid,
|
solid,
|
||||||
cutout,
|
cutout,
|
||||||
translucent: {
|
translucent: {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// fluids drawn like luanti's flowing fluids (MapblockMeshGenerator::drawLiquidNode in its content_mapblock.cpp): each
|
// fluids drawn like luanti's flowing fluids (MapblockMeshGenerator::drawLiquidNode in its content_mapblock.cpp): each
|
||||||
// corner of the surface is as high as the fluid around it, so it slopes down where it flows away from a source. the
|
// corner of the surface is as high as the fluid around it, so it slopes down where it flows away from a source. the
|
||||||
// sides between two cells of it are left out, except where it pours down past the surface of the one beside it
|
// sides between two cells of it are left out, except where it pours down past the surface of the one beside it
|
||||||
import { FACE_CORNERS } from "$/common/block_models.ts";
|
import { FACE_CORNERS } from "@/common/block_models.ts";
|
||||||
|
|
||||||
// one of the 3x3 cells around a fluid and level with it, and the cell above that one
|
// one of the 3x3 cells around a fluid and level with it, and the cell above that one
|
||||||
export interface FluidCell {
|
export interface FluidCell {
|
||||||
|
|||||||
+58
-32
@@ -6,15 +6,21 @@
|
|||||||
// something that isn't fully clear, block light starts at blocks that give off light. both spread to
|
// something that isn't fully clear, block light starts at blocks that give off light. both spread to
|
||||||
// neighbors losing max(1, the neighbor's opacity) per step.
|
// neighbors losing max(1, the neighbor's opacity) per step.
|
||||||
//
|
//
|
||||||
// minecraft stores light and updates it as blocks change. here it's worked out from scratch for the
|
// minecraft stores light and updates it as blocks change. here it's worked out from scratch around the sections being
|
||||||
// 3x3 chunks around the chunk being meshed, which gives the same result: light reaches at most 15
|
// meshed: the 3x3 chunks around theirs, from the section below them to the one above. that gives the same result, since
|
||||||
// blocks, so nothing outside those chunks can light the middle one or its border
|
// light reaches at most 15 blocks, so nothing outside can light them or their border. the only light that comes from
|
||||||
|
// further is the sky's straight down, which starts where each column's sky height says (see column_heights in
|
||||||
|
// common/section.ts) instead of being followed down from the top.
|
||||||
|
//
|
||||||
|
// y in a region counts from its bottom, which is a section's. in a dimension without sky light there's only block
|
||||||
|
// light
|
||||||
|
|
||||||
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
|
import { AIR, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||||
|
import type { Section } from "@/common/section.ts";
|
||||||
|
import { SECTION_HEIGHT, type WorldShapeJson } from "@/common/world_shape.ts";
|
||||||
|
|
||||||
export const REGION_SIZE = CHUNK_SIZE * 3;
|
export const REGION_SIZE = CHUNK_SIZE * 3;
|
||||||
export const REGION_LAYER = REGION_SIZE * REGION_SIZE;
|
export const REGION_LAYER = REGION_SIZE * REGION_SIZE;
|
||||||
export const REGION_VOLUME = REGION_LAYER * CHUNK_HEIGHT;
|
|
||||||
// what unloaded chunks and the space below the world are made of: opaque, dark, never shown
|
// what unloaded chunks and the space below the world are made of: opaque, dark, never shown
|
||||||
export const REGION_VOID = ID_MASK;
|
export const REGION_VOID = ID_MASK;
|
||||||
|
|
||||||
@@ -25,31 +31,53 @@ export interface LightTables {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class LightRegion {
|
export class LightRegion {
|
||||||
|
// in blocks, of the sections last filled in
|
||||||
|
height = 0;
|
||||||
|
readonly sky_light: boolean;
|
||||||
// block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x
|
// block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x
|
||||||
blocks = new Uint16Array(REGION_VOLUME);
|
blocks: Uint16Array;
|
||||||
sky = new Uint8Array(REGION_VOLUME);
|
sky: Uint8Array;
|
||||||
block_light = new Uint8Array(REGION_VOLUME);
|
block_light: Uint8Array;
|
||||||
|
|
||||||
// the lowest y that still sees the sky, per column
|
// the lowest y that still sees the sky, per column. the region's height when that's above it
|
||||||
#heights = new Int32Array(REGION_LAYER);
|
#heights = new Int32Array(REGION_LAYER);
|
||||||
#queue = new Int32Array(1 << 18);
|
#queue = new Int32Array(1 << 18);
|
||||||
#queue_length = 0;
|
#queue_length = 0;
|
||||||
|
|
||||||
// the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing ones are void
|
// room for the dimension's whole height
|
||||||
fill(chunks: (Uint32Array | null)[]) {
|
constructor(shape: WorldShapeJson) {
|
||||||
|
this.sky_light = shape.sky_light;
|
||||||
|
const volume = REGION_LAYER * (shape.max_y - shape.min_y);
|
||||||
|
this.blocks = new Uint16Array(volume);
|
||||||
|
this.sky = new Uint8Array(volume);
|
||||||
|
this.block_light = new Uint8Array(volume);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the same sections of the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing
|
||||||
|
// chunks are void. sky is each chunk's sky height by column (see column_heights), and bottom the y of the region's
|
||||||
|
// bottom in the world
|
||||||
|
fill(chunks: (Section[] | null)[], sky: (ArrayLike<number> | null)[], bottom: number) {
|
||||||
|
this.height = chunks[4]!.length * SECTION_HEIGHT;
|
||||||
for (let i = 0; i < 9; i++) {
|
for (let i = 0; i < 9; i++) {
|
||||||
const source = chunks[i];
|
const source = chunks[i];
|
||||||
const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE;
|
const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE;
|
||||||
for (let y = 0; y < CHUNK_HEIGHT; y++) {
|
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||||
|
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||||
|
const height = sky[i] ? sky[i]![z * CHUNK_SIZE + x] - bottom : this.height;
|
||||||
|
this.#heights[origin + z * REGION_SIZE + x] = Math.min(Math.max(height, 0), this.height);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let y = 0; y < this.height; y++) {
|
||||||
|
const section = source?.[y >> 4];
|
||||||
for (let z = 0; z < CHUNK_SIZE; z++) {
|
for (let z = 0; z < CHUNK_SIZE; z++) {
|
||||||
const to = y * REGION_LAYER + origin + z * REGION_SIZE;
|
const to = y * REGION_LAYER + origin + z * REGION_SIZE;
|
||||||
if (!source) {
|
if (!section?.blocks) {
|
||||||
this.blocks.fill(REGION_VOID, to, to + CHUNK_SIZE);
|
this.blocks.fill(section ? section.value & ID_MASK : REGION_VOID, to, to + CHUNK_SIZE);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const from = y * CHUNK_AREA + z * CHUNK_SIZE;
|
const from = ((y & 15) << 8) | (z << 4);
|
||||||
for (let x = 0; x < CHUNK_SIZE; x++) {
|
for (let x = 0; x < CHUNK_SIZE; x++) {
|
||||||
this.blocks[to + x] = source[from + x] & ID_MASK;
|
this.blocks[to + x] = section.blocks[from + x] & ID_MASK;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -62,18 +90,14 @@ export class LightRegion {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#compute_sky({ opacity }: LightTables) {
|
#compute_sky({ opacity }: LightTables) {
|
||||||
const { blocks, sky } = this;
|
const { sky, height: region_height } = this;
|
||||||
sky.fill(0);
|
sky.fill(0, 0, REGION_LAYER * region_height);
|
||||||
this.#queue_length = 0;
|
this.#queue_length = 0;
|
||||||
|
if (!this.sky_light) return;
|
||||||
|
|
||||||
// straight down from the top, until something isn't fully clear
|
// straight down from the top, to the sky height
|
||||||
for (let column = 0; column < REGION_LAYER; column++) {
|
for (let column = 0; column < REGION_LAYER; column++) {
|
||||||
let y = CHUNK_HEIGHT - 1;
|
for (let y = this.#heights[column]; y < region_height; y++) sky[y * REGION_LAYER + column] = 15;
|
||||||
while (y >= 0 && opacity[blocks[y * REGION_LAYER + column]] === 0) {
|
|
||||||
sky[y * REGION_LAYER + column] = 15;
|
|
||||||
y--;
|
|
||||||
}
|
|
||||||
this.#heights[column] = y + 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// only the lit cells next to a darker one can spread: the bottom of each column's sunlight,
|
// only the lit cells next to a darker one can spread: the bottom of each column's sunlight,
|
||||||
@@ -89,7 +113,7 @@ export class LightRegion {
|
|||||||
if (z < REGION_SIZE - 1) {
|
if (z < REGION_SIZE - 1) {
|
||||||
highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]);
|
highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]);
|
||||||
}
|
}
|
||||||
const top = Math.min(CHUNK_HEIGHT - 1, Math.max(height, highest_neighbor - 1));
|
const top = Math.min(region_height - 1, Math.max(height, highest_neighbor - 1));
|
||||||
for (let y = height; y <= top; y++) {
|
for (let y = height; y <= top; y++) {
|
||||||
this.#push(y * REGION_LAYER + column);
|
this.#push(y * REGION_LAYER + column);
|
||||||
}
|
}
|
||||||
@@ -101,10 +125,11 @@ export class LightRegion {
|
|||||||
|
|
||||||
#compute_block_light({ opacity, emission }: LightTables) {
|
#compute_block_light({ opacity, emission }: LightTables) {
|
||||||
const { blocks, block_light } = this;
|
const { blocks, block_light } = this;
|
||||||
block_light.fill(0);
|
const volume = REGION_LAYER * this.height;
|
||||||
|
block_light.fill(0, 0, volume);
|
||||||
this.#queue_length = 0;
|
this.#queue_length = 0;
|
||||||
|
|
||||||
for (let i = 0; i < REGION_VOLUME; i++) {
|
for (let i = 0; i < volume; i++) {
|
||||||
const level = emission[blocks[i]];
|
const level = emission[blocks[i]];
|
||||||
if (level > 0) {
|
if (level > 0) {
|
||||||
block_light[i] = level;
|
block_light[i] = level;
|
||||||
@@ -127,6 +152,7 @@ export class LightRegion {
|
|||||||
// breadth first from everything queued. a cell can be queued again when a brighter path reaches it
|
// breadth first from everything queued. a cell can be queued again when a brighter path reaches it
|
||||||
#propagate(light: Uint8Array, opacity: Uint8Array, is_sky: boolean) {
|
#propagate(light: Uint8Array, opacity: Uint8Array, is_sky: boolean) {
|
||||||
const blocks = this.blocks;
|
const blocks = this.blocks;
|
||||||
|
const top = this.height - 1;
|
||||||
|
|
||||||
const spread = (to: number, level: number, down: boolean) => {
|
const spread = (to: number, level: number, down: boolean) => {
|
||||||
const block_opacity = opacity[blocks[to]];
|
const block_opacity = opacity[blocks[to]];
|
||||||
@@ -150,7 +176,7 @@ export class LightRegion {
|
|||||||
const x = rest - z * REGION_SIZE;
|
const x = rest - z * REGION_SIZE;
|
||||||
|
|
||||||
if (y > 0) spread(index - REGION_LAYER, level, true);
|
if (y > 0) spread(index - REGION_LAYER, level, true);
|
||||||
if (y < CHUNK_HEIGHT - 1) spread(index + REGION_LAYER, level, false);
|
if (y < top) spread(index + REGION_LAYER, level, false);
|
||||||
if (x > 0) spread(index - 1, level, false);
|
if (x > 0) spread(index - 1, level, false);
|
||||||
if (x < REGION_SIZE - 1) spread(index + 1, level, false);
|
if (x < REGION_SIZE - 1) spread(index + 1, level, false);
|
||||||
if (z > 0) spread(index - REGION_SIZE, level, false);
|
if (z > 0) spread(index - REGION_SIZE, level, false);
|
||||||
@@ -162,18 +188,18 @@ export class LightRegion {
|
|||||||
|
|
||||||
// what a cell looks like to the mesher, including above and below the world
|
// what a cell looks like to the mesher, including above and below the world
|
||||||
export function region_block(region: LightRegion, index: number, y: number) {
|
export function region_block(region: LightRegion, index: number, y: number) {
|
||||||
if (y >= CHUNK_HEIGHT) return AIR;
|
if (y >= region.height) return AIR;
|
||||||
if (y < 0) return REGION_VOID;
|
if (y < 0) return REGION_VOID;
|
||||||
return region.blocks[index];
|
return region.blocks[index];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function region_sky(region: LightRegion, index: number, y: number) {
|
export function region_sky(region: LightRegion, index: number, y: number) {
|
||||||
if (y >= CHUNK_HEIGHT) return 15;
|
if (y >= region.height) return region.sky_light ? 15 : 0;
|
||||||
if (y < 0) return 0;
|
if (y < 0) return 0;
|
||||||
return region.sky[index];
|
return region.sky[index];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function region_block_light(region: LightRegion, index: number, y: number) {
|
export function region_block_light(region: LightRegion, index: number, y: number) {
|
||||||
if (y >= CHUNK_HEIGHT || y < 0) return 0;
|
if (y >= region.height || y < 0) return 0;
|
||||||
return region.block_light[index];
|
return region.block_light[index];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// which faces of a section can be seen through from which others, for occlusion culling (see
|
||||||
|
// client/rendering/occlusion.ts). worked out by the chunk workers as they mesh a section
|
||||||
|
|
||||||
|
// the 6 directions out of a section, and the faces they leave through, are a bit each: -x, +x, -y, +y, -z, +z. a
|
||||||
|
// direction's opposite is direction ^ 1
|
||||||
|
export const ALL_DIRECTIONS = 0b111111;
|
||||||
|
|
||||||
|
// a bit for each of the 15 pairs of different faces
|
||||||
|
const PAIR_BITS = new Uint16Array(36);
|
||||||
|
{
|
||||||
|
let bit = 0;
|
||||||
|
for (let a = 0; a < 6; a++) {
|
||||||
|
for (let b = a + 1; b < 6; b++) {
|
||||||
|
PAIR_BITS[a * 6 + b] = PAIR_BITS[b * 6 + a] = 1 << bit++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// every face sees every other, like a section of air, or one that hasn't been meshed yet
|
||||||
|
export const ALL_VISIBLE = (1 << 15) - 1;
|
||||||
|
|
||||||
|
// the directions a section can be left in when it was entered through the faces in incoming
|
||||||
|
export function exits(visibility: number, incoming: number) {
|
||||||
|
// most sections are all air or all stone. entered through one face, all the others
|
||||||
|
if (visibility === ALL_VISIBLE) return incoming & (incoming - 1) ? ALL_DIRECTIONS : ALL_DIRECTIONS & ~incoming;
|
||||||
|
if (visibility === 0) return 0;
|
||||||
|
let out = 0;
|
||||||
|
for (let a = 0; a < 6; a++) {
|
||||||
|
if (!(incoming & (1 << a))) continue;
|
||||||
|
for (let b = 0; b < 6; b++) {
|
||||||
|
if (visibility & PAIR_BITS[a * 6 + b]) out |= 1 << b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const unvisited = new Uint16Array(256);
|
||||||
|
const region = new Uint16Array(256);
|
||||||
|
|
||||||
|
// a section's visibility from the cells that can be seen through, by row (y << 4 | z, a bit per x). each connected
|
||||||
|
// region of them connects every pair of faces it touches. a region grows a row at a time, each row filled along its
|
||||||
|
// open runs at once, until it stops growing
|
||||||
|
export function section_visibility(open: Uint16Array) {
|
||||||
|
let count = 0;
|
||||||
|
for (let r = 0; r < 256; r++) count += bit_count(open[r]);
|
||||||
|
if (count === 4096) return ALL_VISIBLE;
|
||||||
|
if (count === 0) return 0;
|
||||||
|
|
||||||
|
unvisited.set(open);
|
||||||
|
let result = 0;
|
||||||
|
for (let start = 0; start < 256; start++) {
|
||||||
|
while (unvisited[start] !== 0) {
|
||||||
|
const seed = unvisited[start] & -unvisited[start];
|
||||||
|
region[start] = fill_row(seed, unvisited[start]);
|
||||||
|
let lo = start;
|
||||||
|
let hi = start;
|
||||||
|
let grown = true;
|
||||||
|
while (grown) {
|
||||||
|
grown = false;
|
||||||
|
const first = Math.max(0, lo - 16);
|
||||||
|
const last = Math.min(255, hi + 16);
|
||||||
|
// up then back down, so a region that winds back reaches its far end in fewer sweeps
|
||||||
|
for (let i = 0; i < 2 * (last - first + 1); i++) {
|
||||||
|
const r = i <= last - first ? first + i : last - (i - (last - first + 1));
|
||||||
|
let near = region[r];
|
||||||
|
if (r >= 16) near |= region[r - 16];
|
||||||
|
if (r < 240) near |= region[r + 16];
|
||||||
|
if (r & 15) near |= region[r - 1];
|
||||||
|
if ((r & 15) !== 15) near |= region[r + 1];
|
||||||
|
const reached = near & unvisited[r];
|
||||||
|
if (reached & ~region[r]) {
|
||||||
|
region[r] = fill_row(reached, unvisited[r]);
|
||||||
|
if (r < lo) lo = r;
|
||||||
|
if (r > hi) hi = r;
|
||||||
|
grown = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let faces = 0;
|
||||||
|
for (let r = lo; r <= hi; r++) {
|
||||||
|
const row = region[r];
|
||||||
|
if (row === 0) continue;
|
||||||
|
region[r] = 0;
|
||||||
|
unvisited[r] &= ~row;
|
||||||
|
const y = r >> 4;
|
||||||
|
const z = r & 15;
|
||||||
|
if (row & 1) faces |= 1;
|
||||||
|
if (row & 0x8000) faces |= 2;
|
||||||
|
if (y === 0) faces |= 4;
|
||||||
|
if (y === 15) faces |= 8;
|
||||||
|
if (z === 0) faces |= 16;
|
||||||
|
if (z === 15) faces |= 32;
|
||||||
|
}
|
||||||
|
// one region touching every face connects them all, nothing else can add to it
|
||||||
|
if (faces === ALL_DIRECTIONS) return ALL_VISIBLE;
|
||||||
|
for (let a = 0; a < 6; a++) {
|
||||||
|
for (let b = a + 1; b < 6; b++) {
|
||||||
|
if (faces & (1 << a) && faces & (1 << b)) result |= PAIR_BITS[a * 6 + b];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the cells of open connected to seeds within a row, filling each way and doubling the reach at each step
|
||||||
|
function fill_row(seeds: number, open: number) {
|
||||||
|
let up = seeds;
|
||||||
|
let through_up = open;
|
||||||
|
let down = seeds;
|
||||||
|
let through_down = open;
|
||||||
|
for (let step = 1; step <= 8; step <<= 1) {
|
||||||
|
up |= through_up & (up << step);
|
||||||
|
through_up &= through_up << step;
|
||||||
|
down |= through_down & (down >> step);
|
||||||
|
through_down &= through_down >> step;
|
||||||
|
}
|
||||||
|
return up | down;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bit_count(row: number) {
|
||||||
|
let count = 0;
|
||||||
|
for (; row; row &= row - 1) count++;
|
||||||
|
return count;
|
||||||
|
}
|
||||||
@@ -500,7 +500,7 @@ export function bake_model(
|
|||||||
let cull = face_json.cullface ? FACE_INDEX[face_json.cullface] : -1;
|
let cull = face_json.cullface ? FACE_INDEX[face_json.cullface] : -1;
|
||||||
for (let t = 0; t < x_turns && cull >= 0; t++) cull = TURN_X[cull];
|
for (let t = 0; t < x_turns && cull >= 0; t++) cull = TURN_X[cull];
|
||||||
for (let t = 0; t < turns && cull >= 0; t++) cull = TURN_Y[cull];
|
for (let t = 0; t < turns && cull >= 0; t++) cull = TURN_Y[cull];
|
||||||
const { face: facing, flush, aligned } = classify(positions);
|
const { face: facing, flush, aligned } = classify_quad(positions);
|
||||||
quads.push({
|
quads.push({
|
||||||
positions,
|
positions,
|
||||||
uvs,
|
uvs,
|
||||||
@@ -560,7 +560,7 @@ export function element_rotation(element: ModelElementJson): (point: number[]) =
|
|||||||
}
|
}
|
||||||
|
|
||||||
// which way a quad faces most, whether it's flat against the block's edge, and whether it faces straight along an axis
|
// which way a quad faces most, whether it's flat against the block's edge, and whether it faces straight along an axis
|
||||||
function classify(p: number[]): { face: number; flush: boolean; aligned: boolean } {
|
export function classify_quad(p: number[]): { face: number; flush: boolean; aligned: boolean } {
|
||||||
const e1 = [p[3] - p[0], p[4] - p[1], p[5] - p[2]];
|
const e1 = [p[3] - p[0], p[4] - p[1], p[5] - p[2]];
|
||||||
const e2 = [p[9] - p[0], p[10] - p[1], p[11] - p[2]];
|
const e2 = [p[9] - p[0], p[10] - p[1], p[11] - p[2]];
|
||||||
const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
|
const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
|
// the block rules shared phases register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
|
||||||
// clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own
|
// clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own
|
||||||
// BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with
|
// BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with
|
||||||
import type {
|
import type {
|
||||||
@@ -70,8 +70,8 @@ export class BlockRules {
|
|||||||
readonly told?: (x: number, y: number, z: number, from: Position) => void,
|
readonly told?: (x: number, y: number, z: number, from: Position) => void,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
// checked by the shared context, see common/shared_context.ts
|
||||||
register(mod: string, id: string, rules: Rules) {
|
register(mod: string, id: string, rules: Rules) {
|
||||||
if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of ${id} are registered twice`);
|
|
||||||
this.#rules.set(id, { mod, rules });
|
this.#rules.set(id, { mod, rules });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// binary messages and saves, written and read a number at a time. little-endian, which is what both use
|
||||||
|
export class Writer {
|
||||||
|
#bytes = new Uint8Array(16 * 1024);
|
||||||
|
#view = new DataView(this.#bytes.buffer);
|
||||||
|
#length = 0;
|
||||||
|
|
||||||
|
#reserve(size: number) {
|
||||||
|
if (this.#length + size <= this.#bytes.length) return;
|
||||||
|
const bytes = new Uint8Array(Math.max(this.#bytes.length * 2, this.#length + size));
|
||||||
|
bytes.set(this.#bytes);
|
||||||
|
this.#bytes = bytes;
|
||||||
|
this.#view = new DataView(bytes.buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
u8(value: number) {
|
||||||
|
this.#reserve(1);
|
||||||
|
this.#bytes[this.#length++] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
u16(value: number) {
|
||||||
|
this.#reserve(2);
|
||||||
|
this.#view.setUint16(this.#length, value, true);
|
||||||
|
this.#length += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
i16(value: number) {
|
||||||
|
this.#reserve(2);
|
||||||
|
this.#view.setInt16(this.#length, value, true);
|
||||||
|
this.#length += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
u32(value: number) {
|
||||||
|
this.#reserve(4);
|
||||||
|
this.#view.setUint32(this.#length, value, true);
|
||||||
|
this.#length += 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a u8 length, then the text as utf-8
|
||||||
|
string(text: string) {
|
||||||
|
const bytes = new TextEncoder().encode(text);
|
||||||
|
if (bytes.length > 255) throw new Error(`${text} is too long`);
|
||||||
|
this.u8(bytes.length);
|
||||||
|
this.#reserve(bytes.length);
|
||||||
|
this.#bytes.set(bytes, this.#length);
|
||||||
|
this.#length += bytes.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes() {
|
||||||
|
return this.#bytes.subarray(0, this.#length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// throws when there's less left than what's read
|
||||||
|
export class Reader {
|
||||||
|
#bytes: Uint8Array;
|
||||||
|
#view: DataView;
|
||||||
|
#offset = 0;
|
||||||
|
// only old saves are big-endian
|
||||||
|
#little: boolean;
|
||||||
|
|
||||||
|
constructor(bytes: Uint8Array, little_endian = true) {
|
||||||
|
this.#bytes = bytes;
|
||||||
|
this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||||
|
this.#little = little_endian;
|
||||||
|
}
|
||||||
|
|
||||||
|
get done() {
|
||||||
|
return this.#offset === this.#bytes.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
#take(size: number) {
|
||||||
|
if (this.#offset + size > this.#bytes.length) throw new Error("Too short");
|
||||||
|
const offset = this.#offset;
|
||||||
|
this.#offset += size;
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
u8() {
|
||||||
|
return this.#bytes[this.#take(1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
u16() {
|
||||||
|
return this.#view.getUint16(this.#take(2), this.#little);
|
||||||
|
}
|
||||||
|
|
||||||
|
i16() {
|
||||||
|
return this.#view.getInt16(this.#take(2), this.#little);
|
||||||
|
}
|
||||||
|
|
||||||
|
u32() {
|
||||||
|
return this.#view.getUint32(this.#take(4), this.#little);
|
||||||
|
}
|
||||||
|
|
||||||
|
string() {
|
||||||
|
const length = this.u8();
|
||||||
|
const offset = this.#take(length);
|
||||||
|
return new TextDecoder().decode(this.#bytes.subarray(offset, offset + length));
|
||||||
|
}
|
||||||
|
|
||||||
|
// the next size bytes, not copied
|
||||||
|
take(size: number) {
|
||||||
|
const offset = this.#take(size);
|
||||||
|
return this.#bytes.subarray(offset, offset + size);
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
-197
@@ -4,24 +4,16 @@
|
|||||||
// how the server streams the world to clients, like minecraft java since 1.20.2: whole chunks in batches around each
|
// how the server streams the world to clients, like minecraft java since 1.20.2: whole chunks in batches around each
|
||||||
// player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md
|
// player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md
|
||||||
import { deflateSync, inflateSync } from "fflate";
|
import { deflateSync, inflateSync } from "fflate";
|
||||||
import { CHUNK_AREA, CHUNK_HEIGHT } from "./constants.ts";
|
import { Reader, Writer } from "./bytes.ts";
|
||||||
|
import { type ChunkColumn, type ColumnBiomes, read_column, type Section, write_column } from "./section.ts";
|
||||||
|
|
||||||
// the view distances clients can ask for, in chunks, like minecraft's
|
// the view distances clients can ask for, in chunks, like minecraft's
|
||||||
export const MIN_VIEW_DISTANCE = 2;
|
export const MIN_VIEW_DISTANCE = 2;
|
||||||
export const MAX_VIEW_DISTANCE = 32;
|
export const MAX_VIEW_DISTANCE = 32;
|
||||||
|
|
||||||
export const SECTION_HEIGHT = 16;
|
|
||||||
const SECTION_VOLUME = CHUNK_AREA * SECTION_HEIGHT;
|
|
||||||
const SECTIONS = CHUNK_HEIGHT / SECTION_HEIGHT;
|
|
||||||
const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
|
|
||||||
|
|
||||||
// the first byte of a binary message, the only kind there is so far
|
// the first byte of a binary message, the only kind there is so far
|
||||||
export const LEVEL_CHUNK = 1;
|
export const LEVEL_CHUNK = 1;
|
||||||
|
|
||||||
// bits per block of a section's indirect palette, the smallest that fits. more than 256 kinds are stored directly
|
|
||||||
const PALETTE_BITS = [1, 2, 4, 8];
|
|
||||||
const DIRECT_BITS = 32;
|
|
||||||
|
|
||||||
// minecraft's ChunkTrackingView.isWithinDistance: a round view, with the ring of chunks around it (outer) that the
|
// minecraft's ChunkTrackingView.isWithinDistance: a round view, with the ring of chunks around it (outer) that the
|
||||||
// client needs to mesh and light the edge of what it shows
|
// client needs to mesh and light the edge of what it shows
|
||||||
export function is_within_view(
|
export function is_within_view(
|
||||||
@@ -39,13 +31,14 @@ export function is_within_view(
|
|||||||
return near * near + far * far < view_distance * view_distance;
|
return near * near + far * far < view_distance * view_distance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// what a client reads a level_chunk as
|
||||||
export interface LevelChunk {
|
export interface LevelChunk {
|
||||||
x: number;
|
x: number;
|
||||||
z: number;
|
z: number;
|
||||||
// block values (numeric id | state bits << 16) in the sender's numbering, y then z then x
|
// block values (numeric id | state bits << 16) in the receiver's numbering, see decode_level_chunk. from the bottom
|
||||||
blocks: Uint32Array;
|
// of the world up, the dimension's whole height
|
||||||
// each column's biome, x then z
|
sections: Section[];
|
||||||
biomes: string[];
|
biomes: ColumnBiomes;
|
||||||
}
|
}
|
||||||
|
|
||||||
// a level_chunk message, like minecraft's ClientboundLevelChunkWithLightPacket without the light (clients light
|
// a level_chunk message, like minecraft's ClientboundLevelChunkWithLightPacket without the light (clients light
|
||||||
@@ -53,28 +46,10 @@ export interface LevelChunk {
|
|||||||
//
|
//
|
||||||
// u8 LEVEL_CHUNK
|
// u8 LEVEL_CHUNK
|
||||||
// i32 chunk x, i32 chunk z
|
// i32 chunk x, i32 chunk z
|
||||||
// the rest deflated:
|
// the rest deflated: the sections' block values and biomes, see write_column in common/section.ts
|
||||||
// u16 biome palette size, then each biome: u8 length and the id as utf-8
|
export function encode_level_chunk(chunk: ChunkColumn): Uint8Array<ArrayBuffer> {
|
||||||
// u8 each column's biome palette index, x then z. left out when there's one biome
|
|
||||||
// 16 sections of 16x16x16 blocks, bottom first, each a paletted container like minecraft's:
|
|
||||||
// u8 bits per block
|
|
||||||
// 0: u32 the value of every block
|
|
||||||
// 1, 2, 4, 8: u16 palette size, u32 each value, then each block's palette index packed from the low bits up
|
|
||||||
// 32: u32 each block's value
|
|
||||||
export function encode_level_chunk(chunk: LevelChunk): Uint8Array<ArrayBuffer> {
|
|
||||||
const writer = new Writer();
|
const writer = new Writer();
|
||||||
|
write_column(writer, chunk.sections, chunk.biomes);
|
||||||
const biome_palette = [...new Set(chunk.biomes)];
|
|
||||||
writer.u16(biome_palette.length);
|
|
||||||
for (const biome of biome_palette) writer.string(biome);
|
|
||||||
if (biome_palette.length > 1) {
|
|
||||||
for (const biome of chunk.biomes) writer.u8(biome_palette.indexOf(biome));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let section = 0; section < SECTIONS; section++) {
|
|
||||||
write_section(writer, chunk.blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME));
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = deflateSync(writer.bytes());
|
const body = deflateSync(writer.bytes());
|
||||||
const bytes = new Uint8Array(9 + body.length);
|
const bytes = new Uint8Array(9 + body.length);
|
||||||
const view = new DataView(bytes.buffer);
|
const view = new DataView(bytes.buffer);
|
||||||
@@ -85,39 +60,6 @@ export function encode_level_chunk(chunk: LevelChunk): Uint8Array<ArrayBuffer> {
|
|||||||
return bytes;
|
return bytes;
|
||||||
}
|
}
|
||||||
|
|
||||||
function write_section(writer: Writer, blocks: Uint32Array) {
|
|
||||||
const palette: number[] = [];
|
|
||||||
const index_of = new Map<number, number>();
|
|
||||||
for (const value of blocks) {
|
|
||||||
if (!index_of.has(value)) {
|
|
||||||
index_of.set(value, palette.length);
|
|
||||||
palette.push(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (palette.length === 1) {
|
|
||||||
writer.u8(0);
|
|
||||||
writer.u32(palette[0]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const bits = PALETTE_BITS.find((bits) => palette.length <= 1 << bits);
|
|
||||||
if (bits === undefined) {
|
|
||||||
writer.u8(DIRECT_BITS);
|
|
||||||
for (const value of blocks) writer.u32(value);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
writer.u8(bits);
|
|
||||||
writer.u16(palette.length);
|
|
||||||
for (const value of palette) writer.u32(value);
|
|
||||||
const per_byte = 8 / bits;
|
|
||||||
for (let i = 0; i < SECTION_VOLUME; i += per_byte) {
|
|
||||||
let byte = 0;
|
|
||||||
for (let j = 0; j < per_byte; j++) byte |= index_of.get(blocks[i + j])! << (j * bits);
|
|
||||||
writer.u8(byte);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// throws when the bytes aren't a level_chunk. map turns each block value into the receiver's numbering
|
// throws when the bytes aren't a level_chunk. map turns each block value into the receiver's numbering
|
||||||
export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => number = (value) => value): LevelChunk {
|
export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => number = (value) => value): LevelChunk {
|
||||||
if (bytes[0] !== LEVEL_CHUNK || bytes.length < 9) throw new Error("Not a level_chunk");
|
if (bytes[0] !== LEVEL_CHUNK || bytes.length < 9) throw new Error("Not a level_chunk");
|
||||||
@@ -125,134 +67,7 @@ export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => nu
|
|||||||
const x = header.getInt32(1, true);
|
const x = header.getInt32(1, true);
|
||||||
const z = header.getInt32(5, true);
|
const z = header.getInt32(5, true);
|
||||||
const reader = new Reader(inflateSync(bytes.subarray(9)));
|
const reader = new Reader(inflateSync(bytes.subarray(9)));
|
||||||
|
const { sections, biomes } = read_column(reader, map);
|
||||||
const biome_palette: string[] = [];
|
|
||||||
const biome_count = reader.u16();
|
|
||||||
if (biome_count === 0) throw new Error("No biomes");
|
|
||||||
for (let i = 0; i < biome_count; i++) biome_palette.push(reader.string());
|
|
||||||
const biomes: string[] = new Array(CHUNK_AREA);
|
|
||||||
for (let column = 0; column < CHUNK_AREA; column++) {
|
|
||||||
const index = biome_count > 1 ? reader.u8() : 0;
|
|
||||||
if (index >= biome_count) throw new Error("Bad biome index");
|
|
||||||
biomes[column] = biome_palette[index];
|
|
||||||
}
|
|
||||||
|
|
||||||
const blocks = new Uint32Array(CHUNK_VOLUME);
|
|
||||||
for (let section = 0; section < SECTIONS; section++) {
|
|
||||||
read_section(reader, blocks.subarray(section * SECTION_VOLUME, (section + 1) * SECTION_VOLUME), map);
|
|
||||||
}
|
|
||||||
if (!reader.done) throw new Error("Wrong size");
|
if (!reader.done) throw new Error("Wrong size");
|
||||||
return { x, z, blocks, biomes };
|
return { x, z, sections, biomes };
|
||||||
}
|
|
||||||
|
|
||||||
function read_section(reader: Reader, blocks: Uint32Array, map: (value: number) => number) {
|
|
||||||
const bits = reader.u8();
|
|
||||||
if (bits === 0) {
|
|
||||||
blocks.fill(map(reader.u32()));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (bits === DIRECT_BITS) {
|
|
||||||
for (let i = 0; i < SECTION_VOLUME; i++) blocks[i] = map(reader.u32());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!PALETTE_BITS.includes(bits)) throw new Error(`Bad bits per block ${bits}`);
|
|
||||||
|
|
||||||
const palette: number[] = [];
|
|
||||||
const size = reader.u16();
|
|
||||||
if (size > 1 << bits) throw new Error("Bad palette");
|
|
||||||
for (let i = 0; i < size; i++) palette.push(map(reader.u32()));
|
|
||||||
const per_byte = 8 / bits;
|
|
||||||
const mask = (1 << bits) - 1;
|
|
||||||
for (let i = 0; i < SECTION_VOLUME; i += per_byte) {
|
|
||||||
const byte = reader.u8();
|
|
||||||
for (let j = 0; j < per_byte; j++) {
|
|
||||||
const index = (byte >> (j * bits)) & mask;
|
|
||||||
if (index >= size) throw new Error("Bad palette index");
|
|
||||||
blocks[i + j] = palette[index];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Writer {
|
|
||||||
#bytes = new Uint8Array(16 * 1024);
|
|
||||||
#view = new DataView(this.#bytes.buffer);
|
|
||||||
#length = 0;
|
|
||||||
|
|
||||||
#reserve(size: number) {
|
|
||||||
if (this.#length + size <= this.#bytes.length) return;
|
|
||||||
const bytes = new Uint8Array(Math.max(this.#bytes.length * 2, this.#length + size));
|
|
||||||
bytes.set(this.#bytes);
|
|
||||||
this.#bytes = bytes;
|
|
||||||
this.#view = new DataView(bytes.buffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
u8(value: number) {
|
|
||||||
this.#reserve(1);
|
|
||||||
this.#bytes[this.#length++] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
u16(value: number) {
|
|
||||||
this.#reserve(2);
|
|
||||||
this.#view.setUint16(this.#length, value, true);
|
|
||||||
this.#length += 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
u32(value: number) {
|
|
||||||
this.#reserve(4);
|
|
||||||
this.#view.setUint32(this.#length, value, true);
|
|
||||||
this.#length += 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
string(text: string) {
|
|
||||||
const bytes = new TextEncoder().encode(text);
|
|
||||||
if (bytes.length > 255) throw new Error(`${text} is too long to send`);
|
|
||||||
this.u8(bytes.length);
|
|
||||||
this.#reserve(bytes.length);
|
|
||||||
this.#bytes.set(bytes, this.#length);
|
|
||||||
this.#length += bytes.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
bytes() {
|
|
||||||
return this.#bytes.subarray(0, this.#length);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Reader {
|
|
||||||
#bytes: Uint8Array;
|
|
||||||
#view: DataView;
|
|
||||||
#offset = 0;
|
|
||||||
|
|
||||||
constructor(bytes: Uint8Array) {
|
|
||||||
this.#bytes = bytes;
|
|
||||||
this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
||||||
}
|
|
||||||
|
|
||||||
get done() {
|
|
||||||
return this.#offset === this.#bytes.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
#take(size: number) {
|
|
||||||
if (this.#offset + size > this.#bytes.length) throw new Error("Too short");
|
|
||||||
const offset = this.#offset;
|
|
||||||
this.#offset += size;
|
|
||||||
return offset;
|
|
||||||
}
|
|
||||||
|
|
||||||
u8() {
|
|
||||||
return this.#bytes[this.#take(1)];
|
|
||||||
}
|
|
||||||
|
|
||||||
u16() {
|
|
||||||
return this.#view.getUint16(this.#take(2), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
u32() {
|
|
||||||
return this.#view.getUint32(this.#take(4), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
string() {
|
|
||||||
const length = this.u8();
|
|
||||||
const offset = this.#take(length);
|
|
||||||
return new TextDecoder().decode(this.#bytes.subarray(offset, offset + length));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -36,7 +36,7 @@ export const ID_MASK = 0xFFFF;
|
|||||||
export const STATE_SHIFT = 16;
|
export const STATE_SHIFT = 16;
|
||||||
|
|
||||||
export const CHUNK_SIZE = 16;
|
export const CHUNK_SIZE = 16;
|
||||||
export const CHUNK_HEIGHT = 256;
|
// how tall chunks are is up to their dimension, see common/world_shape.ts
|
||||||
// the top of oceans and rivers
|
// the top of oceans and rivers
|
||||||
export const SEA_LEVEL = 64;
|
export const SEA_LEVEL = 64;
|
||||||
export const CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
|
export const CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// runs the content phase of a mod's script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the
|
||||||
|
// server on its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to
|
||||||
|
// the mod's data before anything else reads it
|
||||||
|
import { type BlockJson, validate_block } from "./mod_data.ts";
|
||||||
|
import type { ContentContext } from "./mod_api/content.ts";
|
||||||
|
import { ModLoadError, registrar, run_phase } from "./mod_loader.ts";
|
||||||
|
import { expose_engine } from "./hooks.ts";
|
||||||
|
import { common_engine } from "./engine_modules.ts";
|
||||||
|
|
||||||
|
export interface ContentScript {
|
||||||
|
mod: string;
|
||||||
|
version: string;
|
||||||
|
engine_access?: boolean;
|
||||||
|
// importable url of the script
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a .cubi's bundled script, what server/content_worker.ts is sent
|
||||||
|
export interface ContentScriptCode {
|
||||||
|
mod: string;
|
||||||
|
version: string;
|
||||||
|
engine_access?: boolean;
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what a content phase registered, in order, and what was wrong. with problems the mod doesn't load
|
||||||
|
export interface RegisteredContent {
|
||||||
|
blocks: BlockJson[];
|
||||||
|
problems: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function run_content_script(
|
||||||
|
{ mod, version, engine_access, url }: ContentScript,
|
||||||
|
): Promise<RegisteredContent> {
|
||||||
|
// the whole script loads here, and one with engine access can import cubi/engine. only engine.common is here
|
||||||
|
expose_engine({ common: common_engine() });
|
||||||
|
const blocks: BlockJson[] = [];
|
||||||
|
let running = true;
|
||||||
|
const register = registrar(mod, "content", () => running);
|
||||||
|
const ctx: ContentContext = {
|
||||||
|
mod: { id: mod, version },
|
||||||
|
blocks: {
|
||||||
|
register(block) {
|
||||||
|
register.running("block");
|
||||||
|
// what a file could hold, so the server, its players and its worldgen workers all get the same thing
|
||||||
|
const json = JSON.parse(JSON.stringify(block ?? null));
|
||||||
|
const id = typeof json?.id === "string" ? json.id : "without an id";
|
||||||
|
const problems = validate_block(json);
|
||||||
|
if (problems.length > 0) register.fail(`block ${id}: ${problems.join("; ")}`);
|
||||||
|
register.own("block", json.id);
|
||||||
|
blocks.push(json);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await run_phase({ id: mod, engine_access }, url, "content", () => ctx);
|
||||||
|
return { blocks, problems: [] };
|
||||||
|
} catch (e) {
|
||||||
|
const problem = e instanceof ModLoadError ? e.problem : e instanceof Error ? e.message : String(e);
|
||||||
|
return { blocks, problems: [problem] };
|
||||||
|
} finally {
|
||||||
|
running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import { Container, ContainerSlot, ItemStack } from "./inventory.ts";
|
|||||||
import { BlockRules } from "./block_rules.ts";
|
import { BlockRules } from "./block_rules.ts";
|
||||||
import { Tags } from "./tags.ts";
|
import { Tags } from "./tags.ts";
|
||||||
import { CommandDispatcher } from "./commands.ts";
|
import { CommandDispatcher } from "./commands.ts";
|
||||||
import { OverworldTerrain } from "./worldgen/terrain.ts";
|
import { NoiseTerrain } from "./worldgen/terrain.ts";
|
||||||
import { physics } from "./physics.ts";
|
import { physics } from "./physics.ts";
|
||||||
|
|
||||||
// built when it's exposed, not when this module loads, so import cycles can't leave anything undefined
|
// built when it's exposed, not when this module loads, so import cycles can't leave anything undefined
|
||||||
@@ -20,7 +20,7 @@ export function common_engine() {
|
|||||||
BlockRules,
|
BlockRules,
|
||||||
Tags,
|
Tags,
|
||||||
CommandDispatcher,
|
CommandDispatcher,
|
||||||
OverworldTerrain,
|
NoiseTerrain,
|
||||||
physics,
|
physics,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user