Compare commits
351
Commits
9e580f175e
...
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 | ||
|
|
98fa45ebd1 | ||
|
|
68b78f053a | ||
|
|
c3394f69b6 | ||
|
|
577bec86b4 | ||
|
|
adf140eb6b | ||
|
|
569fb51d91 | ||
|
|
ef35e5e26b | ||
|
|
9e48a42c1f | ||
|
|
43bd4509ad | ||
|
|
b329a61d96 | ||
|
|
65113862f7 | ||
|
|
c8b5f2a3bd | ||
|
|
ad782839ec | ||
|
|
61693d611a | ||
|
|
4a713a85d1 | ||
|
|
2ad757eb44 | ||
|
|
151758b94f | ||
|
|
facbbb07da | ||
|
|
b08de6bf81 | ||
|
|
658a6453b7 | ||
|
|
65934d34a1 | ||
|
|
407ed77385 | ||
|
|
23d02c5229 | ||
|
|
3734f5707a | ||
|
|
43aa6b2551 | ||
|
|
4717e45a9a | ||
|
|
43521b3675 | ||
|
|
5d64b801a3 | ||
|
|
b8cccb86ff | ||
|
|
fa0748a9c5 | ||
|
|
872db88066 | ||
|
|
507e9aab24 | ||
|
|
a70375c9ad | ||
|
|
e525681328 | ||
|
|
3cc33ea10c | ||
|
|
1539cf6933 | ||
|
|
bcd0690ef5 | ||
|
|
8fc08ab41e | ||
|
|
e5221ba681 | ||
|
|
e729b92d20 | ||
|
|
f46058f9b5 | ||
|
|
c955d8d143 | ||
|
|
a28e0b9abb | ||
|
|
233c518def | ||
|
|
08df7f1b6b | ||
|
|
feb1ddd1f7 | ||
|
|
583cce88c1 | ||
|
|
436f68ce33 | ||
|
|
26b59a1899 | ||
|
|
fc27771a92 | ||
|
|
17d83acfc8 | ||
|
|
0cfa4d9b4a | ||
|
|
bcca8fa4a5 | ||
|
|
4fad43d9cc | ||
|
|
31ae2973d7 | ||
|
|
4cd29a17b3 | ||
|
|
1b30d71a47 | ||
|
|
20e6ac6fbb | ||
|
|
db0589d965 | ||
|
|
6af6c52673 | ||
|
|
0d80e85dec | ||
|
|
b5777c84d3 | ||
|
|
0bc66c21b9 | ||
|
|
987e7a0f9a | ||
|
|
2c1eaf5735 | ||
|
|
1c2dcd0dbc | ||
|
|
77cd327f94 | ||
|
|
0af35d1e17 | ||
|
|
c7a2392591 | ||
|
|
b43e8fe8b8 | ||
|
|
7faa070d83 | ||
|
|
74c315bdfc | ||
|
|
a0596ed0ef | ||
|
|
cedc7725b5 | ||
|
|
d7f1b91c0a | ||
|
|
6ad476ac18 | ||
|
|
55ad08266e | ||
|
|
a10b15a3fd | ||
|
|
b34e97e487 | ||
|
|
a18b099206 | ||
|
|
5165698fe3 | ||
|
|
dfc6a6d77b | ||
|
|
bea5f10a12 | ||
|
|
02cbeda0a0 | ||
|
|
c5ffc23bcd | ||
|
|
038b6d2caa | ||
|
|
99bdcaeffc | ||
|
|
d4eff11f3e | ||
|
|
e5baeab193 | ||
|
|
355e7a21ca | ||
|
|
48c6f0ec1d | ||
|
|
c1dd0e62a8 | ||
|
|
69c32e4d13 | ||
|
|
f5c65331ca | ||
|
|
a913e0c5ad | ||
|
|
6269f0306d | ||
|
|
8b0ce1a2a8 | ||
|
|
2ebcf55ad3 | ||
|
|
726a52b91a | ||
|
|
df26248f4a | ||
|
|
ff5fb971da | ||
|
|
4bd052e0c7 | ||
|
|
4a9ac423fe | ||
|
|
b507ad627b | ||
|
|
eb02f0a5f6 | ||
|
|
365819ef7f | ||
|
|
e1f3fda692 | ||
|
|
fbef1d96d2 | ||
|
|
935c0df7af | ||
|
|
3c80938e91 | ||
|
|
aa8257ad86 | ||
|
|
d4aa663836 | ||
|
|
7655d5a0ce | ||
|
|
67e8fe5c00 | ||
|
|
870235442b | ||
|
|
2cc5d4e013 | ||
|
|
c3bc1b3501 | ||
|
|
cd943246d0 | ||
|
|
42661d37ad | ||
|
|
99a7b0ad00 | ||
|
|
a63094213e | ||
|
|
ec34603b0a | ||
|
|
c71584eeea | ||
|
|
21442fb822 | ||
|
|
592659e57b | ||
|
|
e8387392fd | ||
|
|
fa969e0a96 | ||
|
|
1623b91ddf | ||
|
|
ab2b8e6545 | ||
|
|
5a59a63862 | ||
|
|
44a39bf8ec | ||
|
|
cd3b39c3d7 | ||
|
|
3d2b235f64 | ||
|
|
afe6e03d4c | ||
|
|
bf91450a9d | ||
|
|
f348734a41 | ||
|
|
be05f70fb5 | ||
|
|
f4cf1d8fa8 | ||
|
|
b03ad862e0 | ||
|
|
20c5e97599 | ||
|
|
0376b1ab1f | ||
|
|
88a3c9c92d | ||
|
|
48f5b80776 | ||
|
|
ceb1b1f0f0 | ||
|
|
6dc85ff17e | ||
|
|
373d9f83e5 | ||
|
|
588655e7df | ||
|
|
79ff6f9ad5 | ||
|
|
7fe9c15b67 | ||
|
|
4d5700f0bf | ||
|
|
9bc51b05ad | ||
|
|
344148f9b8 | ||
|
|
2cd19f9764 | ||
|
|
a82d3283e8 | ||
|
|
067fac270b | ||
|
|
aa0d2f73d0 | ||
|
|
9c5a15542a | ||
|
|
a2ed562817 | ||
|
|
807b38b0af | ||
|
|
dd66d6caa7 | ||
|
|
7e7ac8f6f4 | ||
|
|
9f0b049148 | ||
|
|
ec2b53c02a | ||
|
|
757ee74bc7 | ||
|
|
78117f65c9 | ||
|
|
d101fa2ef3 | ||
|
|
fbc9266936 | ||
|
|
b6b10e35e2 | ||
|
|
b128da0631 | ||
|
|
ff53d30a7e | ||
|
|
4f8fef6ca2 | ||
|
|
7767efab58 | ||
|
|
6fe5e0809e | ||
|
|
3ec25c1471 | ||
|
|
8f8030c02e | ||
|
|
40d5a4f5af | ||
|
|
b830196829 | ||
|
|
69c5c187db | ||
|
|
d13938550d | ||
|
|
5481ec94a4 | ||
|
|
4524cfe960 | ||
|
|
3cf4b10b8c | ||
|
|
c29f3be466 | ||
|
|
5d4b91b3a1 | ||
|
|
505a8598b1 | ||
|
|
33ba86fc76 | ||
|
|
4cdf48c9fb | ||
|
|
6a6abae0d5 | ||
|
|
67c84e3504 | ||
|
|
681692bdce | ||
|
|
721b6d6f3e | ||
|
|
2707cefe9d | ||
|
|
8e6b830ac2 | ||
|
|
f78bc374eb | ||
|
|
cb7d655f0c | ||
|
|
41fa75e864 | ||
|
|
7417bfd5f1 | ||
|
|
63e6248f9f | ||
|
|
91655c28c5 | ||
|
|
24fe7cdede | ||
|
|
ecc0295f6d | ||
|
|
50d47cedef | ||
|
|
4fb392adae | ||
|
|
dcaf878254 | ||
|
|
1511338a23 | ||
|
|
4397bf2c90 | ||
|
|
3202c18ab5 | ||
|
|
a4fec0681f | ||
|
|
043c526c9c | ||
|
|
9f637e6afb | ||
|
|
5a018a0470 | ||
|
|
d2dde8c14f | ||
|
|
7b3cdd925e | ||
|
|
cd07d441b2 | ||
|
|
f749f6be79 | ||
|
|
e560cb3928 | ||
|
|
e5dcb97643 | ||
|
|
4309c700d2 | ||
|
|
88d6de13d5 | ||
|
|
9ca717d2d0 | ||
|
|
d5015edfa1 | ||
|
|
6e5703a482 | ||
|
|
8396e8e895 | ||
|
|
f2c3cb8135 | ||
|
|
ea9f3f61bb | ||
|
|
1fc92a7b00 | ||
|
|
a7835261e1 | ||
|
|
3dc7d2adee | ||
|
|
deba36260e | ||
|
|
013a4fbb97 | ||
|
|
1c09466424 | ||
|
|
6fb7a423cb | ||
|
|
a6fd508529 | ||
|
|
0052faa24d | ||
|
|
cbc9edfd60 | ||
|
|
93382d3c97 | ||
|
|
5e2b415f5c | ||
|
|
3af5f6e54b | ||
|
|
342b45d593 | ||
|
|
dc70ada7c4 | ||
|
|
4fbcca6851 | ||
|
|
65f27d6099 |
@@ -3,3 +3,4 @@ world/
|
|||||||
server_mods/
|
server_mods/
|
||||||
dist/
|
dist/
|
||||||
ports/
|
ports/
|
||||||
|
/config/
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# bworld
|
||||||
|
|
||||||
|
A voxel game in TypeScript on Deno. The base game is itself a mod (`mods/bworld`), written against the same modding API
|
||||||
|
as any other mod.
|
||||||
|
|
||||||
|
**Never under any circumstance commit anything on your own**
|
||||||
|
|
||||||
|
**Never under any circumstance generate any textures or audio files**
|
||||||
|
|
||||||
|
Always ask before making even the simplest models, unless it's coming from ports/
|
||||||
|
|
||||||
|
## Names
|
||||||
|
|
||||||
|
- The engine is called `cubi`, all engine names should use the `cubi` namespace like `cubi:air`
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
- `server/`: the game server, world, saves and server-side game logic
|
||||||
|
- `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/`)
|
||||||
|
- `mods/`: mods, with JSON data (blocks, items, recipes, worldgen, tags), textures and TypeScript scripts
|
||||||
|
- `docs/`: modding docs and `docs/modding_plan.md`
|
||||||
|
- `tests/`: Deno tests
|
||||||
|
- `tools/`: dev scripts (mod checking and packing, worldgen preview, benchmarks)
|
||||||
|
- `ports/`: reference source from other projects, not part of the game (see below)
|
||||||
|
- `build/`, `server_mods/`, `dist/`, `world/`: build output and the local world. Don't edit these by hand.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```sh
|
||||||
|
deno task test # every test, takes about 3 minutes
|
||||||
|
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 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 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 task import KIND IN --output OUT # convert a java mod's resources, see tools/importer.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests load mods straight from `mods/` through `test_game` in `tests/helpers.ts`, so they don't need a build. Run
|
||||||
|
`deno task check-mods` after changing anything in a mod.
|
||||||
|
|
||||||
|
## Engine and base game
|
||||||
|
|
||||||
|
The engine is what any game built on it needs: rendering, physics, networking, saving, registries, the mod loader, GUI,
|
||||||
|
entities. Game content and rules belong in `mods/bworld` (data in its JSON folders, behavior in `mods/bworld/scripts/`).
|
||||||
|
If the base game can't do something as a mod, add what's missing to the modding API rather than special-casing it in the
|
||||||
|
engine, since other mods would hit the same wall. See "The Engine and the Base Game" in `docs/modding_plan.md`.
|
||||||
|
|
||||||
|
When changing the modding API, update the docs that cover it: `MODS.md` and `docs/modding/`, which follows the layout of
|
||||||
|
`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
|
||||||
|
|
||||||
|
- Classes are PascalCase, everything else is snake_case: functions, variables, fields, files and ids.
|
||||||
|
- Before writing something new, search the project for an existing feature that already does it or something close to
|
||||||
|
it, and reuse or extend that. Code duplication is a major problem here and should be avoided.
|
||||||
|
- Keep things simple. Don't add abstractions, options or generality the task doesn't need.
|
||||||
|
- Private class members use `#`, not the `private` keyword.
|
||||||
|
- Comments are lowercase and explain why or what something is for, not what the next line does.
|
||||||
|
- Don't mention Minecraft by name in comments, and don't paste or reference pieces of its code in them. Comments should
|
||||||
|
explain the code on its own terms.
|
||||||
|
- Mod data files start with `"format_version": 1`, and ids are namespaced by mod (`bworld:oak_log`). New content should
|
||||||
|
follow the files next to it, so look at a similar block, item or recipe first.
|
||||||
|
- Changing a message in `common/protocol.ts` means bumping `PROTOCOL_VERSION`.
|
||||||
|
- The game is in pre-alpha and backwards compatibility isn't a priority. Only test worlds exist. If supporting old saves
|
||||||
|
or old data takes a lot of code, it's fine to break them instead.
|
||||||
|
- Tests should check the behavior they're about, and shouldn't need changing when unrelated parts of the game change.
|
||||||
|
Avoid asserting on specific content (exact block lists, recipe counts, worldgen output, tuned numbers) unless that
|
||||||
|
content is what's being tested.
|
||||||
|
- Changing world generation (terrain, ores, features) on purpose makes the worldgen golden tests fail. Record them again
|
||||||
|
with `deno test -A tests/worldgen_golden_test.ts -- --update`.
|
||||||
|
- Commit messages are short and plain, like "Metal ingots and blocks", with no prefixes.
|
||||||
|
|
||||||
|
## Reference code in `ports/`
|
||||||
|
|
||||||
|
`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
|
||||||
|
resemble NeoForge's.
|
||||||
|
- `ports/justenoughitems`: check when working on the recipe viewer mod (`mods/recipe_viewer`).
|
||||||
|
- `ports/sodium`: check when looking for rendering optimizations.
|
||||||
|
- `ports/lithium`: check when looking for server optimizations.
|
||||||
@@ -0,0 +1,734 @@
|
|||||||
|
# Create
|
||||||
|
|
||||||
|
A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics, processing, logistics, fluids,
|
||||||
|
redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as
|
||||||
|
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
|
||||||
|
|
||||||
|
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed`, `rotating`, `fluid` and
|
||||||
|
items), R4, R5, R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts, cogwheels, gearboxes,
|
||||||
|
encased shafts and cogs, clutches, gearshifts and chain drives turned by a hand crank, creative motor or water wheel,
|
||||||
|
with stress and overstress), Create's pressing recipes, the mechanical press pressing items on the ground or compacting
|
||||||
|
in a basin, and the basin holding items and fluids. Facts about Create come from reading `ports/create1.21.1` and
|
||||||
|
`ports/create1.19.3`, and facts about bworld from its source.
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
| Copy | Version | Used for |
|
||||||
|
| -------------------- | ------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `ports/create1.21.1` | 6.0.11 | **All code and data**: mechanics, numbers, recipes, tags, worldgen, ponder scripts |
|
||||||
|
| `ports/create1.19.3` | 0.5.0.j | **Textures, models, blockstates, sounds and ponder scenes** from its `assets/` and `src/generated/resources/assets/` |
|
||||||
|
|
||||||
|
0.5.0.j shipped with only an MIT `LICENSE`, so its assets are used under that, with the MIT notice in
|
||||||
|
`mods/create/CREDITS.md`. 6.0.11's `assets/` folder isn't in the copy and isn't used.
|
||||||
|
|
||||||
|
**Keep the art removable.** Everything from 0.5.0.j's assets is written by the importer (below) into
|
||||||
|
`mods/create/textures/` and `mods/create/models/`, and nothing else in the mod depends on a specific file being there.
|
||||||
|
Removing the art is then deleting those two folders and re-running the importer with `--no-assets`. That writes
|
||||||
|
placeholder models (a plain cube, or the block's shape) and a placeholder texture, and the mod still loads and plays.
|
||||||
|
|
||||||
|
**Content newer than 0.5.0.j has no art to take**, so it needs new art either way. These are the blocks and items 6.0.11
|
||||||
|
registers that 0.5.0.j doesn't: the package logistics (`packager`, `repackager`, `package_frogport`, `stock_ticker`,
|
||||||
|
`stock_link`, `redstone_requester`, `factory_gauge`, `package_filter`, `item_hatch`, `chain_conveyor`, cardboard and its
|
||||||
|
blocks and armor, table cloths, `shopping_list`), `large_water_wheel`, `elevator_pulley`, `elevator_contact`,
|
||||||
|
`contraption_controls`, `mechanical_roller`, the copycats, `clipboard`, `desk_bell`, `pulse_timer`, metal doors and
|
||||||
|
scaffolding, `andesite_alloy_block`, `industrial_iron_block`, `weathered_iron_block`, `experience_block`, netherite
|
||||||
|
diving gear. The importer lists them in its report.
|
||||||
|
|
||||||
|
## How Big Create Is
|
||||||
|
|
||||||
|
6.0.11 is 2017 Java files, about 275,000 lines. By part:
|
||||||
|
|
||||||
|
| Part | Lines | What |
|
||||||
|
| --------------------------- | ------ | ------------------------------------------------------------------------------- |
|
||||||
|
| `content/kinetics` | 36,000 | Shafts, cogs, gearboxes, generators, belts, and the machines that use rotation |
|
||||||
|
| `infrastructure` | 33,000 | Config, datagen, ponder scenes, commands |
|
||||||
|
| `content/trains` | 30,000 | Tracks, the track graph, signals, stations, schedules, train entities |
|
||||||
|
| `content/logistics` | 30,000 | Funnels, tunnels, chutes, depots, vaults, filters, and 6.0's packages |
|
||||||
|
| `content/contraptions` | 27,000 | Moving block structures: bearings, pistons, pulleys, gantries, actors |
|
||||||
|
| `content/equipment` | 17,000 | Wrench, goggles, potato cannon, backtank, toolbox, symmetry wand |
|
||||||
|
| `content/redstone` | 12,000 | Links, nixie tubes, display links, threshold switch, diodes |
|
||||||
|
| `content/fluids` | 12,000 | Pipes, pumps, tanks, spouts, drains, hose pulley, boilers |
|
||||||
|
| `compat` | 10,000 | Other mods. Only the JEI part matters, for the recipe viewer |
|
||||||
|
| `content/decoration` | 7,000 | Palettes, copycats, girders, sliding doors, placards |
|
||||||
|
| `content/schematics` | 7,000 | Schematic table, schematicannon |
|
||||||
|
| `content/processing` | 5,000 | Basin, blaze burner, sequenced assembly, the processing recipe base |
|
||||||
|
| `foundation`, `api`, `impl` | 40,000 | Block entity behaviours, connected textures, GUI, networking, rendering helpers |
|
||||||
|
|
||||||
|
Data in 6.0.11: 188 blocks and 60 items registered one by one (plus generated families like palettes), and 1881 recipes
|
||||||
|
in 19 types. Art in 0.5.0.j: 1043 generated and 573 hand-made block models, 1006 textures, 92 connected texture sheets,
|
||||||
|
153 ponder scenes.
|
||||||
|
|
||||||
|
A straight line-by-line translation would be most of a year of work and would carry over things bworld doesn't need,
|
||||||
|
like datagen, mixins, compat and Forge plumbing. The plan below is built to avoid that.
|
||||||
|
|
||||||
|
## Strategy
|
||||||
|
|
||||||
|
Six rules that keep the work small:
|
||||||
|
|
||||||
|
1. **Import data, don't hand-write it.** One tool converts Create's models, textures, blockstates, recipes, tags, loot,
|
||||||
|
names and worldgen into bworld's formats, and reports what it couldn't convert. Hundreds of blocks then cost the same
|
||||||
|
as one. It's run once to start from, and what it made is edited by hand after. This replaces Create's datagen.
|
||||||
|
2. **Port Create's architecture onto bworld's, not its classes.** Create builds every machine from a few shared pieces
|
||||||
|
(block entity behaviours, a rotation network, processing recipes, instance types). Each piece becomes one bworld
|
||||||
|
piece, and then the machines are mostly data plus a little code (see [Architecture](#architecture)).
|
||||||
|
3. **Put general features in the engine, once.** Block capabilities, fluids, redstone, instanced rendering and moving
|
||||||
|
block structures are things any mod could use. They go in the engine shaped like NeoForge's (check `ports/neoforge`),
|
||||||
|
and Create is their first user.
|
||||||
|
4. **Change-driven server work.** Rotation, pipes and belts are networks that only recompute when something in them
|
||||||
|
changes. Blocks that have nothing to do don't tick.
|
||||||
|
5. **GPU-driven animation.** A turning part is uploaded once with its axis, speed and offset, and the vertex shader
|
||||||
|
turns it from the time, like Create's `rotating` instance type. Nothing is sent or computed per frame for something
|
||||||
|
that turns at a steady speed.
|
||||||
|
6. **Playable in phases.** Each phase ends with something to use in a world and tests passing, in an order where every
|
||||||
|
phase only needs the ones before it.
|
||||||
|
|
||||||
|
## The Importer
|
||||||
|
|
||||||
|
A generic tool for any Minecraft Java mod, `tools/importer.ts`, not one for Create. It converts one kind of resource at
|
||||||
|
a time, from a single file or a whole folder:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
deno run -A tools/importer.ts model MODEL.json --output PATH # one model, printed without --output
|
||||||
|
deno run -A tools/importer.ts model path/to/resources --output DIR # every assets/<namespace>/models in it
|
||||||
|
```
|
||||||
|
|
||||||
|
A folder can be a mod's whole resources, one `assets/<namespace>/models`, or a folder inside one, and the output keeps
|
||||||
|
the same folders. `--parents FOLDER` adds other resources to follow parents through (to tell sprites and OBJ models
|
||||||
|
apart), and `--remap FILE` renames locations before they become ids. Every kind reports what it converted, what it
|
||||||
|
skipped and why, and what's wrong, and exits with an error when anything is.
|
||||||
|
|
||||||
|
**Ids.** A resource location becomes a bworld id by joining its folders with `_`, the same rule `check-mods` uses for
|
||||||
|
textures in subfolders: `create:block/cogwheel` is `create:block_cogwheel`, for its model and its texture alike. It's a
|
||||||
|
pure function of the location, so every kind agrees on ids without sharing state: a blockstate pointing at a model
|
||||||
|
writes the same id the model was written with. Two locations that join to the same id are an error, fixed with
|
||||||
|
`--remap`.
|
||||||
|
|
||||||
|
**Remaps** are prefix rules, longest first, and a `skip` list of patterns for locations to leave out of every kind:
|
||||||
|
`{ "textures": { "minecraft:block/": "bworld:" }, "models": {}, "ids": {}, "tags": {} }`. The defaults map Minecraft's
|
||||||
|
block and item textures, its blocks and items (`ids`) and its tags to the base game's of the same name, and Forge's
|
||||||
|
shared tags to `c`, which is what bworld calls them. A mod's remap file is where its other vanilla ids go.
|
||||||
|
|
||||||
|
**Kinds:**
|
||||||
|
|
||||||
|
| Kind | Java | bworld | Status |
|
||||||
|
| ------------ | -------------------------------------------- | ----------------------------------------------------------------------- | ------ |
|
||||||
|
| `model` | `assets/*/models/**.json` | `models/`, parents kept, faces renamed, Blockbench extras dropped | Built |
|
||||||
|
| `texture` | `assets/*/textures/**.png` and `.png.mcmeta` | `textures/`, with animations | Built |
|
||||||
|
| `blockstate` | `assets/*/blockstates/*.json` | `blocks/*.json` with `variants` or `parts`, string states made numeric | Built |
|
||||||
|
| `item` | `assets/*/models/item/*.json` | `items/*.json` for items that aren't a block's, with their sprite | Built |
|
||||||
|
| `lang` | `assets/*/lang/en_us.json` | item and block names | |
|
||||||
|
| `recipe` | `data/*/recipe(s)/**.json` | `recipes/`: vanilla types to bworld's. Stonecutting and pressing so far | Built |
|
||||||
|
| `tag` | `data/*/tags/**.json` | `tags/`, Forge's shared tags as `c:`, missing entries optional | Built |
|
||||||
|
| `loot` | `data/*/loot_table(s)/**.json` | `drops`, or loot tables | |
|
||||||
|
| `worldgen` | `data/*/worldgen/**.json` | `worldgen/`: ores, and features where bworld has them | |
|
||||||
|
| `sound` | `assets/*/sounds.json`, `sounds/**.ogg` | sounds, once the engine has them (S8) | |
|
||||||
|
| `mod` | all of the above | a whole mod folder with a manifest, and one report | |
|
||||||
|
|
||||||
|
Block properties (shape, tool, toughness) aren't in any data file: Java mods set them in code. `blockstate` writes a
|
||||||
|
block for each blockstate with placeholder properties, and what a block really has, like its `components`, is written
|
||||||
|
into its file by hand after. The importer is a starting point, not something to run again over a mod that's been worked
|
||||||
|
on, since that would write over those changes.
|
||||||
|
|
||||||
|
**What `model` does today.** It keeps `parent`, since the engine merges parents in when it loads (see
|
||||||
|
[Parents](docs/modding/resources/models.md#parents)), and remaps it like any id. Minecraft's template parents (`cube`,
|
||||||
|
`cube_all`, `cube_column`, `orientable`, slabs, stairs, walls, glass panes) become the base game's models of the same
|
||||||
|
name in `mods/bworld/models/templates/`, and the default remap is read from that folder. A parent that holds nothing
|
||||||
|
bworld uses, like `block/block` (bworld has its own way of drawing blocks' items), is left out. It drops Blockbench's
|
||||||
|
extras and the `display` transforms of places bworld doesn't draw items (third person, the left hand, the head), keeps
|
||||||
|
every texture variable (some models draw faces with `#particle`), skips item sprites (`item/generated`) and `loader`
|
||||||
|
models (OBJ, composite) anywhere up a model's parents, and says why.
|
||||||
|
|
||||||
|
Run over Create 0.5.0.j's 2237 model files it converts 2091, and with its textures they make a mod `check-mods` accepts.
|
||||||
|
The rest are the 16 crimson and warped ones the remap file skips, 79 item sprites, 50 OBJ or composite models and one
|
||||||
|
with only third person transforms, and 3 name clashes were fixed with one remap line. Merged the way the game merges
|
||||||
|
them, the 2099 models with boxes come out identical to flattening them, and the files are 1.5 MB instead of 3.4 MB. 26
|
||||||
|
vanilla textures they use (pistons, redstone torches, rails) aren't in bworld yet.
|
||||||
|
|
||||||
|
**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
|
||||||
|
to the png, keeping only its `animation` section: bworld reads the same format. It checks every texture against the
|
||||||
|
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
|
||||||
|
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.
|
||||||
|
|
||||||
|
**What `blockstate` and `item` do today.** `blockstate` writes a block for each blockstate: each property becomes a
|
||||||
|
numbered state with the fewest bits that fit (booleans as false and true, facing as north, east, south, west, up and
|
||||||
|
down so a 2 bit facing still faces its placer), properties that never change the look (like `waterlogged`) are left out,
|
||||||
|
`variants` keep their models, `x` and `y` turns and `uvlock`, and a `multipart` becomes `parts`, one for each way a part
|
||||||
|
can be drawn. Blocks that aren't full cubes are `cutout`, or `translucent` when their model asks for it. A model that
|
||||||
|
can't be imported (OBJ, composite) is drawn as a placeholder cube. Every block gets the same placeholder mining (a
|
||||||
|
second, any tool) and drops itself, since Java mods set those in code. A block has an item when Java has an item model
|
||||||
|
for it, drawn with that model, or flat as its sprite. `item` writes the items that aren't a block's, with their sprite,
|
||||||
|
or with their model for the 9 Java draws in 3D from boxes (wrench, potato cannon, extendo grip), whose texture is the
|
||||||
|
model's `particle`. The empty blaze burner's model is OBJ, so it's flat.
|
||||||
|
|
||||||
|
`mods/create` is the result: 556 blocks and 81 items from 0.5.0.j (the crimson and warped windows are left out with the
|
||||||
|
remap file's `skip`) that can be placed and look like Create's, with no behavior. `check-mods` accepts it, warning only
|
||||||
|
about 31 vanilla textures bworld doesn't have yet. The 132 blockstates that use `uvlock` keep it.
|
||||||
|
|
||||||
|
**What `tag` and `recipe` do today.** Tags and recipes are checked against the mods next to `--output`, read the way
|
||||||
|
`check-mods` reads them. `tag` writes each item, block, entity and biome tag in bworld's format, which is Java's,
|
||||||
|
keeping folders in tag ids. An entry that doesn't exist here becomes optional (`required: false`), so the tag loads now
|
||||||
|
and picks it up once it's added, and what the remaps skip is left out. `recipe` converts each type bworld has an
|
||||||
|
equivalent for and reports the rest by type. A recipe naming an item or tag that doesn't exist here, or that only loads
|
||||||
|
under a condition (another mod installed), is skipped, since bworld's recipes have to be complete. So far
|
||||||
|
`minecraft:stonecutting` is converted to `bworld:stonecutting`, and `create:pressing` keeps its type in the shape in
|
||||||
|
[Recipes](#recipes), from 0.5's and 6.0's JSON alike.
|
||||||
|
|
||||||
|
Create 0.5.0.j's data gives 89 tags: 45 of Create's and 44 of Forge's shared ones, which are `c:` here. Fluid tags are
|
||||||
|
skipped. Of its 531 stonecutting recipes, 423 are converted. The other 108 cut granite, diorite, deepslate, calcite,
|
||||||
|
tuff and dripstone, which bworld doesn't have yet. Re-importing once it does brings them in. Of its 6 pressing recipes,
|
||||||
|
4 are converted, ingots into sheets. Sugar cane into paper and grass into dirt paths wait for those items.
|
||||||
|
|
||||||
|
**For Create**, `mods/create/import/` keeps the remap file, the block table and the commands. Re-running the import is
|
||||||
|
one command, and hand-written files are never in the folders it writes.
|
||||||
|
|
||||||
|
**Vanilla ids in recipes.** Create's recipes use 447 distinct Minecraft ids, like dyes, `minecraft:cobblestone` and
|
||||||
|
`minecraft:netherrack`. Each becomes the bworld id of the same name, or another with the remap file's `ids`. A recipe
|
||||||
|
using one bworld doesn't have is skipped and listed in the report, so the report always says how much of Create is
|
||||||
|
missing because bworld lacks something.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
How each of Create's shared pieces lands in bworld:
|
||||||
|
|
||||||
|
| Create | bworld |
|
||||||
|
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `SmartBlockEntity` and its `BlockEntityBehaviour`s | A block with several components. Each behaviour (filtering, scroll value, inventory, fluid tank, transported items) is one reusable `create:` component with params |
|
||||||
|
| `lazyTick` (every N ticks) | A counter in the component, or `on_second` |
|
||||||
|
| `sendData` / `getUpdateTag` | Client-visible tile data (R1) |
|
||||||
|
| `BlockEntityRenderer` and Flywheel `Visual`s | Block visuals (R2) drawing instances (R3) |
|
||||||
|
| `AllPartialModels` | Models in `models/` used by visuals, not blocks (R4) |
|
||||||
|
| `AllInstanceTypes`: rotating, scrolling, scrolling transformed, fluid | Engine instance types (R3) |
|
||||||
|
| `RotationPropagator`, `KineticNetwork` | `scripts/kinetics/` |
|
||||||
|
| NeoForge capabilities (`IItemHandler`, `IFluidHandler`) | Block capabilities (S1, S2) |
|
||||||
|
| `ProcessingRecipe` and its 19 types | Custom recipe types parsed in one place (`scripts/recipes/`) |
|
||||||
|
| `AbstractContraptionEntity`, `Contraption` | Engine block structure entities (S6) and the mod's assembly code |
|
||||||
|
| `AllPackets` | Mod channels |
|
||||||
|
| Menus and screens | Menus and screens, which bworld has |
|
||||||
|
| `AllConfigs` | `mods/create/config.json`, read in `setup` (S12) |
|
||||||
|
| Registrate, datagen | The importer |
|
||||||
|
| Mixins | Engine hooks, only where an engine feature isn't worth adding |
|
||||||
|
| Ponder | A scene player (P13) |
|
||||||
|
| `compat/jei` | Recipe viewer categories (R11) |
|
||||||
|
|
||||||
|
Server code is laid out by subsystem, each a folder with no `ctx` in its core logic so tests can call it directly:
|
||||||
|
|
||||||
|
```
|
||||||
|
mods/create/scripts/
|
||||||
|
server.ts shared.ts client.ts worldgen.ts
|
||||||
|
kinetics/ connections, spreading, stress, generators
|
||||||
|
processing/ press, mixer, millstone, crushing, saw, fan, deployer, crafter, basin, burner, sequenced assembly
|
||||||
|
logistics/ belts, funnels, tunnels, chutes, depots, arm, vaults, filters, packages
|
||||||
|
fluids/ pipes, pumps, tanks, spouts, drains, hose pulley, boilers
|
||||||
|
redstone/ links, nixie tubes, display links, diodes, observers
|
||||||
|
contraptions/ assembly, movement, actors, controls
|
||||||
|
trains/ track graph, signals, stations, schedules, train movement
|
||||||
|
equipment/ wrench, goggles, potato cannon, backtank, toolbox, symmetry wand
|
||||||
|
recipes/ parsing every Create recipe type
|
||||||
|
visuals/ client visuals for each block that moves
|
||||||
|
```
|
||||||
|
|
||||||
|
## Engine Work
|
||||||
|
|
||||||
|
Everything here is general, and none of it mentions Create. Each line says which phase first needs it.
|
||||||
|
|
||||||
|
### Rendering
|
||||||
|
|
||||||
|
**R1. Client-visible tile data** (P1, built). `block.set_client_data(field, value)` keeps a field of a block's data that
|
||||||
|
clients see too, apart from its server-only `data`. Players get every field with the chunk, then each field again when
|
||||||
|
it's set to something else, like NeoForge's `getUpdateTag` but per field, so a fast-changing field doesn't resend the
|
||||||
|
rest. It's saved, goes with the block, and client scripts read it with `ctx.world.get_client_data`. The display item is
|
||||||
|
its `item` field now, so there's one way to sync block data. R2's visuals will be told when a field changes.
|
||||||
|
|
||||||
|
**R2. Block visuals** (P1, built). `ctx.render.register_visual(block_id, create, { replaces_model })` in client scripts,
|
||||||
|
like Flywheel's `Visual`. The chunk mesher lists the blocks with visuals in each chunk it meshes, and leaves out the
|
||||||
|
models of the ones whose visual replaces it, like `ENTITYBLOCK_ANIMATED`. A visual is made from that list, `update`d
|
||||||
|
when a client data field changes, made again when the block's states change, and deleted with the block or chunk. It
|
||||||
|
draws `rotating` and `transformed` instances of its block's model or of any model in `models/` by id, turned like a
|
||||||
|
variant. A visual that has to move on the CPU (a crank easing in, a press head) gets `on_frame`, like `DynamicVisual`.
|
||||||
|
Visuals are kept per chunk, and only the ones in chunks in view get `on_frame`.
|
||||||
|
|
||||||
|
**R3. Instanced drawing** (P1, `transformed`, `rotating`, `fluid` and items built). A WebGPU pipeline that draws one
|
||||||
|
model many times from an instance buffer (`vs_instance` in `client/renderer/core.ts`, cut out like cutout terrain). The
|
||||||
|
instance types, matching Create's:
|
||||||
|
|
||||||
|
| Type | Per instance | Shader |
|
||||||
|
| ------------- | ------------------------------------------ | ----------------------------------------------------------------------- |
|
||||||
|
| `transformed` | a matrix, light, tint | moves the model |
|
||||||
|
| `rotating` | position, axis, rpm, offset, light, tint | turns the model around its axis by `ticks × rpm × 0.3 + offset` degrees |
|
||||||
|
| `scrolling` | position, rotation, uv scroll speed, light | scrolls the texture coordinates, for belts |
|
||||||
|
| `fluid` | box, fluid texture, fill, light | a box of a fluid's texture, for tanks and pipes |
|
||||||
|
|
||||||
|
Instances are grouped by model and type, and each group is one draw call. Light is packed per instance from the block's
|
||||||
|
light, updated when that light changes. `rotating` is the important one: thousands of shafts at a steady speed cost
|
||||||
|
nothing per frame. See `ports/sodium` for how to keep buffer updates cheap.
|
||||||
|
|
||||||
|
As built, `transformed` and `rotating` share one instance layout (a placement matrix, an axis, rpm, offset and light, 96
|
||||||
|
bytes): a rotating instance is placed at its block and spins, a transformed one is placed by its matrix and doesn't. So
|
||||||
|
instances are grouped by model alone. Each group keeps its instances on the CPU too, changes them there, and writes the
|
||||||
|
range from the first changed instance to the last once a frame. A deleted instance's place is taken by the last one, so
|
||||||
|
a group's instances are always its first ones. Light comes with each chunk mesh. Every instance is drawn each frame,
|
||||||
|
with no culling by chunk, since a draw call per model is cheaper than one per model per chunk until there are far more
|
||||||
|
instances than P1 has. Faces are shaded on the GPU by the way they face after turning. `scrolling` comes with belts
|
||||||
|
(P4).
|
||||||
|
|
||||||
|
`fluid` is built apart from the table: each box is a model of its own, built on the CPU when its box is set, cut into a
|
||||||
|
piece per block it crosses so the texture is never stretched, like Create's `renderTiledFace`, and tinted in its fluid's
|
||||||
|
color. It's one draw call per box, drawn blended after the other instances and back to front. Items are transformed
|
||||||
|
instances too, of a model built once from what an item draws, one per way an item looks (its id, texture and layer
|
||||||
|
colors), so a belt of one item is one draw call.
|
||||||
|
|
||||||
|
**R4. Models without blocks** (P1). Any model in `models/` can be loaded by id for visuals, baked once into a GPU
|
||||||
|
buffer, and turned for whatever axis it's used on. Built: each model is baked the first time a visual uses it and
|
||||||
|
uploaded the first time it's drawn, once per level. Every model is packed and sent to clients whether a block uses it or
|
||||||
|
not, and the partials P1's visuals use are all imported with their textures: `shaft`, `shaft_half`, `cogwheel_shaft`,
|
||||||
|
`cogwheel_shaftless`, `large_cogwheel_shaftless`, `hand_crank/handle`, `gauge/dial`, `gauge/indicator`, both gauge heads
|
||||||
|
and `rotation_speed_controller/bracket` (as `create:block_shaft_half` and so on). 0.5.0.j's water wheel is its block's
|
||||||
|
own model. 6.0's wheels that take the wood they're made of swap the oak textures in their model, which needs their new
|
||||||
|
art and a texture override on a model reference, so it waits for that art.
|
||||||
|
|
||||||
|
**R5. The model format** (P0, built). Everything Create's static models use: `parent`, `x` turns, `uvlock` on variants
|
||||||
|
and parts, element `rotation` at any angle around one axis, and items drawn with models. An item's `model` draws it in
|
||||||
|
3D like a block's `item_model`, and a model's `display` places it in slots, in the hand, on the ground and on blocks
|
||||||
|
(`gui`, `firstperson_righthand`, `ground`, `fixed`) from the same starting places as Minecraft's, so Create's transforms
|
||||||
|
look the same. The wrench, potato cannon and extendo grip are drawn with theirs. Third person and left hand transforms
|
||||||
|
are dropped until bworld draws items there.
|
||||||
|
|
||||||
|
**R6. Connected textures** (P2). Create's casings, windows and vaults pick a tile from a sheet depending on which
|
||||||
|
neighbours are the same block (`foundation/block/connected/`: rectangle, horizontal, vertical and omni). It's done in
|
||||||
|
the chunk mesher, from a `connected` field on a block's textures that names the sheet and the kind. Generic: any mod's
|
||||||
|
glass can use it.
|
||||||
|
|
||||||
|
**R7. Block structure rendering** (P7). A contraption's blocks are meshed once by the chunk worker, as a small chunk of
|
||||||
|
their own, and drawn with the contraption's matrix each frame. Its moving parts (a drill on it, a bearing's shaft) are
|
||||||
|
instances drawn relative to it. A block change on it remeshes only it.
|
||||||
|
|
||||||
|
**R8. Render time** (P1, built). World ticks plus the partial tick, as a shader uniform and for client scripts. It's
|
||||||
|
`ClientLevel.ticks`, which doesn't jump with `/time`. Visuals get it in `on_frame`, and the shaders as `uniforms.time`
|
||||||
|
(`set_render_time`), wrapped every 24000 ticks so a 32 bit float stays precise. That's a whole number of turns at any
|
||||||
|
speed in steps of 0.05 rpm, so those don't jump when it wraps.
|
||||||
|
|
||||||
|
**R9. Particles** (P3). A simple GPU particle system: sprite, velocity, gravity, lifetime. Used for rotation indicators,
|
||||||
|
crushing, fan processing, steam, fluid splashes. Optional for gameplay, so it can come late.
|
||||||
|
|
||||||
|
**R10. In-world text and boxes** (P3). Create's value boxes (the number on a scroll value, filter slots on a block's
|
||||||
|
side) and goggles' overlay. A small API for drawing a label or an item at a point in the world, and a HUD element API,
|
||||||
|
which is in bworld's types but throws today. Setting a scroll value is built, the way 0.5.0.j does it: a block with
|
||||||
|
`"scrollable": true` gets the mouse wheel as `on_scroll`, and `send_message(text, { overlay: true })` shows the value
|
||||||
|
above the hotbar until the box can show it (see [Scrolling](docs/modding/blocks/components.md#scrolling)).
|
||||||
|
|
||||||
|
**R11. 3D in GUIs** (P3). Drawing a model or block in a screen, turned and animated, for the recipe viewer's Create
|
||||||
|
categories (a press pressing over its recipe, like `compat/jei`), goggles and ponder.
|
||||||
|
|
||||||
|
### Server and Gameplay
|
||||||
|
|
||||||
|
**S0. Ticking only what ticks** (P1, built). `ServerWorld` keeps the tiles that tick per chunk, so `GameServer.tick`
|
||||||
|
only looks at the chunks near players instead of every tile in the world. A component turns ticking off and on for one
|
||||||
|
block with `block.set_ticking(false)`, or `ctx.world.set_block_ticking(x, y, z, true)` from elsewhere, like returning no
|
||||||
|
ticker in NeoForge, and it stays off through saving. A shaft has tile data and never ticks. A press only ticks while
|
||||||
|
pressing.
|
||||||
|
|
||||||
|
**S1. Block capabilities** (P3). `ctx.capabilities.register_block("items", block_id, (block, side) => handler)` and
|
||||||
|
`ctx.world.capability("items", x, y, z, side)`, like NeoForge's `BlockCapability`. Handlers insert, extract, report
|
||||||
|
slots, and simulate. Chests and furnaces get them in `mods/bworld`. Funnels, chutes, arms, deployers, belts and vaults
|
||||||
|
all move items only through this.
|
||||||
|
|
||||||
|
**S2. Fluids** (P5). A fluid registry (bworld's water and lava, plus mods' own like Create's honey and chocolate), fluid
|
||||||
|
stacks with amounts in millibuckets, a `"fluids"` capability, and fluid containers in items (buckets, bottles).
|
||||||
|
|
||||||
|
**S3. Redstone** (P6, or earlier for clutches). A signal API in the engine (each block side has a power level 0 to 15,
|
||||||
|
`get_signal`, `has_neighbor_signal`, updates to neighbours) and the basic blocks in `mods/bworld`: lever, button, dust,
|
||||||
|
torch, repeater, comparator, lamp. Create reads and makes signals in about 40 blocks, and bworld has no redstone at all
|
||||||
|
today.
|
||||||
|
|
||||||
|
**S4. Machines acting on the world** (P3, built).
|
||||||
|
|
||||||
|
- `fluid_flow(x, y, z)` (wraps `common/physics.ts`), for water wheels and fans.
|
||||||
|
- Item entities in a box, which can be changed and removed, for the press, fans and belts picking items up.
|
||||||
|
- Pushing entities, for fans.
|
||||||
|
- Breaking a block over time with progress shown, and its drops, for drills and saws.
|
||||||
|
- A fake player using an item on a block, for the deployer (`DeployerFakePlayer`).
|
||||||
|
|
||||||
|
As built, all in `ctx.world` (see the modding docs for each): `fluid_flow`, `entities_in(from, to, type?)` with
|
||||||
|
`EntityRef.get_item`, `set_item`, `velocity` and `push`, `spawn_item` for an item lying still where it's put (the
|
||||||
|
press's extra results), and `player.push`, which is sent to their client since it moves them. `set_break_progress` shows
|
||||||
|
cracks to the players who have the chunk, sending only a change of stage, and `ctx.blocks.toughness` gives what breaking
|
||||||
|
time is measured against. `break_block` takes `harvest` (drops what the right tool would, like
|
||||||
|
`BlockHelper.destroyBlockAs` ignoring tool requirements) and `collect` (returns the drops without dropping them), and
|
||||||
|
returns the drops. `use_item_on(item, x, y, z, face)` runs a player's whole right click (the block's `on_interact`, the
|
||||||
|
item's `on_use`, placing) as one `[machine]` player that's never online, standing in front of the face, and returns what
|
||||||
|
it holds after and anything it was given. The deployer's left click (punching and breaking) isn't there yet, and neither
|
||||||
|
is a fan pushing players on their client every tick, which Create does on both sides.
|
||||||
|
|
||||||
|
**S5. Scripted entities** (P7). Mods can define an entity's behaviour in server scripts (tick, data, interaction) and
|
||||||
|
how it's drawn in client scripts. Needed for the contraption entity, seats, potato cannon projectiles, trains and
|
||||||
|
packages.
|
||||||
|
|
||||||
|
**S6. Block structure entities** (P7). An entity that carries a grid of blocks with their states and tile data, moved
|
||||||
|
and turned as a whole: assembled from the world and put back, saved, and synced. Players and mobs stand on it and bump
|
||||||
|
into it as it moves (Create's `ContraptionCollider`, about 1000 lines, is the hardest part), and they can point at and
|
||||||
|
use its blocks. Generic: boats with decks, falling structures and elevators would all use it.
|
||||||
|
|
||||||
|
**S7. Player API additions** (P1, built). `player.is_sneaking()` on the server and in client scripts, and `sneaking` in
|
||||||
|
placement and interaction rules, for blocks like `DirectionalKineticBlock` that sneaking places the other way round.
|
||||||
|
Like Minecraft's secondary use, sneaking with an item in hand skips the clicked block's interactions and uses or places
|
||||||
|
the item, and an item's `on_use` gets the block it was used on, for the wrench's pickup. Reach is the
|
||||||
|
`cubi:block_interaction_range` and `cubi:entity_interaction_range` attributes, which clients aim with, so the extendo
|
||||||
|
grip is a modifier while it's held. `player.start_using(ticks)` uses an item over time, with `on_use_tick`,
|
||||||
|
`on_release_using` and `on_finish_using`, for the sand paper, builder's tea and packages. The potato cannon and wands
|
||||||
|
are plain uses, but their reload needs item cooldowns (Minecraft's `getCooldowns`, shown on the hotbar), which aren't
|
||||||
|
built.
|
||||||
|
|
||||||
|
**S8. Sound** (P3). Web Audio, positional, with sound events defined in data. bworld has no sound at all yet. Create's
|
||||||
|
whistles, presses, cranks and trains want it, but nothing breaks without it.
|
||||||
|
|
||||||
|
**S9. More recipe types in bworld** (P0). `shapeless` crafting (Create's cogwheels and many others), stonecutting
|
||||||
|
(palettes have hundreds of stonecutting recipes, and the mechanical saw uses them), and smoking and blasting for fans.
|
||||||
|
Stonecutting is built, as `bworld:stonecutting` with the stonecutter, and the saw reads the same recipes with
|
||||||
|
`ctx.recipes.list("bworld:stonecutting")`.
|
||||||
|
|
||||||
|
**S10. Block shape families in bworld** (P10). Stairs, slabs and walls don't exist in bworld yet, and Create's palettes
|
||||||
|
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
|
||||||
|
`mods/create/scripts/worldgen.ts`, or a data feature if those exist by then. Zinc is a plain ore in `ores.json`.
|
||||||
|
|
||||||
|
**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
|
||||||
|
`server_mods/`, setting by setting, and a setting the mod doesn't have or a value of the wrong kind stops it from
|
||||||
|
starting. Players' copies of a mod leave the config out, so what clients need is sent like any other server data. Tests
|
||||||
|
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.
|
||||||
|
|
||||||
|
**S13. NBT** (P11). Reading and writing structure NBT, for schematics and ponder scenes.
|
||||||
|
|
||||||
|
**S14. Uploading files** (P11). A client sending a file to the server in pieces over a mod channel, for schematics.
|
||||||
|
|
||||||
|
## Recipes
|
||||||
|
|
||||||
|
All 19 of Create's types, plus the vanilla types its data uses:
|
||||||
|
|
||||||
|
| Type | Count | Made by | Phase |
|
||||||
|
| ----------------------------------------------------- | ----- | ------------------------------------------- | ----------------------- |
|
||||||
|
| `crafting` (shaped/shapeless) | 369 | crafting grid | P0 |
|
||||||
|
| `stonecutting` | 327 | stonecutter (S9), mechanical saw | P3 |
|
||||||
|
| `smelting`, `blasting`, `smoking`, `campfire_cooking` | 64 | furnace, fans | P3 |
|
||||||
|
| `pressing` | 43 | mechanical press | P3 |
|
||||||
|
| `milling` | 246 | millstone | P3 |
|
||||||
|
| `crushing` | 211 | crushing wheels | P3 |
|
||||||
|
| `cutting` | 32 | mechanical saw | P3 |
|
||||||
|
| `splashing`, `haunting` | 73 | encased fan through water or soul fire | P3 |
|
||||||
|
| `deploying` | 167 | deployer | P3 |
|
||||||
|
| `item_application` | 8 | using an item on a block | P3 |
|
||||||
|
| `sandpaper_polishing` | 1 | sand paper | P3 |
|
||||||
|
| `mixing`, `compacting` | 21 | mixer and press over a basin | P3 (items), P5 (fluids) |
|
||||||
|
| `mechanical_crafting` | 4 | mechanical crafters | P3 |
|
||||||
|
| `sequenced_assembly` | 3 | belts with presses, deployers, spouts, saws | P4 |
|
||||||
|
| `filling`, `emptying` | 24 | spout, item drain | P5 |
|
||||||
|
| `toolbox_dyeing`, `item_copying`, `conversion` | — | built-in, special | P9 |
|
||||||
|
|
||||||
|
Create's own types keep Create's shape inside bworld's envelope, but with bworld's item choices (an id, a `#tag`, or a
|
||||||
|
list of those any of which fits) in place of Java's `{ item }` and `{ tag }`, like every other recipe here:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"format_version": 1,
|
||||||
|
"recipe": {
|
||||||
|
"type": "create:pressing",
|
||||||
|
"ingredients": ["#c:ingots/iron"],
|
||||||
|
"results": [{ "id": "create:iron_sheet", "count": 1 }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`scripts/recipes/` parses all of them in one place: ingredients as item choices, or sized fluid ingredients; results as
|
||||||
|
`{ id, count, chance }` or fluid stacks; `processing_time` and `heat_requirement`. Built for pressing and compacting,
|
||||||
|
with fluid results as `{ fluid, amount }` but no fluid ingredients, durations or heat yet, in
|
||||||
|
`scripts/recipes/processing.ts`, which the server script runs in `setup`. It checks each type's input and output limits,
|
||||||
|
which come from each recipe class's `getMaxInputCount` and `getMaxOutputCount`. The recipe viewer gets one reader for
|
||||||
|
this shape, so every Create type shows with no per-type code, and animated categories (R11) are added per machine on
|
||||||
|
top.
|
||||||
|
|
||||||
|
## Kinetics
|
||||||
|
|
||||||
|
The core of everything, so its rules are written out here.
|
||||||
|
|
||||||
|
**What turns.** One component, `create:kinetic`, with params for which state holds the axis (`axis`, `facing`,
|
||||||
|
`horizontal_facing`), which ends have an axle, whether it's a small or large cog, and its stress impact. Generators add
|
||||||
|
`create:generator` with a capacity. Special connections (gearbox, chain drive, belt, speed controller) are named
|
||||||
|
handlers in `kinetics/connections.ts`.
|
||||||
|
|
||||||
|
**Connections**, with the ratio speed is multiplied by on the way across:
|
||||||
|
|
||||||
|
| Pair | Where | Ratio |
|
||||||
|
| -------------------- | --------------------------------------------------------------------------------- | ------------------------ |
|
||||||
|
| Axle to axle | Face neighbours along the axis, both with an axle toward each other | 1 |
|
||||||
|
| Small cog, small cog | Face neighbours, same axis, not along it | −1 |
|
||||||
|
| Large cog to small | Same axis, level along it, ±1 on both other axes | −2 (−0.5 the other way) |
|
||||||
|
| Large cog, large cog | Different axes, ±1 along both their axes, 0 on the third | ±1 by the offsets' signs |
|
||||||
|
| Gearbox | Turns each side, reversing by side, see `getAxisModifier` in `RotationPropagator` | ±1 |
|
||||||
|
| Chain drive | Along a line of chain drives, with the adjustable one's ratio | per block |
|
||||||
|
| Belt | Every segment of a belt turns with its two ends | 1 |
|
||||||
|
|
||||||
|
A large cog also looks at the 12 blocks diagonal to it along an edge. Cog placement rules (no large cog face to face
|
||||||
|
with any cog off its axis) and the axis a cog picks when placed are in `CogWheelBlock`.
|
||||||
|
|
||||||
|
**Spreading.** When a kinetic block is placed or a generator's speed changes, its speed spreads to what it's connected
|
||||||
|
to. If a neighbour already turns the other way, or the speed passes 256 rpm, the changed block breaks. A faster
|
||||||
|
neighbour takes over this block, and a faster block takes over its neighbour's tree. In a loop, a speed that doesn't
|
||||||
|
match breaks the block. Removing a block clears the tree it was the source of and spreads again from what's left powered
|
||||||
|
at its edge. Both walks use a queue, not recursion. Rules from `RotationPropagator`.
|
||||||
|
|
||||||
|
**Stress.** A network's capacity is the sum of each generator's capacity × |rpm|, and its stress the sum of each block's
|
||||||
|
impact × |rpm|. When stress is more than capacity, every block in it acts still and is drawn still. The network is found
|
||||||
|
by walking connections when something changes, never per tick. Values come from `BlockStressValues` and config defaults,
|
||||||
|
into `config.json`.
|
||||||
|
|
||||||
|
**What the client gets.** Each kinetic block's rpm and whether its network is overstressed, in client data (R1). Its
|
||||||
|
visual makes a `rotating` instance with the axis, rpm and an offset that keeps cog teeth meshed. The offset is 22.5°
|
||||||
|
when the block's coordinates on the two axes that aren't its axis add up to an even number, otherwise 11.25° for large
|
||||||
|
cogs and 0 for the rest. A speed change updates one instance, and nothing else happens per frame.
|
||||||
|
|
||||||
|
**As built** (`scripts/kinetics/`: the shaft, both cogwheels and the hand crank). `create:kinetic` takes `axis` (the
|
||||||
|
state with x, y or z) or `facing` (the state with the 6 faces), `shaft` (`both`, `front` or `back`) and `cog` (`small`
|
||||||
|
or `large`), and its shared rules place blocks like `RotatedPillarKineticBlock`, `DirectionalKineticBlock` and
|
||||||
|
`CogWheelBlock`, lining up with an axle or cog beside them. A cog that would cut into another isn't placed, like
|
||||||
|
`isValidCogwheelPosition`, by `state_for_placement` returning `false`. Connections are the table's first four rows.
|
||||||
|
Spreading is `RotationPropagator`'s, with queues: a block's speed is its `speed` client data, and the block it gets it
|
||||||
|
from and the generator it comes from (`source` and `network`) are tile data. Two things differ: on_break runs while the
|
||||||
|
block is still there, so the walk after a removal treats its place as empty, and generators that stop with what turned
|
||||||
|
them start again right after the walk instead of a tick later (`reActivateSource`). Create's flicker score and its
|
||||||
|
periodic `validateKinetics` aren't ported, since shafts don't tick. `create:hand_crank` turns while it's clicked, for 10
|
||||||
|
ticks after each click, the other way while sneaking, and costs hunger by the config's `crank_hunger`. Its visual turns
|
||||||
|
the half shaft as a `rotating` instance and eases the handle in `on_frame`, like `HandCrankVisual`. A large cog is drawn
|
||||||
|
as its shaftless model and a separate shaft, offset apart, like `LargeCogVisual`. The crank doesn't pop off when its
|
||||||
|
block is taken away yet, and cogs have no placement helper (`CogwheelBlockItem`'s ghost offsets). It needed four engine
|
||||||
|
additions: `looking` in `state_for_placement` (`getNearestLookingDirection`), `false` from it to not place
|
||||||
|
(`getStateForPlacement` returning null), `ctx.blocks` in shared scripts, and `ctx.world.get_block_ref` for changing
|
||||||
|
another block's data (`getBlockEntity`).
|
||||||
|
|
||||||
|
**Stress as built** (`scripts/kinetics/stress.ts`). Impacts and capacities are the config's `stress.impact` and
|
||||||
|
`stress.capacity` by block id, like `CStress`, with Create's values for the blocks built so far, and 0 for a block that
|
||||||
|
isn't listed. A network is the blocks whose `network` is the same generator. Each change in `spreading.ts` notes the
|
||||||
|
networks it touched, and then each of them is walked from its generator and summed. Every block in one that's
|
||||||
|
overstressed gets `overstressed` client data, which `actual_speed` in `connections.ts` reads as still, for the press and
|
||||||
|
for visuals, like `getSpeed`. Speeds and spreading are unchanged by it. The totals aren't kept, since only the
|
||||||
|
stressometer will show them. Both a second generator joining a network and one in it stopping change its capacity
|
||||||
|
without changing any speed, so a generator's change always reworks its network.
|
||||||
|
|
||||||
|
**Generators as built** (`scripts/kinetics/generators.ts`). Each is a component with its speed in params, and a capacity
|
||||||
|
in the config. `create:creative_motor` turns from when it's placed, at a speed kept in its tile data. Scrolling the
|
||||||
|
mouse wheel at it (the block is `scrollable`, so it gets `on_scroll`) steps through speeds like 0.5's motor: by 1 near
|
||||||
|
0, then by 4, 16 and 64, by 1 while sneaking, skipping 0, within `max_speed`, and the speed shows above the hotbar.
|
||||||
|
Scrolling works anywhere on the block, not only on a value box, and there's no settings board like 6.0's. Its casing is
|
||||||
|
the block's model and its half shaft turns. `create:water_wheel` scores the fluid flowing past the 4 blocks around it
|
||||||
|
across its axis with `fluid_flow`, like `determineAndApplyFlowScore`, and turns at its speed whichever way the score
|
||||||
|
says. It scores again a tick after a neighbour changes, and every second for flow that changes without that (Create does
|
||||||
|
it every 3 seconds), so a wheel ticks once a second. It can't be placed beside another wheel unless they share an axle,
|
||||||
|
like `canSurvive`. The large water wheel isn't built, and neither is changing a wheel's planks.
|
||||||
|
|
||||||
|
**Transmission as built** (`connections.ts`, `chains.ts`). All of it is `create:kinetic` params, so the rules are data
|
||||||
|
and one function, `speed_ratio`, which takes the table's gearbox and chain drive rows now. `gearbox` puts an axle on the
|
||||||
|
4 sides around its axis, and `split` (`clutch` or `gearshift`) with `powered` names a 1 bit state. Both turn their axles
|
||||||
|
by `axis_modifier`, from the side their speed comes from (`getAxisModifier`), which the server keeps in their `source`
|
||||||
|
client data for their visuals' half shafts. A gearbox reverses what goes straight through it, like Create's. The clutch
|
||||||
|
and gearshift are powered by verdigris through `bworld:verdigris_input`, and any change to a kinetic block's states that
|
||||||
|
changes how it turns takes it out of its network and puts it back, like `areStatesKineticallyEquivalent` with
|
||||||
|
`detachKinetics` (straight away rather than a tick later). The vertical gearbox is an item that `places` the gearbox,
|
||||||
|
whose placing rule stands it on its side when `placement.item` is the vertical gearbox, and a loot table gives back the
|
||||||
|
item it was. Encased shafts are the shaft's rule with a casing model. Encased cogs are cogs with `shaft_states`, the 1
|
||||||
|
bit states for an axle out of each end. They have no item, like Create's: `create:encasable` on shafts and cogs turns
|
||||||
|
one right clicked with a casing into the encased one, keeping its axis, with an axle toward each axle beside it, and
|
||||||
|
both break into what was encased. Turning one back with a wrench waits for the wrench (P9). `chain` names a chain
|
||||||
|
drive's `part` and `axis_along_first` states, which `chain_update` keeps up to date on placing and on neighbour changes,
|
||||||
|
like `updateShape`. The adjustable chain gearshift also names a 4 bit `power` state, which the verdigris input fills
|
||||||
|
with how much power goes into it, for `chain_ratio`. The metal girder encased shaft waits for girders (P10).
|
||||||
|
|
||||||
|
**Chunk borders.** Tile data keeps speeds across unloading. bworld keeps every tile in memory and reloads a chunk when a
|
||||||
|
block in it is read, so the walk sees a whole network, and Create's separate count of unloaded members' stress
|
||||||
|
(`KineticNetwork`'s unloaded stress) isn't needed.
|
||||||
|
|
||||||
|
## Phases
|
||||||
|
|
||||||
|
Each phase ends with every test passing and something to see and use in a world. Engine work (R and S) is listed where
|
||||||
|
it's first needed.
|
||||||
|
|
||||||
|
### P0: Importer and Skeleton
|
||||||
|
|
||||||
|
- S9 (`shapeless`), R5.
|
||||||
|
- The importer's other kinds, up to `mod`, and Create's remap file and block table in `mods/create/import/`.
|
||||||
|
- `mods/create` with every block and item imported, static models, names, recipes that only need crafting, tags.
|
||||||
|
|
||||||
|
Check: every Create block can be placed and looks right standing still, crafting recipes work, and the report lists
|
||||||
|
what's missing.
|
||||||
|
|
||||||
|
### P1: Kinetics
|
||||||
|
|
||||||
|
- S0, S7, S12, R1, R2, R3 (`transformed` and `rotating`), R4, R8.
|
||||||
|
- Shaft, cogwheel, large cogwheel, gearbox, vertical gearbox, encased shafts and cogs, clutch and gearshift (with a
|
||||||
|
placeholder signal until S3), chain drive and adjustable chain gearshift, rotation speed controller, speedometer and
|
||||||
|
stressometer.
|
||||||
|
- Generators: hand crank, valve handle, water wheel, large water wheel, creative motor.
|
||||||
|
- Kinetic network, stress and overstress.
|
||||||
|
|
||||||
|
Check: a water wheel drives a long shaft line through gearboxes and cog ratios, all turning smoothly on the GPU, and
|
||||||
|
1000 shafts cost nothing per frame and only a little per tick.
|
||||||
|
|
||||||
|
### P2: Materials and World
|
||||||
|
|
||||||
|
- S11, R6.
|
||||||
|
- Zinc ore, striated stone bands, andesite alloy, brass (made in P3's mixer), casings with connected textures.
|
||||||
|
|
||||||
|
Check: new worlds have zinc and Create's stones, and casings join up.
|
||||||
|
|
||||||
|
### P3: Processing
|
||||||
|
|
||||||
|
- S1, S4, S8, R9, R10, R11, and smoking and blasting from S9.
|
||||||
|
- Mechanical press, millstone, crushing wheels, mechanical saw, encased fan with its processing (washing, smoking,
|
||||||
|
blasting, haunting from `AllFanProcessingTypes`), deployer, mechanical crafters, item application, sand paper, depot,
|
||||||
|
basin, mixer and compacting (items only), blaze burner and its heat.
|
||||||
|
- Recipe viewer: Create's recipe format, catalysts, and animated categories.
|
||||||
|
|
||||||
|
Check: ores go through crushing, washing and smelting into more ingots than a furnace alone gives, and brass is mixed in
|
||||||
|
a heated basin.
|
||||||
|
|
||||||
|
As built so far: the mechanical press, pressing items lying on the ground under it (`PressingBehaviour`'s world mode, in
|
||||||
|
`scripts/processing/press.ts` and the server script). While it turns it looks for an item with a pressing recipe every
|
||||||
|
10 ticks, then runs its 240 step cycle at Create's speed for its rpm and presses at the bottom: a lone item turns into
|
||||||
|
its result, and from a stack one is pressed and its results land beside it, like `bulkPressing` off. It stops ticking
|
||||||
|
while it's still, and a kinetic block that starts turning ticks again. Clients get the step the cycle was at and its
|
||||||
|
rate as `press` client data whenever the rate changes, and the visual moves the head from those, so nothing is sent
|
||||||
|
while it runs at a steady speed. Pressing on belts, depots and basins, its stress impact, sound and particles come with
|
||||||
|
those.
|
||||||
|
|
||||||
|
The basin (`scripts/processing/basin.ts`) holds what Create's input inventory and tanks do: up to 9 kinds of item, a
|
||||||
|
stack of each, and 2 tanks of 1000 mB, a fluid each. An item that lands in it goes in through the engine's
|
||||||
|
`on_entity_stand`, like `updateEntityAfterFallOn`, so it doesn't tick. A full fluid container used on it empties into
|
||||||
|
it, an empty one fills from its first tank, and an empty hand takes every item out, like `BasinBlock.useItemOn`. What's
|
||||||
|
in it is only its `items` and `tanks` client data, and its visual draws them like `BasinRenderer`: the fluids side by
|
||||||
|
side, filling faster at first, and the items in a ring over them, bobbing while there's fluid. Water and lava buckets
|
||||||
|
aren't fluid containers in bworld, so they don't fill it yet. Its facing toward an output, and the item and fluid
|
||||||
|
capabilities (S1, S2), come with mixing and the logistics that move things in and out. For it the engine got
|
||||||
|
`on_entity_stand`, and an item inside a block only floats out of it when it's inside what it bumps into, like
|
||||||
|
Minecraft's `noCollision`, so items can lie in a hollow.
|
||||||
|
|
||||||
|
A press with a basin two blocks under it presses into the basin instead of on the ground, its head coming 22/16 of a
|
||||||
|
block down, like `PressingBehaviour`'s basin mode. Each cycle it makes the first `create:compacting` recipe that can be
|
||||||
|
made there, the ones with more ingredients first, like `BasinOperatingBlockEntity.getMatchingRecipes`, and it only
|
||||||
|
starts one when a recipe can be made. `apply_basin_recipe` in `processing/basin.ts` is `BasinRecipe.apply`: an item for
|
||||||
|
each ingredient from the basin's input items, item results into its outputs, which recipes don't take again, and fluid
|
||||||
|
results into its tanks, all or nothing. Outputs are its `outputs` client data, drawn and taken out by hand with the
|
||||||
|
rest. Unlike Create's, its input and output tanks are the same 2, since no recipe takes fluids yet. bworld's shared
|
||||||
|
script makes a compacting recipe for every juicing recipe while Create's press and basin are there, so the press makes
|
||||||
|
juice. Create's own 7 compacting recipes need fluid ingredients or Minecraft items, and aren't imported yet.
|
||||||
|
|
||||||
|
### P4: Logistics
|
||||||
|
|
||||||
|
- R3's `scrolling` type.
|
||||||
|
- Belts. A belt is a line of segments, and only its controller (its first segment) ticks, moving every item on it
|
||||||
|
(`BeltInventory`), like `BeltBlockEntity.isController`. Items on belts are instances drawn by the controller's visual.
|
||||||
|
- Funnels, brass and andesite tunnels, chutes and smart chutes, mechanical arm, item vaults (multiblock), filters and
|
||||||
|
attribute filters, sequenced assembly on belts.
|
||||||
|
|
||||||
|
Check: a sorting line with funnels, filters and an arm, and a precision mechanism made by sequenced assembly.
|
||||||
|
|
||||||
|
### P5: Fluids
|
||||||
|
|
||||||
|
- S2, R3's `fluid` type.
|
||||||
|
- Fluid pipes, encased and glass pipes, mechanical pump, fluid tanks (multiblock), spout, item drain, hose pulley,
|
||||||
|
portable fluid interface, basins with fluids, mixing and compacting with fluids, filling and emptying.
|
||||||
|
- Pipes are networks found by walking pipes from a pump when something changes (`FluidPropagator`, `FluidNetwork`).
|
||||||
|
Fluid only moves while a pump runs, and a network with no running pump doesn't tick.
|
||||||
|
- Steam engine and boilers on tanks (`BoilerData`), which are fluids plus heat plus kinetics.
|
||||||
|
|
||||||
|
Check: a steam engine on a tank boiler, fed by a pump from water and heated by blaze burners, drives a factory.
|
||||||
|
|
||||||
|
### P6: Redstone
|
||||||
|
|
||||||
|
- S3, in `mods/bworld` first.
|
||||||
|
- Redstone link, nixie tube, display link and display board, threshold switch, smart observer, analog lever, pulse
|
||||||
|
extender and timer, powered latch and toggle latch, contact, desk bell, sequenced gearshift. The pulse repeater is
|
||||||
|
bworld's now. Clutch and gearshift switch to real signals.
|
||||||
|
|
||||||
|
Check: a factory that stops when a vault is full and shows its count on a display board.
|
||||||
|
|
||||||
|
### P7: Contraptions
|
||||||
|
|
||||||
|
- S5, S6, R7.
|
||||||
|
- Mechanical bearing, windmill bearing with sails, clockwork bearing, mechanical piston, rope pulley, elevator pulley
|
||||||
|
and contacts, gantry carriage, linear and radial chassis, super glue, contraption controls.
|
||||||
|
- Actors, which act as their contraption moves (`AllMovementBehaviours`): drill, saw, harvester, plough, roller,
|
||||||
|
deployer, seats, storage, portable interfaces.
|
||||||
|
- Minecart contraptions need minecarts and rails, which bworld doesn't have. They wait until bworld has them, and the
|
||||||
|
cart assembler with them.
|
||||||
|
|
||||||
|
Check: a windmill turns, a drill on a piston mines a wall, and a player rides an elevator.
|
||||||
|
|
||||||
|
### P8: Trains
|
||||||
|
|
||||||
|
- Train tracks and curved tracks, which are drawn as meshes made along their curves, not blocks.
|
||||||
|
- The track graph (`TrackGraph`, `GlobalRailwayManager`), saved with the world, and train movement along it.
|
||||||
|
- Bogeys, stations, assembly, signals and edge groups, schedules, train controls and HUD, train observers, displays.
|
||||||
|
- A train is a block structure entity (S6) that follows the graph instead of moving freely.
|
||||||
|
|
||||||
|
Check: a scheduled train runs between two stations through signals.
|
||||||
|
|
||||||
|
### P9: Equipment
|
||||||
|
|
||||||
|
- Wrench (turning blocks, and picking them up with sneaking), goggles and the overlay (R10), extendo grip, potato
|
||||||
|
cannon, symmetry wand, toolbox, copper backtank and diving gear (air under water), clipboard, blueprint, worldshaper,
|
||||||
|
and Create's armor.
|
||||||
|
|
||||||
|
### P10: Decoration
|
||||||
|
|
||||||
|
- S10.
|
||||||
|
- Palettes (stone types in cut, polished, bricks, small bricks, layered and pillar, each as block, stairs, slab and
|
||||||
|
wall), windows and panes (connected glass), girders and brackets, scaffolding, ladders, bars, doors, sliding and
|
||||||
|
framed doors, placards, table cloths, copycats.
|
||||||
|
- Copycats show another block's texture in their own shape, which needs a model built from tile data. They come last.
|
||||||
|
|
||||||
|
### P11: Schematics
|
||||||
|
|
||||||
|
- S13, S14.
|
||||||
|
- Schematic and quill, schematic table with uploads, schematicannon placing from a schematic with its fuel and
|
||||||
|
materials.
|
||||||
|
|
||||||
|
### P12: Package Logistics (6.0)
|
||||||
|
|
||||||
|
- Packager, repackager, frogport, chain conveyor, stock link and ticker, redstone requester, factory gauge, shop table
|
||||||
|
cloths, cardboard.
|
||||||
|
- All new art, see [Sources](#sources).
|
||||||
|
|
||||||
|
### P13: Ponder
|
||||||
|
|
||||||
|
- A scene player: a small world from a scene's NBT, drawn in a screen (R11), with Create's scene scripts
|
||||||
|
(`infrastructure/ponder/scenes/`) ported to run its steps. 0.5.0.j has 153 scene files.
|
||||||
|
- The `W` key over an item opens its scenes.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`tests/create/`, a file per subsystem, with `test_game` from `tests/helpers.ts`. Each phase's check becomes tests:
|
||||||
|
|
||||||
|
- **Rules from plain functions:** connection ratios, recipe parsing, belt item movement, pipe flow.
|
||||||
|
- **Machines in a world:** an input goes in, the right output comes out, and nothing happens without power.
|
||||||
|
- **Networks:** placing and breaking in the middle of a line; two generators fighting; overstress.
|
||||||
|
- **Performance:** a tick with 10,000 shafts, and a frame's instance updates, stay under a budget. These are benchmarks
|
||||||
|
(`deno bench`), not tests, so a slow machine doesn't fail CI.
|
||||||
|
|
||||||
|
Following CLAUDE.md, tests check behaviour and not tuned numbers, except where the number is the point, like a 2:1 cog
|
||||||
|
ratio. Recipes come from the imported data, so tests use Create's recipes instead of copying them.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
- **Minecraft content Create assumes:** blazes (the blaze burner captures one), soul fire (haunting), the Nether and the
|
||||||
|
End (crushing and haunting recipes), minecarts and rails (cart contraptions, controller rails), honey and chocolate as
|
||||||
|
fluids, dyes. Add them to bworld, substitute them in Create's remap file, or drop what needs them?
|
||||||
|
- **Unloaded chunks:** blocks only tick within 6 chunks of a player. Do factories need a way to stay loaded, like chunk
|
||||||
|
loaders, or is "near a player" fine for bworld?
|
||||||
|
- **Contraption collision:** port `ContraptionCollider`'s approach, or write a simpler one for bworld's physics
|
||||||
|
(`common/physics.ts`) that handles turning structures differently?
|
||||||
|
- **Trains before or after contraptions:** trains reuse S6, but they're also the most-loved part of Create. Is P8 worth
|
||||||
|
moving earlier?
|
||||||
|
- **6.0's package logistics:** new art for about 20 blocks. Port them, or leave Create at 0.5's logistics?
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published
|
||||||
|
by the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
@@ -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,9 +35,13 @@ 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, and blocks that hold or show items
|
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or
|
||||||
|
show items
|
||||||
|
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a
|
||||||
|
machine
|
||||||
- [Crops](docs/modding/blocks/crops.md): farming without writing code
|
- [Crops](docs/modding/blocks/crops.md): farming without writing code
|
||||||
|
- [Verdigris](docs/modding/blocks/verdigris.md): blocks that make and use signals, like levers, torches and doors
|
||||||
|
|
||||||
**Items**
|
**Items**
|
||||||
|
|
||||||
@@ -47,34 +51,45 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
|
|
||||||
**Entities**
|
**Entities**
|
||||||
|
|
||||||
- [Entities](docs/modding/entities/index.md): animals, 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**
|
||||||
|
|
||||||
- [Containers](docs/modding/inventories/containers.md): slots the server owns and saves
|
- [Containers](docs/modding/inventories/containers.md): slots the server owns and saves
|
||||||
- [Container Screens](docs/modding/inventories/menus.md): showing containers to players
|
- [Menus](docs/modding/inventories/menus.md): slots, data and buttons on the server, and their screens
|
||||||
|
|
||||||
**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 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
|
||||||
|
- [Loot Tables](docs/modding/resources/loot_tables.md): what blocks, mobs, fishing and chests give
|
||||||
|
- [Fluids](docs/modding/resources/fluids.md): fluids that can be held, apart from blocks that flow, and the fluid
|
||||||
|
handlers that tanks and containers are filled and drained through
|
||||||
|
|
||||||
**Everything else**
|
**Everything else**
|
||||||
|
|
||||||
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
||||||
- [Screens](docs/modding/gui/index.md): inventory overlays and drawing with `Graphics`
|
- [Biomes](docs/modding/worldgen/biomes.md): surfaces, colors and seasons
|
||||||
|
- [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
|
||||||
- [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
|
||||||
|
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, keybinds and mod
|
A few parts of those types aren't built yet and throw when used: forms, custom screens and keybinds.
|
||||||
channels. [`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the
|
[`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the mod API.
|
||||||
mod API.
|
|
||||||
|
|||||||
+13
-47
@@ -1,17 +1,3 @@
|
|||||||
shout out to kenney
|
|
||||||
|
|
||||||
# Tiny town
|
|
||||||
|
|
||||||
https://kenney.nl/assets/tiny-town
|
|
||||||
|
|
||||||
license: [Creative Commons CC0](https://creativecommons.org/publicdomain/zero/1.0/)
|
|
||||||
|
|
||||||
# Roguelike
|
|
||||||
|
|
||||||
https://kenney.nl/assets/roguelike-rpg-pack
|
|
||||||
|
|
||||||
license: [Creative Commons CC0](https://creativecommons.org/publicdomain/zero/1.0/)
|
|
||||||
|
|
||||||
# UI
|
# UI
|
||||||
|
|
||||||
Catppuccin UI (Mocha, pink accent), with AppleSkin's saturation icons from the same pack. Packed into `sprites/gui.png`
|
Catppuccin UI (Mocha, pink accent), with AppleSkin's saturation icons from the same pack. Packed into `sprites/gui.png`
|
||||||
@@ -45,47 +31,19 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|||||||
SOFTWARE.
|
SOFTWARE.
|
||||||
```
|
```
|
||||||
|
|
||||||
# m6x11.ttf
|
# Fluid slot
|
||||||
|
|
||||||
Font by Daniel Linssen (https://managore.itch.io)
|
The droplet in the `fluid_slot` sprite of `sprites/gui.png` is Modern Industrialization's, from its fluid slots, drawn
|
||||||
|
over the UI's slot by hand.
|
||||||
|
|
||||||
https://managore.itch.io/m6x11 (https://web.archive.org/web/20260217032856/https://managore.itch.io/m6x11)
|
https://github.com/AztechMC/Modern-Industrialization
|
||||||
|
|
||||||
license: `free to use with attribution`
|
|
||||||
|
|
||||||
# Tiny wonder farm
|
|
||||||
|
|
||||||
https://butterymilk.itch.io/tiny-wonder-farm-asset-pack
|
|
||||||
(https://web.archive.org/web/20260204234306/https://butterymilk.itch.io/tiny-wonder-farm-asset-pack)
|
|
||||||
|
|
||||||
license:
|
license:
|
||||||
|
|
||||||
```
|
|
||||||
There's two versions, free and paid (premium):
|
|
||||||
|
|
||||||
Free: It includes a limited number of items available for free.
|
|
||||||
|
|
||||||
You are free to use sprites included in the pack in any of your non-commercial projects as well as edit the sprites and
|
|
||||||
add something new!
|
|
||||||
|
|
||||||
Premium: It includes everything shown from the showcase, all tilemaps, sprites, characters and more!
|
|
||||||
|
|
||||||
You are free to use sprites included in the pack in any of your commercial or non-commercial projects as well as edit
|
|
||||||
the sprites and add something new!
|
|
||||||
|
|
||||||
You can't resell the sprites, even if changes were made. You cannot use it in any projects related to NFT."
|
|
||||||
```
|
|
||||||
|
|
||||||
# Farmer's delight
|
|
||||||
|
|
||||||
https://github.com/vectorwing/FarmersDelight
|
|
||||||
|
|
||||||
License:
|
|
||||||
|
|
||||||
```
|
```
|
||||||
MIT License
|
MIT License
|
||||||
|
|
||||||
Copyright (c) 2020 vectorwing
|
Copyright (c) 2020 Azercoco & Technici4n
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
@@ -105,3 +63,11 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
SOFTWARE.
|
SOFTWARE.
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# m6x11.ttf
|
||||||
|
|
||||||
|
Font by Daniel Linssen (https://managore.itch.io)
|
||||||
|
|
||||||
|
https://managore.itch.io/m6x11 (https://web.archive.org/web/20260217032856/https://managore.itch.io/m6x11)
|
||||||
|
|
||||||
|
license: `free to use with attribution`
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.4 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 3.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 92 KiB |
@@ -1,17 +1,21 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { copy, walk } from "@std/fs";
|
import { copy, walk } from "@std/fs";
|
||||||
import { relative } from "@std/path";
|
import { relative } from "@std/path";
|
||||||
import { PROTOCOL_VERSION } from "./common/protocol.ts";
|
import { PROTOCOL_VERSION } from "./common/protocol.ts";
|
||||||
import { CLIENT_MANIFEST, client_manifest, sha256 } from "./desktop/client_updates.ts";
|
import { CLIENT_MANIFEST, client_manifest } from "./desktop/client_updates.ts";
|
||||||
|
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) {
|
||||||
@@ -65,7 +69,7 @@ async function build_sprites() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// the engine's textures (engine:<file>), with a list of them. clients put them in the texture atlas with the mods'
|
// the engine's textures (cubi:<file>), with a list of them. clients put them in the texture atlas with the mods'
|
||||||
function build_engine_textures() {
|
function build_engine_textures() {
|
||||||
const folder = `${BUILD_FOLDER}/assets/textures`;
|
const folder = `${BUILD_FOLDER}/assets/textures`;
|
||||||
Deno.mkdirSync(folder, { recursive: true });
|
Deno.mkdirSync(folder, { recursive: true });
|
||||||
@@ -91,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")}`);
|
||||||
@@ -100,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") {
|
||||||
@@ -127,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`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,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);
|
||||||
|
|||||||
+17
-33
@@ -1,6 +1,11 @@
|
|||||||
import { load_texture, Texture } from "./renderer/mod.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
type Asset = Texture | HTMLAudioElement | string | Record<string, unknown>;
|
import { load_texture, Texture } from "./renderer/mod.ts";
|
||||||
|
import { decode_png } from "./png.ts";
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
|
type Asset = Texture | string | Record<string, unknown>;
|
||||||
|
|
||||||
export class AssetManager {
|
export class AssetManager {
|
||||||
static instance = new AssetManager();
|
static instance = new AssetManager();
|
||||||
@@ -15,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();
|
};
|
||||||
};
|
this.loading_promises.push(promise());
|
||||||
img.onerror = () => reject(new Error(`Failed to load image: ${src}`));
|
|
||||||
});
|
|
||||||
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());
|
||||||
|
|||||||
+127
-38
@@ -1,7 +1,14 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// 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 { 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
|
||||||
@@ -15,15 +22,22 @@ export interface TextureSize {
|
|||||||
height: number;
|
height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// pixels around each texture, copies of its edge, so a face whose uvs reach the texture's edge never shows a bit of
|
||||||
|
// the next texture over, however the lookup rounds. see extrude_borders
|
||||||
|
export const ATLAS_BORDER = 1;
|
||||||
|
|
||||||
// shelves, tallest first so each row wastes little, and by id when they're the same size so the same textures always
|
// shelves, tallest first so each row wastes little, and by id when they're the same size so the same textures always
|
||||||
// give the same atlas. engine:missing is 16×16 and always there
|
// give the same atlas. cubi:missing is 16×16 and always there
|
||||||
export function atlas_layout(sizes: Map<string, TextureSize>): AtlasLayout {
|
export function atlas_layout(sizes: Map<string, TextureSize>): AtlasLayout {
|
||||||
const entries = [...sizes].filter(([id]) => id !== "engine:missing");
|
const entries = [...sizes].filter(([id]) => id !== "cubi:missing");
|
||||||
entries.push(["engine:missing", { width: TEXTURE_SIZE, height: TEXTURE_SIZE }]);
|
entries.push(["cubi:missing", { width: TEXTURE_SIZE, height: TEXTURE_SIZE }]);
|
||||||
entries.sort(([a, sa], [b, sb]) => sb.height - sa.height || sb.width - sa.width || a.localeCompare(b));
|
entries.sort(([a, sa], [b, sb]) => sb.height - sa.height || sb.width - sa.width || a.localeCompare(b));
|
||||||
|
|
||||||
const area = entries.reduce((sum, [, { width, height }]) => sum + width * height, 0);
|
const area = entries.reduce(
|
||||||
const widest = Math.max(...entries.map(([, { width }]) => width));
|
(sum, [, { width, height }]) => sum + (width + 2 * ATLAS_BORDER) * (height + 2 * ATLAS_BORDER),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const widest = Math.max(...entries.map(([, { width }]) => width + 2 * ATLAS_BORDER));
|
||||||
let size = 2 ** Math.ceil(Math.log2(Math.max(Math.sqrt(area), widest)));
|
let size = 2 ** Math.ceil(Math.log2(Math.max(Math.sqrt(area), widest)));
|
||||||
while (true) {
|
while (true) {
|
||||||
const regions = pack_shelves(entries, size);
|
const regions = pack_shelves(entries, size);
|
||||||
@@ -32,62 +46,82 @@ export function atlas_layout(sizes: Map<string, TextureSize>): AtlasLayout {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// undefined if they don't fit in a size × size square
|
// undefined if they don't fit in a size × size square. regions are the textures themselves, inside their border
|
||||||
function pack_shelves(entries: [string, TextureSize][], size: number) {
|
function pack_shelves(entries: [string, TextureSize][], size: number) {
|
||||||
const regions: Record<string, SpriteRegion> = {};
|
const regions: Record<string, SpriteRegion> = {};
|
||||||
let x = 0;
|
let x = 0;
|
||||||
let y = 0;
|
let y = 0;
|
||||||
let shelf = 0;
|
let shelf = 0;
|
||||||
for (const [id, { width, height }] of entries) {
|
for (const [id, { width, height }] of entries) {
|
||||||
if (x + width > size) {
|
const [outer_width, outer_height] = [width + 2 * ATLAS_BORDER, height + 2 * ATLAS_BORDER];
|
||||||
|
if (x + outer_width > size) {
|
||||||
x = 0;
|
x = 0;
|
||||||
y += shelf;
|
y += shelf;
|
||||||
shelf = 0;
|
shelf = 0;
|
||||||
}
|
}
|
||||||
regions[id] = { x, y, width, height };
|
regions[id] = { x: x + ATLAS_BORDER, y: y + ATLAS_BORDER, width, height };
|
||||||
x += width;
|
x += outer_width;
|
||||||
shelf = Math.max(shelf, height);
|
shelf = Math.max(shelf, outer_height);
|
||||||
}
|
}
|
||||||
return y + shelf <= size ? regions : undefined;
|
return y + shelf <= size ? regions : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
// textures are png bytes by id. ones that don't decode show as missing
|
// textures are png bytes by id, texture_json the .json of the ones that have one. ones that don't decode show as
|
||||||
export async function build_atlas(textures: Map<string, Uint8Array>) {
|
// missing. an animated texture takes one frame's room, its first frame, and plays from animated (see
|
||||||
const images = new Map<string, ImageBitmap>();
|
// texture_animations.ts)
|
||||||
await Promise.all([...textures].map(async ([id, png]) => {
|
export function build_atlas(textures: Map<string, Uint8Array>, texture_json = new Map<string, TextureJson>()) {
|
||||||
|
const images = new Map<string, Pixels>();
|
||||||
|
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("engine:missing")?.close();
|
|
||||||
images.delete("engine:missing");
|
|
||||||
|
|
||||||
const { size, regions } = atlas_layout(new Map([...images].map(([id, image]) => [id, image])));
|
const animations = new Map<string, Animation>();
|
||||||
const canvas = new OffscreenCanvas(size, size);
|
for (const [id, image] of images) {
|
||||||
const ctx = canvas.getContext("2d")!;
|
const json = texture_json.get(id);
|
||||||
|
const animation = json && texture_animation(json, image);
|
||||||
|
if (animation) animations.set(id, animation);
|
||||||
|
}
|
||||||
|
const sizes = new Map([...images].map(([id, image]) => {
|
||||||
|
const animation = animations.get(id);
|
||||||
|
return [id, animation ? { width: animation.frame_width, height: animation.frame_height } : image];
|
||||||
|
}));
|
||||||
|
|
||||||
|
const { size, regions } = atlas_layout(sizes);
|
||||||
|
const pixels = new Uint8ClampedArray(size * size * 4);
|
||||||
|
const atlas = { width: size, height: size, data: pixels };
|
||||||
|
|
||||||
// magenta and black checker
|
// magenta and black checker
|
||||||
const missing = regions["engine: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[] = [];
|
||||||
for (const [id, image] of images) {
|
for (const [id, image] of images) {
|
||||||
ctx.drawImage(image, regions[id].x, regions[id].y);
|
const animation = animations.get(id);
|
||||||
image.close();
|
const { x, y, width, height } = regions[id];
|
||||||
|
const first = animation?.frames[0] ?? { x: 0, y: 0 };
|
||||||
|
copy_pixels(image, first.x, first.y, width, height, atlas, x, y);
|
||||||
|
if (animation) animated.push(new AnimatedTexture(regions[id], animation, image.data, image.width));
|
||||||
}
|
}
|
||||||
for (const id of textures.keys()) {
|
for (const id of textures.keys()) {
|
||||||
regions[id] ??= missing;
|
regions[id] ??= missing;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extrude_borders(pixels, size, regions);
|
||||||
|
|
||||||
// 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)
|
||||||
const pixels = ctx.getImageData(0, 0, size, size).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);
|
||||||
@@ -100,7 +134,50 @@ export async function build_atlas(textures: Map<string, Uint8Array>) {
|
|||||||
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 };
|
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
|
||||||
|
// rgba atlas. an animated texture's border keeps its first frame's edge, only rounding ever shows it
|
||||||
|
export function extrude_borders(pixels: Uint8ClampedArray, size: number, regions: Record<string, SpriteRegion>) {
|
||||||
|
const copy = (from_x: number, from_y: number, to_x: number, to_y: number) => {
|
||||||
|
if (to_x < 0 || to_y < 0 || to_x >= size || to_y >= size) return;
|
||||||
|
const from = (from_y * size + from_x) * 4;
|
||||||
|
const to = (to_y * size + to_x) * 4;
|
||||||
|
for (let c = 0; c < 4; c++) pixels[to + c] = pixels[from + c];
|
||||||
|
};
|
||||||
|
// the missing texture fills in for unknown ids too, once is enough
|
||||||
|
for (const { x, y, width, height } of new Set(Object.values(regions))) {
|
||||||
|
for (let b = 1; b <= ATLAS_BORDER; b++) {
|
||||||
|
for (let px = -b; px < width + b; px++) {
|
||||||
|
const from_x = x + Math.min(Math.max(px, 0), width - 1);
|
||||||
|
copy(from_x, y, x + px, y - b);
|
||||||
|
copy(from_x, y + height - 1, x + px, y + height - 1 + b);
|
||||||
|
}
|
||||||
|
for (let py = -b; py < height + b; py++) {
|
||||||
|
const from_y = y + Math.min(Math.max(py, 0), height - 1);
|
||||||
|
copy(x, from_y, x - b, y + py);
|
||||||
|
copy(x + width - 1, from_y, x + width - 1 + b, y + py);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -118,13 +195,25 @@ export function opaque_pixels(texture_id: string): OpaqueMask | undefined {
|
|||||||
return opaque.get(texture_id);
|
return opaque.get(texture_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the last atlas built, before any animated texture moved on from its first frame
|
||||||
|
let built_atlas: Pixels | undefined;
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
if (!built_atlas || typeof document === "undefined") return undefined;
|
||||||
|
const canvas = new OffscreenCanvas(built_atlas.width, built_atlas.height);
|
||||||
|
canvas.getContext("2d")!.putImageData(new ImageData(built_atlas.data, built_atlas.width), 0, 0);
|
||||||
|
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(`engine:${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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the render benchmark's level, made on the client from a fixed seed so every run draws the same thing whatever world
|
||||||
|
// the player is in: hills with caves, trees and plants, a lake with glass in it, and flat ground for the scenes with
|
||||||
|
// 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
|
||||||
|
import { Alea } from "@paulaboks/rng";
|
||||||
|
import { AIR, CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
|
||||||
|
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
|
||||||
|
import { ChunkColumn } from "@/common/section.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import { DEFAULT_MODEL } from "@/common/block_models.ts";
|
||||||
|
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "@/common/worldgen/noise.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";
|
||||||
|
// 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
|
||||||
|
export const LEVEL_RADIUS = 13;
|
||||||
|
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
|
||||||
|
export const ZONES = {
|
||||||
|
lake: { x: -96, z: -96, radius: 44, height: 46 },
|
||||||
|
arena: { x: 96, z: -96, radius: 26, height: 72 },
|
||||||
|
visuals: { x: -96, z: 96, radius: 22, height: 72 },
|
||||||
|
updates: { x: 96, z: 96, radius: 18, height: 72 },
|
||||||
|
};
|
||||||
|
const BLEND = 24;
|
||||||
|
// what the block update scene changes, a wall facing south
|
||||||
|
export const UPDATE_WALL = {
|
||||||
|
x: ZONES.updates.x - 8,
|
||||||
|
y: ZONES.updates.height + 1,
|
||||||
|
z: ZONES.updates.z,
|
||||||
|
width: 16,
|
||||||
|
height: 8,
|
||||||
|
};
|
||||||
|
// the field of blocks drawn with code, this many on a side
|
||||||
|
const VISUALS_SIZE = 20;
|
||||||
|
// pillars standing in the lake
|
||||||
|
const GLASS_PILLARS = 6;
|
||||||
|
|
||||||
|
// of the ground's top blocks
|
||||||
|
const PLANT_CHANCE = 0.12;
|
||||||
|
const LIGHT_CHANCE = 0.003;
|
||||||
|
// a tree grows in each TREE_CELL square with TREE_CHANCE
|
||||||
|
const TREE_CELL = 8;
|
||||||
|
const TREE_CHANCE = 0.5;
|
||||||
|
// how far leaves reach from the trunk
|
||||||
|
const LEAVES_REACH = 2;
|
||||||
|
// caves are where their noise is above this
|
||||||
|
const CAVE_THRESHOLD = 0.42;
|
||||||
|
|
||||||
|
// what the level is made of, as values with their default states. what the loaded mods have no block for is left out
|
||||||
|
export interface BenchBlocks {
|
||||||
|
// the level's biome, for its colors
|
||||||
|
biome: string;
|
||||||
|
stone: number;
|
||||||
|
// the ground's cover, see SurfaceJson in common/worldgen/biomes.ts
|
||||||
|
top: number;
|
||||||
|
filler: number;
|
||||||
|
filler_depth: number;
|
||||||
|
underwater: number;
|
||||||
|
log: number;
|
||||||
|
leaves?: number;
|
||||||
|
plants: number[];
|
||||||
|
glass?: number;
|
||||||
|
fluid?: number;
|
||||||
|
light?: number;
|
||||||
|
// blocks drawn with code, see client/rendering/visuals.ts
|
||||||
|
visuals: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// visual_blocks are the numeric ids of the blocks drawn with code. the same mods give the same blocks
|
||||||
|
export function bench_blocks(visual_blocks: ReadonlySet<number>): BenchBlocks {
|
||||||
|
const all = EverythingRegistry.get_registry<BlockRegistry>("blocks")
|
||||||
|
.map((block, nid) => ({ block, nid, value: default_block_value(nid, block) }))
|
||||||
|
.filter(({ block, nid }) => block && nid !== AIR)
|
||||||
|
.sort((a, b) => a.block.id.localeCompare(b.block.id));
|
||||||
|
type Entry = typeof all[number];
|
||||||
|
const layer = ({ block }: Entry) => block.render_layer ?? "solid";
|
||||||
|
const cube = ({ block }: Entry) => (block.model ?? DEFAULT_MODEL) === DEFAULT_MODEL && !block.parts;
|
||||||
|
// one look that nothing changes
|
||||||
|
const plain = ({ block, nid }: Entry) =>
|
||||||
|
!block.states?.length && !block.variants && !block.fluid && !block.light_emission && !visual_blocks.has(nid);
|
||||||
|
const tinted = ({ block }: Entry, color: string) => block.tint?.color === color;
|
||||||
|
const by_id = (id: string | undefined) => all.find((b) => b.block.id === id);
|
||||||
|
|
||||||
|
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");
|
||||||
|
// 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 settings = EverythingRegistry.entries<NoiseSettingsJson>("noise_settings").sort(by_key)[0]?.[1];
|
||||||
|
const biomes = EverythingRegistry.entries<Biome>("biomes").sort(by_key).map(([, biome]) => biome);
|
||||||
|
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 top = by_id(biome?.surface.top) ?? solid.find((b) => tinted(b, "grass")) ?? stone;
|
||||||
|
const filler = by_id(biome?.surface.filler) ?? stone;
|
||||||
|
const ground = [stone, top, filler];
|
||||||
|
const leaves = all.filter((b) => plain(b) && cube(b) && layer(b) === "cutout");
|
||||||
|
// what says it grows on the ground's top, with its default states
|
||||||
|
const plants = all.filter((b) =>
|
||||||
|
b.block.place_on && can_stand_on(b.block, top.block.id) && layer(b) === "cutout" && !cube(b) &&
|
||||||
|
!b.block.has_collision && !visual_blocks.has(b.nid)
|
||||||
|
);
|
||||||
|
// water rather than lava
|
||||||
|
const fluids = all.filter((b) => b.block.fluid && !b.block.light_emission);
|
||||||
|
return {
|
||||||
|
biome: biome?.id ?? "",
|
||||||
|
stone: stone.value,
|
||||||
|
top: top.value,
|
||||||
|
filler: filler.value,
|
||||||
|
filler_depth: biome?.surface.filler_depth ?? 3,
|
||||||
|
underwater: (by_id(biome?.surface.underwater_top) ?? filler).value,
|
||||||
|
log: (solid.find((b) => !ground.includes(b)) ?? stone).value,
|
||||||
|
leaves: (leaves.find((b) => tinted(b, "foliage")) ?? leaves[0])?.value,
|
||||||
|
plants: plants.map((b) => b.value),
|
||||||
|
glass: all.find((b) => plain(b) && cube(b) && layer(b) === "translucent")?.value,
|
||||||
|
fluid: (by_id(settings?.fluids[0]?.block) ?? fluids.find((b) => layer(b) === "translucent") ?? fluids[0])
|
||||||
|
?.value,
|
||||||
|
light: all.find((b) => (b.block.light_emission ?? 0) > 0 && !b.block.fluid)?.value,
|
||||||
|
visuals: all.filter((b) => visual_blocks.has(b.nid)).map((b) => b.value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// the level's terrain, a chunk at a time. a chunk always comes out the same
|
||||||
|
export class BenchTerrain {
|
||||||
|
#blocks: BenchBlocks;
|
||||||
|
#hills = new OctaveNoise2D(SEED, "hills", 160, [1, 0.5, 0.25, 0.125]);
|
||||||
|
#mountains = new OctaveNoise2D(SEED, "mountains", 320, [1, 0.5, 0.25]);
|
||||||
|
#caves = new OctaveNoise3D(SEED, "caves", 40, [1, 0.5], 0.75);
|
||||||
|
|
||||||
|
constructor(blocks: BenchBlocks) {
|
||||||
|
this.#blocks = blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the y of the top block
|
||||||
|
height(x: number, z: number): number {
|
||||||
|
const mountains = Math.max(0, this.#mountains.sample(x, z));
|
||||||
|
let height = 68 + this.#hills.sample(x, z) * 16 + mountains * mountains * 140;
|
||||||
|
for (const zone of Object.values(ZONES)) {
|
||||||
|
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
|
||||||
|
height = zone.height + (height - zone.height) * t;
|
||||||
|
}
|
||||||
|
return Math.min(TOP - 32, Math.round(height));
|
||||||
|
}
|
||||||
|
|
||||||
|
chunk(chunk_x: number, chunk_z: number): ChunkColumn {
|
||||||
|
const b = this.#blocks;
|
||||||
|
const blocks = new Uint32Array(LEVEL_SHAPE.volume);
|
||||||
|
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
|
||||||
|
const x0 = chunk_x * CHUNK_SIZE;
|
||||||
|
const z0 = chunk_z * CHUNK_SIZE;
|
||||||
|
// in world coordinates, only what's in this chunk
|
||||||
|
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
|
||||||
|
const lx = x - x0;
|
||||||
|
const lz = z - z0;
|
||||||
|
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;
|
||||||
|
if (!only_air || blocks[index] === AIR) blocks[index] = value;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let lz = 0; lz < CHUNK_SIZE; lz++) {
|
||||||
|
for (let lx = 0; lx < CHUNK_SIZE; lx++) {
|
||||||
|
const x = x0 + lx;
|
||||||
|
const z = z0 + lz;
|
||||||
|
const height = this.height(x, z);
|
||||||
|
const shore = height <= SEA_LEVEL + 1;
|
||||||
|
const cover = height <= SEA_LEVEL ? b.underwater : b.top;
|
||||||
|
const column = lz * CHUNK_SIZE + lx;
|
||||||
|
for (let y = 0; y <= height; y++) {
|
||||||
|
let value = y === height ? cover : y >= height - b.filler_depth ? b.filler : b.stone;
|
||||||
|
if (y > 4 && y < height - 4 && this.#caves.sample(x, y, z) > CAVE_THRESHOLD) value = AIR;
|
||||||
|
blocks[y * CHUNK_AREA + column] = value;
|
||||||
|
}
|
||||||
|
for (let y = height + 1; b.fluid !== undefined && y <= SEA_LEVEL; y++) {
|
||||||
|
blocks[y * CHUNK_AREA + column] = b.fluid;
|
||||||
|
}
|
||||||
|
if (shore || this.#in_zone(x, z, 4)) continue;
|
||||||
|
const above = (height + 1) * CHUNK_AREA + column;
|
||||||
|
const roll = random.next();
|
||||||
|
if (b.light !== undefined && roll < LIGHT_CHANCE) {
|
||||||
|
blocks[above] = b.light;
|
||||||
|
} else if (b.plants.length > 0 && roll < PLANT_CHANCE) {
|
||||||
|
blocks[above] = b.plants[Math.floor(random.next() * b.plants.length)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.#trees(chunk_x, chunk_z, set);
|
||||||
|
this.#features(set);
|
||||||
|
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) {
|
||||||
|
return Object.values(ZONES).some((zone) => Math.hypot(x - zone.x, z - zone.z) < zone.radius + margin);
|
||||||
|
}
|
||||||
|
|
||||||
|
// every tree with blocks in this chunk, some grow from the chunks beside it
|
||||||
|
#trees(chunk_x: number, chunk_z: number, set: (x: number, y: number, z: number, v: number, air?: boolean) => void) {
|
||||||
|
const b = this.#blocks;
|
||||||
|
const cells = (chunk: number) => [
|
||||||
|
Math.floor((chunk * CHUNK_SIZE - LEAVES_REACH) / TREE_CELL),
|
||||||
|
Math.floor((chunk * CHUNK_SIZE + CHUNK_SIZE - 1 + LEAVES_REACH) / TREE_CELL),
|
||||||
|
];
|
||||||
|
const [first_x, last_x] = cells(chunk_x);
|
||||||
|
const [first_z, last_z] = cells(chunk_z);
|
||||||
|
for (let cell_z = first_z; cell_z <= last_z; cell_z++) {
|
||||||
|
for (let cell_x = first_x; cell_x <= last_x; cell_x++) {
|
||||||
|
const random = new Alea(`${SEED}_tree_${cell_x}_${cell_z}`);
|
||||||
|
if (random.next() > TREE_CHANCE) continue;
|
||||||
|
// away from the cell's edges, so leaves don't run into the next cell's tree
|
||||||
|
const x = cell_x * TREE_CELL + LEAVES_REACH +
|
||||||
|
Math.floor(random.next() * (TREE_CELL - LEAVES_REACH * 2));
|
||||||
|
const z = cell_z * TREE_CELL + LEAVES_REACH +
|
||||||
|
Math.floor(random.next() * (TREE_CELL - LEAVES_REACH * 2));
|
||||||
|
const trunk = 4 + Math.floor(random.next() * 3);
|
||||||
|
const ground = this.height(x, z);
|
||||||
|
if (ground <= SEA_LEVEL + 1 || this.#in_zone(x, z, 6)) continue;
|
||||||
|
for (let dy = 0; dy < trunk; dy++) set(x, ground + 1 + dy, z, b.log);
|
||||||
|
if (b.leaves === undefined) continue;
|
||||||
|
for (let dy = trunk - 2; dy <= trunk + 1; dy++) {
|
||||||
|
const reach = dy < trunk ? LEAVES_REACH : 1;
|
||||||
|
for (let dz = -reach; dz <= reach; dz++) {
|
||||||
|
for (let dx = -reach; dx <= reach; dx++) {
|
||||||
|
// rounded off at the corners
|
||||||
|
if (Math.abs(dx) === reach && Math.abs(dz) === reach) continue;
|
||||||
|
set(x + dx, ground + 1 + dy, z + dz, b.leaves, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// glass standing in the lake, and the field of visuals
|
||||||
|
#features(set: (x: number, y: number, z: number, value: number) => void) {
|
||||||
|
const b = this.#blocks;
|
||||||
|
const { lake, visuals } = ZONES;
|
||||||
|
for (let i = 0; b.glass !== undefined && i < GLASS_PILLARS; i++) {
|
||||||
|
const angle = (i / GLASS_PILLARS) * Math.PI * 2;
|
||||||
|
const x = lake.x + Math.round(Math.cos(angle) * lake.radius / 2);
|
||||||
|
const z = lake.z + Math.round(Math.sin(angle) * lake.radius / 2);
|
||||||
|
for (let y = lake.height + 1; y <= SEA_LEVEL + 12; y++) {
|
||||||
|
for (let dz = -1; dz <= 1; dz++) {
|
||||||
|
for (let dx = -1; dx <= 1; dx++) set(x + dx, y, z + dz, b.glass);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let i = 0; b.visuals.length > 0 && i < VISUALS_SIZE * VISUALS_SIZE; i++) {
|
||||||
|
const x = visuals.x - VISUALS_SIZE / 2 + (i % VISUALS_SIZE);
|
||||||
|
const z = visuals.z - VISUALS_SIZE / 2 + Math.floor(i / VISUALS_SIZE);
|
||||||
|
set(x, visuals.height + 1, z, b.visuals[i % b.visuals.length]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,574 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the render benchmark, run from the f3 performance window, for comparing browsers and systems. it draws a level of
|
||||||
|
// its own that's the same every time (see bench_level.ts) through scenes that each load a part of the renderer: the
|
||||||
|
// terrain from above, the lake, a crowd of entities, blocks changing every tick and so on. the world waits meanwhile,
|
||||||
|
// 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
|
||||||
|
// first time and again. the report says what the computer and the browser are, see report.ts
|
||||||
|
import { Camera } from "@/client/camera.ts";
|
||||||
|
import { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
|
import type { GameRenderer } from "@/client/rendering/game_renderer.ts";
|
||||||
|
import { block_visuals } from "@/client/rendering/visuals.ts";
|
||||||
|
import { draw_item } from "@/client/rendering/render_utils.ts";
|
||||||
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
|
import { platform } from "@/client/platform.ts";
|
||||||
|
import { type FrameSample, profiler } from "@/client/profiler.ts";
|
||||||
|
import { RemotePlayer } from "@/client/entity/remote_player.ts";
|
||||||
|
import { RemoteEntity } from "@/client/entity/remote_entity.ts";
|
||||||
|
import { ItemEntity } from "@/client/entity/item_entity.ts";
|
||||||
|
import { tick_texture_animations } from "@/client/texture_animations.ts";
|
||||||
|
import {
|
||||||
|
adapter_info,
|
||||||
|
device,
|
||||||
|
draw_text,
|
||||||
|
gpu_timer,
|
||||||
|
render_debug,
|
||||||
|
render_stats,
|
||||||
|
set_canvas_size,
|
||||||
|
} from "@/client/renderer/mod.ts";
|
||||||
|
import { ID_MASK, SLOT_SIZE, STATE_SHIFT } from "@/common/constants.ts";
|
||||||
|
import { AIR_ID } from "@/common/protocol.ts";
|
||||||
|
import { TIMES_OF_DAY } from "@/common/time.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry, RENDER_LAYERS } from "@/common/everything_registry.ts";
|
||||||
|
import type { EntityJson } from "@/common/mod_data.ts";
|
||||||
|
import type { ModListing } from "@/common/mod_loader.ts";
|
||||||
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
|
import { display_name } from "@/common/utils.ts";
|
||||||
|
import {
|
||||||
|
bench_blocks,
|
||||||
|
type BenchBlocks,
|
||||||
|
BenchTerrain,
|
||||||
|
LEVEL_RADIUS,
|
||||||
|
LEVEL_SHAPE,
|
||||||
|
SEA_LEVEL,
|
||||||
|
UPDATE_WALL,
|
||||||
|
ZONES,
|
||||||
|
} from "./bench_level.ts";
|
||||||
|
import {
|
||||||
|
BENCHMARK_VERSION,
|
||||||
|
type BenchmarkReport,
|
||||||
|
frame_stats,
|
||||||
|
type MeshingResult,
|
||||||
|
type SceneResult,
|
||||||
|
type SystemInfo,
|
||||||
|
time_stats,
|
||||||
|
} from "./report.ts";
|
||||||
|
|
||||||
|
// each scene's parts. warmup and settle aren't counted, settle is for the switch to uncapped frames
|
||||||
|
const PHASES = [
|
||||||
|
{ phase: "warmup", ms: 1500 },
|
||||||
|
{ phase: "paced", ms: 5000 },
|
||||||
|
{ phase: "settle", ms: 500 },
|
||||||
|
{ phase: "uncapped", ms: 4000 },
|
||||||
|
] as const;
|
||||||
|
// every run draws at this size, scaled to fit the window, so runs in different windows compare
|
||||||
|
const RESOLUTION = { width: 1920, height: 1080 };
|
||||||
|
// how long a frame spends building the level, it's built over many so the page keeps responding
|
||||||
|
const BUILD_MS_PER_FRAME = 30;
|
||||||
|
// meshing the level gives up after this
|
||||||
|
const MESHING_TIMEOUT_MS = 120_000;
|
||||||
|
// meshes each worker is given at once, see ClientLevel.max_meshes_in_flight
|
||||||
|
const MESHES_PER_WORKER = 8;
|
||||||
|
// walking round the arena
|
||||||
|
const PLAYERS = 40;
|
||||||
|
const MOBS = 80;
|
||||||
|
// in blocks per tick
|
||||||
|
const WALK_SPEED = 0.2;
|
||||||
|
// lying in the middle of it
|
||||||
|
const ITEMS = 160;
|
||||||
|
const ITEM_ROW = 16;
|
||||||
|
const ITEM_SPACING = 0.6;
|
||||||
|
// the gui scene's lines of item names, about as long as the screen is wide
|
||||||
|
const GUI_LINE_LENGTH = 160;
|
||||||
|
|
||||||
|
interface Scene {
|
||||||
|
name: string;
|
||||||
|
// where the camera is t of the way through each part of the scene, from 0 to 1
|
||||||
|
camera: (camera: Camera, t: number) => void;
|
||||||
|
msaa?: boolean;
|
||||||
|
// before and after it, for what only it has
|
||||||
|
start?: () => void;
|
||||||
|
end?: () => void;
|
||||||
|
// every tick
|
||||||
|
tick?: (ticks: number) => void;
|
||||||
|
// over the level, like a screen
|
||||||
|
draw?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// an entity going round the arena
|
||||||
|
interface Walker {
|
||||||
|
entity: RemotePlayer | RemoteEntity;
|
||||||
|
radius: number;
|
||||||
|
angle: number;
|
||||||
|
// radians per tick, negative is clockwise
|
||||||
|
speed: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RenderBenchmark {
|
||||||
|
// what it's doing, shown while it runs
|
||||||
|
status = "Building the level";
|
||||||
|
|
||||||
|
#renderer: GameRenderer;
|
||||||
|
#mods: ModListing[];
|
||||||
|
// with the report, or why it stopped
|
||||||
|
#on_end: (result: BenchmarkReport | string) => void;
|
||||||
|
#ended = false;
|
||||||
|
#level: ClientLevel;
|
||||||
|
#blocks: BenchBlocks;
|
||||||
|
#camera = new Camera();
|
||||||
|
// what's drawn, nothing while the level is built
|
||||||
|
#scene: Scene | undefined;
|
||||||
|
// how far through the scene's part it is
|
||||||
|
#t = 0;
|
||||||
|
#flow: Generator<void, void>;
|
||||||
|
#build_ms = 0;
|
||||||
|
#walkers: Walker[] = [];
|
||||||
|
// every item, for the gui scene and the ones lying in the arena
|
||||||
|
#items: ItemStack[];
|
||||||
|
// a line of names for each row of the gui scene's slots
|
||||||
|
#gui_lines: string[];
|
||||||
|
#system: SystemInfo;
|
||||||
|
// the game was hidden, which held frames back
|
||||||
|
#hidden = false;
|
||||||
|
#stop_watching_shown: () => void;
|
||||||
|
#saved_debug = { ...render_debug };
|
||||||
|
#saved_draw: Record<string, boolean>;
|
||||||
|
|
||||||
|
constructor(renderer: GameRenderer, mods: ModListing[], on_end: (result: BenchmarkReport | string) => void) {
|
||||||
|
this.#blocks = bench_blocks(new Set(block_visuals.keys()));
|
||||||
|
this.#renderer = renderer;
|
||||||
|
this.#mods = mods;
|
||||||
|
this.#on_end = on_end;
|
||||||
|
this.#items = EverythingRegistry.entries("items").map(([id]) => id).sort().map((id) => new ItemStack(id));
|
||||||
|
const names = this.#items.map((item) => display_name(item.type_id)).join(" ");
|
||||||
|
this.#gui_lines = Array.from(
|
||||||
|
{ length: Math.floor(RESOLUTION.height / SLOT_SIZE) },
|
||||||
|
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.#level = new ClientLevel([], LEVEL_SHAPE, LEVEL_RADIUS);
|
||||||
|
this.#level.time = TIMES_OF_DAY.noon;
|
||||||
|
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
|
||||||
|
this.#system = system_info(this.#level.workers.size);
|
||||||
|
|
||||||
|
// what the f3 window switched is put back after
|
||||||
|
const draw = renderer.level_renderer.draw;
|
||||||
|
this.#saved_draw = { ...draw };
|
||||||
|
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 });
|
||||||
|
set_canvas_size(RESOLUTION);
|
||||||
|
this.#stop_watching_shown = platform.on_shown(() => this.#hidden = true);
|
||||||
|
this.#flow = this.#run();
|
||||||
|
}
|
||||||
|
|
||||||
|
// at the start of the client's frame, before its ticks
|
||||||
|
frame() {
|
||||||
|
this.#guard(() => {
|
||||||
|
if (InputManager.is_key_pressed("Escape")) {
|
||||||
|
this.#end("The benchmark was stopped");
|
||||||
|
} else if (this.#hidden) {
|
||||||
|
this.#end("The benchmark stopped since the game was hidden, which holds frames back");
|
||||||
|
} else {
|
||||||
|
this.#flow.next();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// instead of the client's tick, which waits
|
||||||
|
tick() {
|
||||||
|
this.#guard(() => {
|
||||||
|
this.#scene?.tick?.(this.#level.ticks);
|
||||||
|
this.#level.tick();
|
||||||
|
this.#level.time = TIMES_OF_DAY.noon;
|
||||||
|
tick_texture_animations();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// instead of the client's drawing
|
||||||
|
render(partial_tick: number) {
|
||||||
|
this.#guard(() => {
|
||||||
|
const scene = this.#scene;
|
||||||
|
if (scene) {
|
||||||
|
scene.camera(this.#camera, Math.min(this.#t, 1));
|
||||||
|
this.#renderer.render_level(this.#level, this.#camera, partial_tick);
|
||||||
|
scene.draw?.();
|
||||||
|
}
|
||||||
|
draw_text(`Benchmark: ${this.status}. Escape stops it`, 8, 8);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// a benchmark that throws stops, so the game goes on
|
||||||
|
#guard(fn: () => void) {
|
||||||
|
if (this.#ended) return;
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
this.#end(`The benchmark failed: ${e instanceof Error ? e.message : e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#end(result: BenchmarkReport | string) {
|
||||||
|
this.#ended = true;
|
||||||
|
this.#level.dispose();
|
||||||
|
Object.assign(render_debug, this.#saved_debug);
|
||||||
|
Object.assign(this.#renderer.level_renderer.draw, this.#saved_draw);
|
||||||
|
set_canvas_size(undefined);
|
||||||
|
profiler.samples = undefined;
|
||||||
|
if (gpu_timer) gpu_timer.samples = undefined;
|
||||||
|
this.#stop_watching_shown();
|
||||||
|
this.#on_end(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the whole benchmark, a frame at each yield
|
||||||
|
*#run(): Generator<void, void> {
|
||||||
|
yield* this.#build();
|
||||||
|
const first_mesh = yield* this.#mesh(false);
|
||||||
|
const remesh = yield* this.#mesh(true);
|
||||||
|
const scenes: Record<string, SceneResult> = {};
|
||||||
|
const list = this.#scenes();
|
||||||
|
for (const [i, scene] of list.entries()) {
|
||||||
|
scenes[scene.name] = yield* this.#measure(scene, `${i + 1} of ${list.length}`);
|
||||||
|
}
|
||||||
|
// the mean, firefox's timer only counts whole ms
|
||||||
|
const sky = scenes.sky?.paced;
|
||||||
|
if (sky) this.#system.refresh_hz = Math.round(sky.fps);
|
||||||
|
this.#end({
|
||||||
|
version: BENCHMARK_VERSION,
|
||||||
|
date: new Date().toISOString(),
|
||||||
|
system: this.#system,
|
||||||
|
mods: this.#mods.map((mod) => `${mod.id} ${mod.version}`),
|
||||||
|
resolution: `${RESOLUTION.width}x${RESOLUTION.height}`,
|
||||||
|
render_regions: render_debug.render_regions,
|
||||||
|
level: { chunks: this.#level.chunks.size, build_ms: this.#build_ms },
|
||||||
|
first_mesh,
|
||||||
|
remesh,
|
||||||
|
scenes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
*#build(): Generator<void, void> {
|
||||||
|
const terrain = new BenchTerrain(this.#blocks);
|
||||||
|
const chunks: [number, number][] = [];
|
||||||
|
for (let z = -LEVEL_RADIUS; z < LEVEL_RADIUS; z++) {
|
||||||
|
for (let x = -LEVEL_RADIUS; x < LEVEL_RADIUS; x++) chunks.push([x, z]);
|
||||||
|
}
|
||||||
|
let built = 0;
|
||||||
|
while (built < chunks.length) {
|
||||||
|
const start = performance.now();
|
||||||
|
while (built < chunks.length && performance.now() - start < BUILD_MS_PER_FRAME) {
|
||||||
|
const [x, z] = chunks[built++];
|
||||||
|
this.#level.set_chunk(terrain.chunk(x, z));
|
||||||
|
}
|
||||||
|
this.#build_ms += performance.now() - start;
|
||||||
|
this.status = `building the level, ${Math.floor(built / chunks.length * 100)}%`;
|
||||||
|
yield;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// meshing every chunk that can be, the first time and again once the workers have warmed up
|
||||||
|
*#mesh(again: boolean): Generator<void, MeshingResult> {
|
||||||
|
const level = this.#level;
|
||||||
|
this.#scene = { name: "meshing", camera: overlook };
|
||||||
|
this.status = again ? "meshing the level again" : "meshing the level";
|
||||||
|
if (again) level.remesh_all();
|
||||||
|
const frames: FrameSample[] = [];
|
||||||
|
profiler.samples = frames;
|
||||||
|
const start = performance.now();
|
||||||
|
// this frame asks for the first meshes
|
||||||
|
do {
|
||||||
|
yield;
|
||||||
|
if (performance.now() - start > MESHING_TIMEOUT_MS) throw new Error("meshing the level took too long");
|
||||||
|
} while (level.meshes_pending > 0);
|
||||||
|
profiler.samples = undefined;
|
||||||
|
return {
|
||||||
|
chunks: [...level.chunks.values()].filter((chunk) => level.can_mesh(chunk)).length,
|
||||||
|
ms: performance.now() - start,
|
||||||
|
paced: frame_stats(frames.map((frame) => frame.interval)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
*#measure(scene: Scene, progress: string): Generator<void, SceneResult> {
|
||||||
|
this.#scene = scene;
|
||||||
|
scene.start?.();
|
||||||
|
render_debug.msaa = scene.msaa ?? false;
|
||||||
|
const timed: Partial<Record<"paced" | "uncapped", { frames: FrameSample[]; gpu: number[] }>> = {};
|
||||||
|
let drawn = this.#drawn();
|
||||||
|
for (const { phase, ms } of PHASES) {
|
||||||
|
this.status = `${scene.name}, ${progress}`;
|
||||||
|
render_debug.uncapped = phase === "settle" || phase === "uncapped";
|
||||||
|
const frames: FrameSample[] = [];
|
||||||
|
const gpu: number[] = [];
|
||||||
|
profiler.samples = frames;
|
||||||
|
if (gpu_timer) gpu_timer.samples = gpu;
|
||||||
|
const start = performance.now();
|
||||||
|
for (let frame = 0; (this.#t = (performance.now() - start) / ms) < 1; frame++) {
|
||||||
|
// the first frame's, where the camera always is in the same place
|
||||||
|
if (phase === "paced" && frame === 1) drawn = this.#drawn();
|
||||||
|
yield;
|
||||||
|
}
|
||||||
|
if (phase === "paced" || phase === "uncapped") timed[phase] = { frames, gpu };
|
||||||
|
}
|
||||||
|
render_debug.msaa = false;
|
||||||
|
render_debug.uncapped = false;
|
||||||
|
scene.end?.();
|
||||||
|
// the paced frames' gpu times have all come back by now
|
||||||
|
const { paced, uncapped } = timed;
|
||||||
|
return {
|
||||||
|
paced: frame_stats(paced?.frames.map((frame) => frame.interval) ?? []),
|
||||||
|
uncapped_fps: uncapped && uncapped.frames.length * 1000 /
|
||||||
|
uncapped.frames.reduce((sum, frame) => sum + frame.interval, 0),
|
||||||
|
cpu: time_stats(paced?.frames.map((frame) => frame.frame) ?? []),
|
||||||
|
gpu: time_stats(paced?.gpu ?? []),
|
||||||
|
...drawn,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// what the last frame drew
|
||||||
|
#drawn() {
|
||||||
|
const { draw_calls, quads } = render_stats;
|
||||||
|
const level_renderer = this.#renderer.level_renderer;
|
||||||
|
return {
|
||||||
|
draw_calls,
|
||||||
|
quads: RENDER_LAYERS.reduce((sum, layer) => sum + quads[layer], 0),
|
||||||
|
sections_in_view: level_renderer.visible_sections,
|
||||||
|
entities_in_view: level_renderer.drawn_entities,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#scenes(): Scene[] {
|
||||||
|
const sky = (camera: Camera) => place(camera, 0, 200, 0, 0, 1.5);
|
||||||
|
const { lake, arena, visuals } = ZONES;
|
||||||
|
const wall = UPDATE_WALL;
|
||||||
|
return [
|
||||||
|
// nothing in view: what every frame costs anyway, and the display's refresh
|
||||||
|
{ name: "sky", camera: sky },
|
||||||
|
// the whole level from above
|
||||||
|
{ name: "terrain", camera: overlook },
|
||||||
|
{ name: "msaa", camera: overlook, msaa: true },
|
||||||
|
// round the level, low and looking ahead, so what's in view keeps changing
|
||||||
|
{ name: "flyover", camera: flyover },
|
||||||
|
// across the lake, moving so its water is sorted again
|
||||||
|
{
|
||||||
|
name: "water",
|
||||||
|
camera: (camera, t) =>
|
||||||
|
place(
|
||||||
|
camera,
|
||||||
|
lake.x + 40 + sway(t, 6),
|
||||||
|
SEA_LEVEL + 6,
|
||||||
|
lake.z + 40 - sway(t, 6),
|
||||||
|
Math.PI / 4 + sway(t, 0.3),
|
||||||
|
-0.12,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// only here, so the other scenes don't draw them
|
||||||
|
{
|
||||||
|
name: "entities",
|
||||||
|
camera: (camera, t) => place(camera, arena.x, arena.height + 8, arena.z + 30, sway(t, 0.3), -0.3),
|
||||||
|
start: () => this.#spawn_entities(),
|
||||||
|
end: () => this.#remove_entities(),
|
||||||
|
tick: () => this.#walk(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "visuals",
|
||||||
|
camera: (camera, t) =>
|
||||||
|
place(camera, visuals.x, visuals.height + 10, visuals.z + 18, sway(t, 0.2), -0.5),
|
||||||
|
},
|
||||||
|
// a screen full of items over the sky
|
||||||
|
{ name: "gui", camera: sky, draw: () => this.#draw_gui() },
|
||||||
|
{
|
||||||
|
name: "block_updates",
|
||||||
|
camera: (camera, t) =>
|
||||||
|
place(camera, wall.x + wall.width / 2, wall.y + 4, wall.z + 16, sway(t, 0.15), -0.1),
|
||||||
|
tick: (ticks) => this.#change_wall(ticks),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
#spawn_entities() {
|
||||||
|
const level = this.#level;
|
||||||
|
const { x, z, height } = ZONES.arena;
|
||||||
|
const y = height + 1;
|
||||||
|
// four rings each way round, every other one the other way
|
||||||
|
const walk = (entity: RemotePlayer | RemoteEntity, i: number, count: number, radius: number) => {
|
||||||
|
const ring = i % 4;
|
||||||
|
const ring_radius = radius + ring * 4;
|
||||||
|
const speed = (ring % 2 === 0 ? 1 : -1) * WALK_SPEED / ring_radius;
|
||||||
|
this.#walkers.push({ entity, radius: ring_radius, angle: (i / count) * Math.PI * 2, speed });
|
||||||
|
level.add_entity(entity);
|
||||||
|
};
|
||||||
|
for (let i = 0; i < PLAYERS; i++) {
|
||||||
|
const info = { id: `benchmark_player_${i}`, name: `Player ${i + 1}`, x, y, z, yaw: 0, pitch: 0 };
|
||||||
|
walk(new RemotePlayer(level, info), i, PLAYERS, 6);
|
||||||
|
}
|
||||||
|
const types = EverythingRegistry.entries<EntityJson>("entities").map(([id]) => id).sort();
|
||||||
|
for (let i = 0; types.length > 0 && i < MOBS; i++) {
|
||||||
|
const type = types[i % types.length];
|
||||||
|
const info = {
|
||||||
|
kind: "entity" as const,
|
||||||
|
type,
|
||||||
|
id: `benchmark_mob_${i}`,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
z,
|
||||||
|
yaw: 0,
|
||||||
|
pitch: 0,
|
||||||
|
data: {},
|
||||||
|
};
|
||||||
|
walk(new RemoteEntity(level, info), i, MOBS, 8);
|
||||||
|
}
|
||||||
|
for (let i = 0; this.#items.length > 0 && i < ITEMS; i++) {
|
||||||
|
level.add_entity(
|
||||||
|
new ItemEntity(level, {
|
||||||
|
kind: "item",
|
||||||
|
id: `benchmark_item_${i}`,
|
||||||
|
x: x + ((i % ITEM_ROW) - ITEM_ROW / 2) * ITEM_SPACING,
|
||||||
|
y,
|
||||||
|
z: z + (Math.floor(i / ITEM_ROW) - ITEMS / ITEM_ROW / 2) * ITEM_SPACING,
|
||||||
|
item: { id: this.#items[i % this.#items.length].type_id, count: 1 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#remove_entities() {
|
||||||
|
for (const id of [...this.#level.entities.keys()]) this.#level.remove_entity(id);
|
||||||
|
this.#walkers = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
#walk() {
|
||||||
|
const { x, z, height } = ZONES.arena;
|
||||||
|
for (const walker of this.#walkers) {
|
||||||
|
walker.angle += walker.speed;
|
||||||
|
const cos = Math.cos(walker.angle);
|
||||||
|
const sin = Math.sin(walker.angle);
|
||||||
|
// facing the way it goes, yaw 0 is north (-z)
|
||||||
|
const yaw = Math.atan2(sin * Math.sign(walker.speed), -cos * Math.sign(walker.speed));
|
||||||
|
walker.entity.lerp_to(x + cos * walker.radius, height + 1, z + sin * walker.radius, yaw, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// every block of the wall changes every tick, between a light and stone, so the light around it changes too, the
|
||||||
|
// way the server's block changes come in
|
||||||
|
#change_wall(ticks: number) {
|
||||||
|
const { light, stone } = this.#blocks;
|
||||||
|
const [on, off] = light === undefined
|
||||||
|
? [block_id(stone), [AIR_ID, 0] as const]
|
||||||
|
: [block_id(light), block_id(stone)];
|
||||||
|
const wall = UPDATE_WALL;
|
||||||
|
for (let dy = 0; dy < wall.height; dy++) {
|
||||||
|
for (let dx = 0; dx < wall.width; dx++) {
|
||||||
|
const [id, state] = (dx + dy + ticks) % 2 === 0 ? on : off;
|
||||||
|
this.#level.apply_change(wall.x + dx, wall.y + dy, wall.z, id, state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// every item in slots filling the screen, with their names over them
|
||||||
|
#draw_gui() {
|
||||||
|
const items = this.#items;
|
||||||
|
if (items.length === 0) return;
|
||||||
|
const columns = Math.floor(RESOLUTION.width / SLOT_SIZE);
|
||||||
|
const rows = this.#gui_lines.length;
|
||||||
|
for (let i = 0; i < columns * rows; i++) {
|
||||||
|
const x = (i % columns) * SLOT_SIZE;
|
||||||
|
const y = Math.floor(i / columns) * SLOT_SIZE;
|
||||||
|
draw_item(items[i % items.length], x, y, false);
|
||||||
|
}
|
||||||
|
this.#gui_lines.forEach((line, row) => draw_text(line, 4, row * SLOT_SIZE + 4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the camera at x y z, turned yaw from facing north (-z) and pitch up
|
||||||
|
function place(camera: Camera, x: number, y: number, z: number, yaw: number, pitch: number) {
|
||||||
|
camera.x = x;
|
||||||
|
camera.y = y;
|
||||||
|
camera.z = z;
|
||||||
|
camera.yaw = yaw;
|
||||||
|
camera.pitch = pitch;
|
||||||
|
}
|
||||||
|
|
||||||
|
// there and back once, from 0
|
||||||
|
function sway(t: number, amount: number) {
|
||||||
|
return Math.sin(t * Math.PI * 2) * amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the whole level from its south edge, looking a little to each side
|
||||||
|
function overlook(camera: Camera, t: number) {
|
||||||
|
place(camera, 0, 150, LEVEL_RADIUS * 16 - 8, sway(t, 0.25), -0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
// once round the level, looking ahead and a little in. yaw 0 faces north (-z)
|
||||||
|
function flyover(camera: Camera, t: number) {
|
||||||
|
const angle = t * Math.PI * 2;
|
||||||
|
const radius = LEVEL_RADIUS * 16 * 0.6;
|
||||||
|
place(camera, Math.cos(angle) * radius, 120, Math.sin(angle) * radius, Math.PI - angle - 0.3, -0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
// what apply_change takes for a block value
|
||||||
|
function block_id(value: number): readonly [string, number] {
|
||||||
|
return [EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK)!.id, value >>> STATE_SHIFT];
|
||||||
|
}
|
||||||
|
|
||||||
|
// navigator.userAgentData, chromium's client hints, which the dom typings don't have
|
||||||
|
interface UserAgentData {
|
||||||
|
getHighEntropyValues(hints: string[]): Promise<{
|
||||||
|
platform?: string;
|
||||||
|
platformVersion?: string;
|
||||||
|
architecture?: string;
|
||||||
|
fullVersionList?: { brand: string; version: string }[];
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the first that matches
|
||||||
|
const BROWSERS: [RegExp, string][] = [
|
||||||
|
[/Firefox\/([\d.]+)/, "Firefox"],
|
||||||
|
[/Edg\/([\d.]+)/, "Edge"],
|
||||||
|
[/OPR\/([\d.]+)/, "Opera"],
|
||||||
|
[/Chrome\/([\d.]+)/, "Chrome"],
|
||||||
|
[/Version\/([\d.]+).*Safari/, "Safari"],
|
||||||
|
];
|
||||||
|
const SYSTEMS: [RegExp, string][] = [
|
||||||
|
[/Windows/, "Windows"],
|
||||||
|
[/iPhone|iPad/, "iOS"],
|
||||||
|
[/Mac OS X/, "macOS"],
|
||||||
|
[/Android/, "Android"],
|
||||||
|
[/CrOS/, "ChromeOS"],
|
||||||
|
[/Linux/, "Linux"],
|
||||||
|
];
|
||||||
|
|
||||||
|
// what's running the benchmark. the browser and the system come from the user agent, then from the client hints in
|
||||||
|
// browsers that have them, which say more and come a moment later
|
||||||
|
function system_info(workers: number): SystemInfo {
|
||||||
|
const agent = navigator.userAgent;
|
||||||
|
const browser = BROWSERS.find(([pattern]) => pattern.test(agent));
|
||||||
|
const architecture = /x86_64|x64|Win64/.test(agent) ? " x86_64" : /aarch64|arm64/i.test(agent) ? " arm64" : "";
|
||||||
|
const { vendor = "", architecture: gpu_architecture = "", description = "" } = adapter_info ?? {};
|
||||||
|
const gpu = [vendor, gpu_architecture].filter(Boolean).join(" ") || "unknown gpu";
|
||||||
|
const info: SystemInfo = {
|
||||||
|
browser: browser ? `${browser[1]} ${agent.match(browser[0])![1]}` : "unknown browser",
|
||||||
|
os: (SYSTEMS.find(([pattern]) => pattern.test(agent))?.[1] ?? "unknown system") + architecture,
|
||||||
|
user_agent: agent,
|
||||||
|
cpu_threads: navigator.hardwareConcurrency,
|
||||||
|
memory_gb: (navigator as { deviceMemory?: number }).deviceMemory,
|
||||||
|
gpu: description ? `${gpu} (${description})` : gpu,
|
||||||
|
gpu_features: [...device.features].sort(),
|
||||||
|
timestamps: gpu_timer?.supported ?? false,
|
||||||
|
canvas_format: navigator.gpu.getPreferredCanvasFormat(),
|
||||||
|
// the desktop app's window is drawn a pixel to a pixel
|
||||||
|
device_pixel_ratio: globalThis.devicePixelRatio ?? 1,
|
||||||
|
screen: globalThis.screen && `${screen.width}x${screen.height}`,
|
||||||
|
workers,
|
||||||
|
};
|
||||||
|
const hints = (navigator as { userAgentData?: UserAgentData }).userAgentData;
|
||||||
|
hints?.getHighEntropyValues(["architecture", "platformVersion", "fullVersionList"]).then((values) => {
|
||||||
|
const brands = values.fullVersionList ?? [];
|
||||||
|
const brand = brands.find(({ brand }) => !/Not.A.Brand|Chromium/i.test(brand)) ??
|
||||||
|
brands.find(({ brand }) => brand === "Chromium");
|
||||||
|
if (brand) info.browser = `${brand.brand} ${brand.version}`;
|
||||||
|
info.os = [values.platform, values.platformVersion, values.architecture].filter(Boolean).join(" ");
|
||||||
|
}).catch(() => {});
|
||||||
|
return info;
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the render benchmark's results and how they're written out: a table to read, then the same as json, which
|
||||||
|
// 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
|
||||||
|
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
|
||||||
|
// 99.9%) of the others were faster than
|
||||||
|
export interface FrameStats {
|
||||||
|
frames: number;
|
||||||
|
fps: number;
|
||||||
|
median_fps: number;
|
||||||
|
low_1_fps: number;
|
||||||
|
low_01_fps: number;
|
||||||
|
p99_ms: number;
|
||||||
|
max_ms: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimeStats {
|
||||||
|
mean_ms: number;
|
||||||
|
p99_ms: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SceneResult {
|
||||||
|
// frames as the display paces them
|
||||||
|
paced?: FrameStats;
|
||||||
|
// frames back to back, see render_debug.uncapped. only how many, the time between them says nothing since they
|
||||||
|
// come in bursts between the display's refreshes when the gpu is behind
|
||||||
|
uncapped_fps?: number;
|
||||||
|
// the main thread's and the gpu's time per frame while paced. the gpu's only with timestamp queries
|
||||||
|
cpu?: TimeStats;
|
||||||
|
gpu?: TimeStats;
|
||||||
|
// what the first paced frame drew, which runs of the same version should about agree on
|
||||||
|
draw_calls: number;
|
||||||
|
quads: number;
|
||||||
|
sections_in_view: number;
|
||||||
|
entities_in_view: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// meshing every chunk of the level that can be
|
||||||
|
export interface MeshingResult {
|
||||||
|
chunks: number;
|
||||||
|
ms: number;
|
||||||
|
paced?: FrameStats;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SystemInfo {
|
||||||
|
browser: string;
|
||||||
|
os: string;
|
||||||
|
user_agent: string;
|
||||||
|
cpu_threads: number;
|
||||||
|
// only chromium says, rounded down to a power of two and at most 8
|
||||||
|
memory_gb?: number;
|
||||||
|
gpu: string;
|
||||||
|
gpu_features: string[];
|
||||||
|
// whether the gpu times are there
|
||||||
|
timestamps: boolean;
|
||||||
|
canvas_format: string;
|
||||||
|
// the median fps where nothing is drawn, which is the display's refresh when the browser holds frames to it
|
||||||
|
refresh_hz?: number;
|
||||||
|
device_pixel_ratio: number;
|
||||||
|
// the browser's, the desktop app doesn't know it
|
||||||
|
screen?: string;
|
||||||
|
// meshing workers, see ChunkWorkerPool
|
||||||
|
workers: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BenchmarkReport {
|
||||||
|
version: number;
|
||||||
|
date: string;
|
||||||
|
system: SystemInfo;
|
||||||
|
// "id version"
|
||||||
|
mods: string[];
|
||||||
|
resolution: string;
|
||||||
|
// the f3 window's switch, see ClientLevel.use_render_regions
|
||||||
|
render_regions?: boolean;
|
||||||
|
level: { chunks: number; build_ms: number };
|
||||||
|
first_mesh: MeshingResult;
|
||||||
|
remesh: MeshingResult;
|
||||||
|
scenes: Record<string, SceneResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function frame_stats(intervals: number[]): FrameStats | undefined {
|
||||||
|
if (intervals.length === 0) return undefined;
|
||||||
|
const sorted = [...intervals].sort((a, b) => a - b);
|
||||||
|
const mean = sorted.reduce((sum, ms) => sum + ms, 0) / sorted.length;
|
||||||
|
return {
|
||||||
|
frames: sorted.length,
|
||||||
|
fps: 1000 / mean,
|
||||||
|
median_fps: 1000 / percentile(sorted, 0.5),
|
||||||
|
low_1_fps: 1000 / percentile(sorted, 0.99),
|
||||||
|
low_01_fps: 1000 / percentile(sorted, 0.999),
|
||||||
|
p99_ms: percentile(sorted, 0.99),
|
||||||
|
max_ms: sorted[sorted.length - 1],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function time_stats(times: number[]): TimeStats | undefined {
|
||||||
|
if (times.length === 0) return undefined;
|
||||||
|
const sorted = [...times].sort((a, b) => a - b);
|
||||||
|
return { mean_ms: sorted.reduce((sum, ms) => sum + ms, 0) / sorted.length, p99_ms: percentile(sorted, 0.99) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// the smallest value that at least q of them are at or under
|
||||||
|
function percentile(sorted: number[], q: number) {
|
||||||
|
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))];
|
||||||
|
}
|
||||||
|
|
||||||
|
// markdown, to paste where it's read, with the whole report as json at the end
|
||||||
|
export function format_report(report: BenchmarkReport): string {
|
||||||
|
const { system, first_mesh, remesh } = report;
|
||||||
|
const fps = (value?: number) => value === undefined ? "-" : value.toFixed(1);
|
||||||
|
const ms = (value?: number) => value === undefined ? "-" : value.toFixed(2);
|
||||||
|
const seconds = (ms: number) => `${(ms / 1000).toFixed(2)} s`;
|
||||||
|
const meshing = ({ chunks, ms }: MeshingResult) => `${seconds(ms)} (${Math.round(chunks / ms * 1000)} chunks/s)`;
|
||||||
|
const memory = system.memory_gb ? `, ${system.memory_gb} GB` : "";
|
||||||
|
const refresh = system.refresh_hz ? `, ${system.refresh_hz} Hz` : "";
|
||||||
|
const lines = [
|
||||||
|
`## cubi render benchmark ${report.version}`,
|
||||||
|
"",
|
||||||
|
`${system.browser} on ${system.os}, ${system.gpu}`,
|
||||||
|
`${system.cpu_threads} threads${memory}${refresh}, drawn at ${report.resolution}, ${system.workers} mesh workers` +
|
||||||
|
(system.timestamps ? "" : ", no gpu timestamps") + (report.render_regions ? ", render regions" : ""),
|
||||||
|
`${report.date}, mods: ${report.mods.join(", ") || "none"}`,
|
||||||
|
"",
|
||||||
|
"| scene | fps | 1% low | 0.1% low | uncapped fps | cpu ms | gpu ms | draw calls | quads |",
|
||||||
|
"|---|---:|---:|---:|---:|---:|---:|---:|---:|",
|
||||||
|
];
|
||||||
|
for (const [name, scene] of Object.entries(report.scenes)) {
|
||||||
|
const { paced } = scene;
|
||||||
|
lines.push(
|
||||||
|
`| ${name} | ${fps(paced?.fps)} | ${fps(paced?.low_1_fps)} | ${fps(paced?.low_01_fps)} | ` +
|
||||||
|
`${fps(scene.uncapped_fps)} | ${ms(scene.cpu?.mean_ms)} | ${ms(scene.gpu?.mean_ms)} | ` +
|
||||||
|
`${scene.draw_calls} | ${scene.quads.toLocaleString("en")} |`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
lines.push(
|
||||||
|
"",
|
||||||
|
`Meshing the level's ${first_mesh.chunks} chunks took ${meshing(first_mesh)} the first time and ` +
|
||||||
|
`${meshing(remesh)} again. Building it took ${seconds(report.level.build_ms)} of javascript.`,
|
||||||
|
"",
|
||||||
|
"```json",
|
||||||
|
JSON.stringify(report, (_, value) => typeof value === "number" ? Math.round(value * 100) / 100 : value),
|
||||||
|
"```",
|
||||||
|
);
|
||||||
|
return lines.join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// the report in what format_report wrote, or json on its own
|
||||||
|
export function parse_report(text: string): BenchmarkReport {
|
||||||
|
const json = text.match(/```json\n([\s\S]*?)\n```/)?.[1] ?? text;
|
||||||
|
return JSON.parse(json);
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
};
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { Entity } from "./entity/entity.ts";
|
import type { Entity } from "./entity/entity.ts";
|
||||||
|
|
||||||
// where the world is drawn from. like minecraft's Camera it isn't an entity, it's moved to one's eyes every frame
|
// where the world is drawn from. like minecraft's Camera it isn't an entity, it's moved to one's eyes every frame
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import type { FromChunkWorker, ToChunkWorker } from "./workers/chunk_messages.ts";
|
import type { FromChunkWorker, ToChunkWorker } from "./workers/chunk_messages.ts";
|
||||||
|
|
||||||
// leave a core for the main thread, more than 4 doesnt help much
|
// leave a core for the main thread, more than 4 doesnt help much
|
||||||
|
|||||||
+172
-32
@@ -1,23 +1,38 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { ClientLevel } from "./level/client_level.ts";
|
import { ClientLevel } from "./level/client_level.ts";
|
||||||
import type { BlockHitResult } from "./level/client_level.ts";
|
import type { BlockHitResult } from "./level/client_level.ts";
|
||||||
import { LocalPlayer } from "./entity/local_player.ts";
|
import { LocalPlayer } from "./entity/local_player.ts";
|
||||||
import { RemotePlayer } from "./entity/remote_player.ts";
|
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 type { Entity } from "./entity/entity.ts";
|
||||||
import { Camera } from "./camera.ts";
|
import { Camera } from "./camera.ts";
|
||||||
import { Options } from "./options.ts";
|
import { Options } from "./options.ts";
|
||||||
import { MultiPlayerGameMode } from "./game_mode.ts";
|
import { MultiPlayerGameMode } from "./game_mode.ts";
|
||||||
import { ClientPacketListener } from "./packet_listener.ts";
|
import { ClientPacketListener } from "./packet_listener.ts";
|
||||||
|
import { profiler } from "./profiler.ts";
|
||||||
import { GameRenderer } from "./rendering/game_renderer.ts";
|
import { GameRenderer } from "./rendering/game_renderer.ts";
|
||||||
import { ChatComponent } from "./gui/chat_component.ts";
|
import { ChatComponent } from "./gui/chat_component.ts";
|
||||||
import { GuiInventoryScreen, GuiScreen } from "./gui/gui_screen.ts";
|
import { GuiMenuScreen, GuiScreen } from "./gui/gui_screen.ts";
|
||||||
import { GuiPlayerInventory } from "./gui/gui_player_inventory.ts";
|
import { GuiPlayerInventory } from "./gui/gui_player_inventory.ts";
|
||||||
import { GuiChat } from "./gui/gui_chat.ts";
|
import { GuiChat } from "./gui/gui_chat.ts";
|
||||||
import { InputManager } from "./input_manager.ts";
|
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 { PLAYER_MENU } from "@/common/protocol.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import type { EntityJson } from "@/common/mod_data.ts";
|
||||||
|
import { tick_texture_animations } from "./texture_animations.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
|
||||||
|
const USE_REPEAT_MS = 200;
|
||||||
|
|
||||||
// after a long stall (a hidden tab, a debugger) the game skips ahead instead of running every missed tick at once
|
// after a long stall (a hidden tab, a debugger) the game skips ahead instead of running every missed tick at once
|
||||||
const MAX_TICKS_PER_FRAME = 10;
|
const MAX_TICKS_PER_FRAME = 10;
|
||||||
@@ -39,12 +54,20 @@ export class Client {
|
|||||||
screens: GuiScreen[] = [];
|
screens: GuiScreen[] = [];
|
||||||
// what the player is looking at, updated every frame
|
// what the player is looking at, updated every frame
|
||||||
hit_result: BlockHitResult | undefined;
|
hit_result: BlockHitResult | undefined;
|
||||||
|
// the entity or other player being looked at, closer than any block. hit_result is undefined then
|
||||||
|
entity_hit: Entity | undefined;
|
||||||
debugging = false;
|
debugging = false;
|
||||||
|
// started from the f3 performance window
|
||||||
|
benchmark: RenderBenchmark | undefined;
|
||||||
|
|
||||||
// seconds of game time not ticked yet
|
// seconds of game time not ticked yet
|
||||||
#pending_time = 0;
|
#pending_time = 0;
|
||||||
// whether the attack button is held on a block, breaking it advances every tick
|
// whether the attack button is held on a block, breaking it advances every tick
|
||||||
#attacking = false;
|
#attacking = false;
|
||||||
|
// when holding the use button on a block uses it again, see USE_REPEAT_MS
|
||||||
|
#next_use = 0;
|
||||||
|
// a use was sent and the use button hasn't been let go of since, see #handle_block_interaction
|
||||||
|
#use_held = false;
|
||||||
#stopped = false;
|
#stopped = false;
|
||||||
// the render distance the server was last told, it sends chunks for it
|
// the render distance the server was last told, it sends chunks for it
|
||||||
#sent_view_distance: number;
|
#sent_view_distance: number;
|
||||||
@@ -55,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;
|
||||||
|
|
||||||
@@ -65,6 +88,8 @@ export class Client {
|
|||||||
this.player.yaw = spawn.yaw;
|
this.player.yaw = spawn.yaw;
|
||||||
this.player.pitch = spawn.pitch;
|
this.player.pitch = spawn.pitch;
|
||||||
this.player.inventories.hotbar_selected = connection.selected_slot;
|
this.player.inventories.hotbar_selected = connection.selected_slot;
|
||||||
|
this.player.inventories.extra_slots = connection.player_menu;
|
||||||
|
this.player.inventories.extra = new Container(connection.player_menu.length);
|
||||||
this.level.add_entity(this.player);
|
this.level.add_entity(this.player);
|
||||||
for (const info of connection.initial_players) {
|
for (const info of connection.initial_players) {
|
||||||
this.level.add_entity(new RemotePlayer(this.level, info));
|
this.level.add_entity(new RemotePlayer(this.level, info));
|
||||||
@@ -87,48 +112,92 @@ export class Client {
|
|||||||
this.screens.push(screen);
|
this.screens.push(screen);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the player closed the one on top
|
||||||
pop_screen() {
|
pop_screen() {
|
||||||
this.screens.pop()?.on_close();
|
const screen = this.screens.pop();
|
||||||
|
screen?.on_close();
|
||||||
|
screen?.on_removed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// the player closed this one, wherever it is
|
||||||
|
close_screen(screen: GuiScreen) {
|
||||||
|
if (!this.screens.includes(screen)) return;
|
||||||
|
this.screens = this.screens.filter((s) => s !== screen);
|
||||||
|
screen.on_close();
|
||||||
|
screen.on_removed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// takes these off without closing them, like when the server opens a menu or closes it
|
||||||
|
remove_screens(which: (screen: GuiScreen) => boolean) {
|
||||||
|
const removed = this.screens.filter(which);
|
||||||
|
this.screens = this.screens.filter((s) => !which(s));
|
||||||
|
for (const screen of removed) screen.on_removed();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
// one frame: input, as many ticks as are due, then drawing between the last tick and the next
|
// one frame: input, as many ticks as are due, then drawing between the last tick and the next. while the benchmark
|
||||||
|
// runs, it ticks and draws its own level instead and the world waits, so what's around the player doesn't change
|
||||||
|
// its numbers
|
||||||
run_frame(delta: number) {
|
run_frame(delta: number) {
|
||||||
if (this.#stopped) {
|
if (this.#stopped) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const screen = this.screen;
|
if (this.benchmark) {
|
||||||
this.screen?.on_tick(delta);
|
this.benchmark.frame();
|
||||||
// a screen that closed itself just now, like chat on enter, had this frame's keys
|
} else {
|
||||||
this.#handle_keybinds(screen !== undefined && this.screen === undefined);
|
const screen = this.screen;
|
||||||
|
this.screen?.on_tick(delta);
|
||||||
|
// a screen that closed itself just now, like chat on enter, had this frame's keys
|
||||||
|
this.#handle_keybinds(screen !== undefined && this.screen === undefined);
|
||||||
|
}
|
||||||
|
|
||||||
this.#pending_time += delta;
|
this.#pending_time += delta;
|
||||||
let ticks = 0;
|
let ticks = 0;
|
||||||
while (this.#pending_time >= TICK_DELTA && ticks < MAX_TICKS_PER_FRAME) {
|
const stopped = profiler.section("ticks", () => {
|
||||||
this.tick();
|
while (this.#pending_time >= TICK_DELTA && ticks < MAX_TICKS_PER_FRAME) {
|
||||||
if (this.#stopped) {
|
if (this.benchmark) this.benchmark.tick();
|
||||||
return;
|
else this.tick();
|
||||||
|
if (this.#stopped) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
this.#pending_time -= TICK_DELTA;
|
||||||
|
ticks += 1;
|
||||||
}
|
}
|
||||||
this.#pending_time -= TICK_DELTA;
|
return false;
|
||||||
ticks += 1;
|
});
|
||||||
|
if (stopped) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (ticks === MAX_TICKS_PER_FRAME) {
|
if (ticks === MAX_TICKS_PER_FRAME) {
|
||||||
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
|
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.game_renderer.render(this, this.#pending_time / TICK_DELTA);
|
const partial_tick = 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
|
||||||
@@ -151,6 +220,7 @@ export class Client {
|
|||||||
this.connection.send({ type: "view_distance", distance: view_distance });
|
this.connection.send({ type: "view_distance", distance: view_distance });
|
||||||
}
|
}
|
||||||
this.level.tick();
|
this.level.tick();
|
||||||
|
tick_texture_animations();
|
||||||
}
|
}
|
||||||
|
|
||||||
// closed_screen: a screen closed this frame and took its keys, so they don't also open the inventory or pick a
|
// closed_screen: a screen closed this frame and took its keys, so they don't also open the inventory or pick a
|
||||||
@@ -169,7 +239,7 @@ export class Client {
|
|||||||
}
|
}
|
||||||
InputManager.set_mouse_grabbed(!this.screen);
|
InputManager.set_mouse_grabbed(!this.screen);
|
||||||
|
|
||||||
this.hit_result = this.level.pick(player.x, player.y + player.eye_height, player.z, player.yaw, player.pitch);
|
this.#pick();
|
||||||
this.#handle_block_interaction();
|
this.#handle_block_interaction();
|
||||||
|
|
||||||
if (!this.screen && !closed_screen) {
|
if (!this.screen && !closed_screen) {
|
||||||
@@ -183,8 +253,8 @@ export class Client {
|
|||||||
|
|
||||||
if (InputManager.is_key_pressed(options.key_inventory)) {
|
if (InputManager.is_key_pressed(options.key_inventory)) {
|
||||||
if (!this.screen) {
|
if (!this.screen) {
|
||||||
this.push_screen(new GuiPlayerInventory(player.inventories, (m) => this.connection.send(m)));
|
this.push_screen(new GuiPlayerInventory(player, (m) => this.connection.send(m)));
|
||||||
} else if (this.screen instanceof GuiInventoryScreen) {
|
} else if (this.screen instanceof GuiMenuScreen) {
|
||||||
this.pop_screen();
|
this.pop_screen();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -202,7 +272,7 @@ export class Client {
|
|||||||
const lost_mouse = InputManager.take_lost_pointer_lock();
|
const lost_mouse = InputManager.take_lost_pointer_lock();
|
||||||
if (InputManager.is_key_pressed("Escape")) {
|
if (InputManager.is_key_pressed("Escape")) {
|
||||||
if (this.screen) {
|
if (this.screen) {
|
||||||
this.pop_screen();
|
if (this.screen.close_on_escape()) this.pop_screen();
|
||||||
} else {
|
} else {
|
||||||
this.push_screen(new PauseScreen(this));
|
this.push_screen(new PauseScreen(this));
|
||||||
}
|
}
|
||||||
@@ -223,18 +293,46 @@ export class Client {
|
|||||||
const inventories = this.player.inventories;
|
const inventories = this.player.inventories;
|
||||||
const screen = this.screen;
|
const screen = this.screen;
|
||||||
if (!screen) {
|
if (!screen) {
|
||||||
this.game_mode.drop_item(inventories.inventory, "inventory", inventories.hotbar_selected, all);
|
// the hotbar slot of menu 0, they're the same numbers
|
||||||
|
const slot = inventories.hotbar_selected;
|
||||||
|
this.game_mode.drop_item(inventories.inventory, slot, PLAYER_MENU, slot, all);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const slot = screen instanceof GuiInventoryScreen ? screen.hovering : undefined;
|
const slot = screen instanceof GuiMenuScreen ? screen.hovering : undefined;
|
||||||
const container = slot && screen instanceof GuiInventoryScreen
|
if (screen instanceof GuiMenuScreen && slot && !slot.output && !inventories.cursor.item) {
|
||||||
? screen.get_container(slot.container)
|
const index = screen.menu.slots.indexOf(slot);
|
||||||
: undefined;
|
this.game_mode.drop_item(slot.container, slot.index, screen.menu.id, index, all);
|
||||||
if (slot && container && !slot.output && !inventories.cursor.item) {
|
|
||||||
this.game_mode.drop_item(container, slot.container, slot.index, all);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// what's under the crosshair: an entity, or the first block in front of it
|
||||||
|
#pick() {
|
||||||
|
const player = this.player;
|
||||||
|
const eye_y = player.y + player.eye_height;
|
||||||
|
const picked = this.level.pick_entity(
|
||||||
|
player.x,
|
||||||
|
eye_y,
|
||||||
|
player.z,
|
||||||
|
player.yaw,
|
||||||
|
player.pitch,
|
||||||
|
player.entity_interaction_range,
|
||||||
|
(entity) =>
|
||||||
|
entity instanceof RemotePlayer ||
|
||||||
|
(entity instanceof RemoteEntity && !entity.dead && is_pickable(entity)),
|
||||||
|
);
|
||||||
|
// a block in front of the entity hides it
|
||||||
|
this.hit_result = this.level.pick(
|
||||||
|
player.x,
|
||||||
|
eye_y,
|
||||||
|
player.z,
|
||||||
|
player.yaw,
|
||||||
|
player.pitch,
|
||||||
|
picked?.distance ?? player.block_interaction_range,
|
||||||
|
this.game_mode.held_item()?.targets_fluids,
|
||||||
|
);
|
||||||
|
this.entity_hit = picked && !this.hit_result ? picked.entity : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
// clicks happen right away, holding to break advances in tick()
|
// clicks happen right away, holding to break advances in tick()
|
||||||
#handle_block_interaction() {
|
#handle_block_interaction() {
|
||||||
const hit = this.hit_result;
|
const hit = this.hit_result;
|
||||||
@@ -244,24 +342,53 @@ export class Client {
|
|||||||
if (!attacking || !hit) {
|
if (!attacking || !hit) {
|
||||||
this.game_mode.stop_destroy_block();
|
this.game_mode.stop_destroy_block();
|
||||||
}
|
}
|
||||||
|
// letting go stops using an item over time, like shooting a bow, even with a screen open by then. the server
|
||||||
|
// may not have said it's using one yet, so it's sent after every use
|
||||||
|
if (this.#use_held && !InputManager.is_mouse_down(2)) {
|
||||||
|
this.#use_held = false;
|
||||||
|
this.connection.send({ type: "release_use" });
|
||||||
|
}
|
||||||
if (this.screen) {
|
if (this.screen) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// the held item swings on every click, and keeps swinging while breaking, like minecraft
|
// middle click in creative gives the block under the crosshair, like minecraft's pick block
|
||||||
if (InputManager.is_mouse_pressed(0) || InputManager.is_mouse_pressed(2) || (attacking && hit)) {
|
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
|
||||||
|
const now = performance.now();
|
||||||
|
const use_pressed = InputManager.is_mouse_pressed(2) && !this.player.using_item;
|
||||||
|
const using = use_pressed ||
|
||||||
|
(hit && InputManager.is_mouse_down(2) && now >= this.#next_use && !this.player.using_item);
|
||||||
|
if (using) {
|
||||||
|
this.#next_use = now + USE_REPEAT_MS;
|
||||||
|
this.#use_held = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the held item swings on every click and use, and keeps swinging while breaking, like minecraft
|
||||||
|
if (InputManager.is_mouse_pressed(0) || using || (attacking && hit)) {
|
||||||
this.game_renderer.hand.swing();
|
this.game_renderer.hand.swing();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this.entity_hit && InputManager.is_mouse_pressed(0)) {
|
||||||
|
this.game_mode.attack(this.entity_hit);
|
||||||
|
}
|
||||||
if (hit) {
|
if (hit) {
|
||||||
if (InputManager.is_mouse_pressed(0)) {
|
if (InputManager.is_mouse_pressed(0)) {
|
||||||
this.game_mode.start_destroy_block(hit);
|
this.game_mode.start_destroy_block(hit);
|
||||||
}
|
}
|
||||||
if (!attacking && InputManager.is_mouse_pressed(2)) {
|
if (!attacking && using) {
|
||||||
this.game_mode.use_item_on(hit);
|
this.game_mode.use_item_on(hit);
|
||||||
}
|
}
|
||||||
} else if (InputManager.is_mouse_pressed(2)) {
|
} else if (use_pressed && this.entity_hit) {
|
||||||
|
this.game_mode.interact(this.entity_hit);
|
||||||
|
} else if (use_pressed) {
|
||||||
this.game_mode.use_item();
|
this.game_mode.use_item();
|
||||||
|
} else if (!this.entity_hit && InputManager.is_mouse_pressed(0)) {
|
||||||
|
this.game_mode.swing();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,7 +397,12 @@ export class Client {
|
|||||||
const previous = inventories.hotbar_selected;
|
const previous = inventories.hotbar_selected;
|
||||||
|
|
||||||
const scroll = InputManager.get_wheel_delta();
|
const scroll = InputManager.get_wheel_delta();
|
||||||
if (scroll > 0) {
|
// at a block that takes the mouse wheel, like a pulse repeater's delay, it goes to the block instead
|
||||||
|
const hit = this.hit_result;
|
||||||
|
if (scroll !== 0 && hit && EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)?.scrollable) {
|
||||||
|
const { x, y, z, face } = hit;
|
||||||
|
this.connection.send({ type: "scroll_block", x, y, z, face, hit: hit.hit, amount: scroll < 0 ? 1 : -1 });
|
||||||
|
} else if (scroll > 0) {
|
||||||
inventories.hotbar_selected = Math.min(8, inventories.hotbar_selected + 1);
|
inventories.hotbar_selected = Math.min(8, inventories.hotbar_selected + 1);
|
||||||
} else if (scroll < 0) {
|
} else if (scroll < 0) {
|
||||||
inventories.hotbar_selected = Math.max(0, inventories.hotbar_selected - 1);
|
inventories.hotbar_selected = Math.max(0, inventories.hotbar_selected - 1);
|
||||||
@@ -283,6 +415,14 @@ export class Client {
|
|||||||
|
|
||||||
if (inventories.hotbar_selected !== previous) {
|
if (inventories.hotbar_selected !== previous) {
|
||||||
this.connection.send({ type: "select_slot", slot: inventories.hotbar_selected });
|
this.connection.send({ type: "select_slot", slot: inventories.hotbar_selected });
|
||||||
|
// the server starts the attack cooldown over too
|
||||||
|
this.player.last_attack = performance.now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// what the crosshair can be on: mobs and objects, not scripted entities like the fishing hook. kinds the client doesn't
|
||||||
|
// know are left to the server
|
||||||
|
function is_pickable(entity: RemoteEntity) {
|
||||||
|
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,50 +0,0 @@
|
|||||||
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");
|
|
||||||
item.textContent = `${mod.name} ${mod.version} (${mod.id})`;
|
|
||||||
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);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
+17
-99
@@ -1,6 +1,10 @@
|
|||||||
import { point_inside_rec } from "$/common/utils.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { InputManager } from "$/client/input_manager.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { begin_clip, draw_rect, draw_rect_stroke, draw_text, end_clip, measure_text } from "./renderer/mod.ts";
|
|
||||||
|
import { point_inside_rec } from "@/common/utils.ts";
|
||||||
|
import { InputManager } from "@/client/input_manager.ts";
|
||||||
|
import { TextInput } from "@/client/gui/widgets.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;
|
||||||
const RESIZE_SIZE = 12;
|
const RESIZE_SIZE = 12;
|
||||||
@@ -18,20 +22,11 @@ interface WindowState {
|
|||||||
content_height: number;
|
content_height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TextInputState {
|
|
||||||
value: string;
|
|
||||||
caret: number;
|
|
||||||
focused: boolean;
|
|
||||||
last_blink: number;
|
|
||||||
show_caret: boolean;
|
|
||||||
key_repeat_timer: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class DebugUI {
|
export class DebugUI {
|
||||||
static windows = new Map<string, WindowState>();
|
static windows = new Map<string, WindowState>();
|
||||||
static current_window: WindowState | undefined = undefined;
|
static current_window: WindowState | undefined = undefined;
|
||||||
|
|
||||||
static text_inputs = new Map<string, TextInputState>();
|
static text_inputs = new Map<string, TextInput>();
|
||||||
static active_text_input: string | undefined = undefined;
|
static active_text_input: string | undefined = undefined;
|
||||||
|
|
||||||
static open_sections = new Map<string, boolean>();
|
static open_sections = new Map<string, boolean>();
|
||||||
@@ -321,15 +316,7 @@ export class DebugUI {
|
|||||||
|
|
||||||
let state = this.text_inputs.get(id);
|
let state = this.text_inputs.get(id);
|
||||||
if (!state) {
|
if (!state) {
|
||||||
// initial state
|
state = new TextInput(value, Infinity);
|
||||||
state = {
|
|
||||||
value,
|
|
||||||
caret: value.length,
|
|
||||||
focused: false,
|
|
||||||
last_blink: performance.now(),
|
|
||||||
show_caret: true,
|
|
||||||
key_repeat_timer: 0,
|
|
||||||
};
|
|
||||||
this.text_inputs.set(id, state);
|
this.text_inputs.set(id, state);
|
||||||
}
|
}
|
||||||
// update on every call
|
// update on every call
|
||||||
@@ -347,11 +334,9 @@ export class DebugUI {
|
|||||||
if (hovered && InputManager.is_mouse_pressed(0)) {
|
if (hovered && InputManager.is_mouse_pressed(0)) {
|
||||||
InputManager.consume_mouse(0);
|
InputManager.consume_mouse(0);
|
||||||
this.active_text_input = id;
|
this.active_text_input = id;
|
||||||
state.focused = true;
|
state.move_caret(value.length);
|
||||||
state.caret = value.length;
|
|
||||||
} else if (InputManager.is_mouse_pressed(0) && !hovered) {
|
} else if (InputManager.is_mouse_pressed(0) && !hovered) {
|
||||||
if (this.active_text_input === id) {
|
if (this.active_text_input === id) {
|
||||||
state.focused = false;
|
|
||||||
this.active_text_input = undefined;
|
this.active_text_input = undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -359,18 +344,7 @@ export class DebugUI {
|
|||||||
const is_active = this.active_text_input === id;
|
const is_active = this.active_text_input === id;
|
||||||
|
|
||||||
if (is_active) {
|
if (is_active) {
|
||||||
this.#handle_text_editing(state);
|
state.handle_keys();
|
||||||
}
|
|
||||||
|
|
||||||
// overkill?
|
|
||||||
if (is_active) {
|
|
||||||
const now = performance.now();
|
|
||||||
if (now - state.last_blink > 500) {
|
|
||||||
state.show_caret = !state.show_caret;
|
|
||||||
state.last_blink = now;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
state.show_caret = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// draw box
|
// draw box
|
||||||
@@ -393,14 +367,14 @@ export class DebugUI {
|
|||||||
|
|
||||||
const text_x = x + 6;
|
const text_x = x + 6;
|
||||||
|
|
||||||
draw_text(state.value, x + 6, y + 4);
|
if (is_active) {
|
||||||
|
state.draw_selection(text_x, y + 4, height - 8, 1);
|
||||||
|
}
|
||||||
|
draw_text(state.value, text_x, y + 4);
|
||||||
|
|
||||||
// caret !
|
// caret !
|
||||||
if (is_active && state.show_caret) {
|
if (is_active && TextInput.caret_visible()) {
|
||||||
const before_text = state.value.substring(0, state.caret);
|
draw_rect(state.caret_x(text_x, 1), y + 4, 1, height - 4);
|
||||||
const caret_x = text_x + measure_text(before_text);
|
|
||||||
|
|
||||||
draw_rect(caret_x, y + 4, 1, height - 4);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.cursor_y += height + PADDING;
|
this.cursor_y += height + PADDING;
|
||||||
@@ -456,60 +430,4 @@ export class DebugUI {
|
|||||||
// thumb
|
// thumb
|
||||||
draw_rect(x, thumb_y, scrollbar_width, thumb_height, [0x88 / 255, 0x88 / 255, 0x88 / 255, 1]);
|
draw_rect(x, thumb_y, scrollbar_width, thumb_height, [0x88 / 255, 0x88 / 255, 0x88 / 255, 1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
static #handle_text_editing(state: TextInputState) {
|
|
||||||
const now = performance.now();
|
|
||||||
const repeat_delay = 400;
|
|
||||||
const repeat_rate = 40;
|
|
||||||
|
|
||||||
function allow_repeat(): boolean {
|
|
||||||
if (InputManager.is_key_pressed("Backspace")) {
|
|
||||||
state.key_repeat_timer = now;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (InputManager.is_key_down("Backspace")) {
|
|
||||||
if (now - state.key_repeat_timer > repeat_delay) {
|
|
||||||
state.key_repeat_timer = now - (repeat_delay - repeat_rate);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (allow_repeat()) {
|
|
||||||
if (state.caret > 0) {
|
|
||||||
state.value = state.value.slice(0, state.caret - 1) + state.value.slice(state.caret);
|
|
||||||
state.caret -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (InputManager.is_key_pressed("Delete")) {
|
|
||||||
state.value = state.value.slice(0, state.caret) + state.value.slice(state.caret + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (InputManager.is_key_pressed("ArrowLeft")) {
|
|
||||||
state.caret = Math.max(0, state.caret - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (InputManager.is_key_pressed("ArrowRight")) {
|
|
||||||
state.caret = Math.min(state.value.length, state.caret + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (InputManager.is_key_pressed("Home")) {
|
|
||||||
state.caret = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (InputManager.is_key_pressed("End")) {
|
|
||||||
state.caret = state.value.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
const typed = InputManager.get_typed_characters();
|
|
||||||
|
|
||||||
for (const char of typed) {
|
|
||||||
state.value = state.value.slice(0, state.caret) + char + state.value.slice(state.caret);
|
|
||||||
state.caret += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// what engine access mods get as engine.client, in client phases. see docs/modding/misc/engine.md
|
||||||
|
import { Client } from "./client.ts";
|
||||||
|
import { Entity } from "./entity/entity.ts";
|
||||||
|
import { LocalPlayer } from "./entity/local_player.ts";
|
||||||
|
import { Player } from "./entity/player.ts";
|
||||||
|
import { RemoteEntity } from "./entity/remote_entity.ts";
|
||||||
|
import { RemotePlayer } from "./entity/remote_player.ts";
|
||||||
|
import { ItemEntity } from "./entity/item_entity.ts";
|
||||||
|
import { ClientLevel } from "./level/client_level.ts";
|
||||||
|
import { GameRenderer } from "./rendering/game_renderer.ts";
|
||||||
|
import { LevelRenderer } from "./rendering/level_renderer.ts";
|
||||||
|
import { HandRenderer } from "./rendering/hand_renderer.ts";
|
||||||
|
import { Camera } from "./camera.ts";
|
||||||
|
import { InputManager } from "./input_manager.ts";
|
||||||
|
import { ClientMenu } from "./menu.ts";
|
||||||
|
import { GuiMenuScreen, GuiScreen } from "./gui/gui_screen.ts";
|
||||||
|
|
||||||
|
// built when it's exposed, not when this module loads, so import cycles can't leave anything undefined
|
||||||
|
export function client_engine() {
|
||||||
|
return {
|
||||||
|
Client,
|
||||||
|
Entity,
|
||||||
|
LocalPlayer,
|
||||||
|
Player,
|
||||||
|
RemoteEntity,
|
||||||
|
RemotePlayer,
|
||||||
|
ItemEntity,
|
||||||
|
ClientLevel,
|
||||||
|
GameRenderer,
|
||||||
|
LevelRenderer,
|
||||||
|
HandRenderer,
|
||||||
|
Camera,
|
||||||
|
InputManager,
|
||||||
|
ClientMenu,
|
||||||
|
GuiScreen,
|
||||||
|
GuiMenuScreen,
|
||||||
|
};
|
||||||
|
}
|
||||||
+62
-3
@@ -1,5 +1,16 @@
|
|||||||
import { move_body } from "$/common/physics.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
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
|
||||||
@@ -36,6 +47,13 @@ export abstract class Entity {
|
|||||||
step_grace_ticks = 0;
|
step_grace_ticks = 0;
|
||||||
// ticks since it was last on the ground
|
// ticks since it was last on the ground
|
||||||
#air_ticks = 0;
|
#air_ticks = 0;
|
||||||
|
// how far the limbs have swung and how hard they swing (0 to 1), like minecraft's WalkAnimationState
|
||||||
|
walk_position = 0;
|
||||||
|
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
|
||||||
@@ -55,6 +73,47 @@ export abstract class Entity {
|
|||||||
return this.colliding_y === 1;
|
return this.colliding_y === 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// in water, like the server's Entity.in_water
|
||||||
|
get in_water() {
|
||||||
|
return physics.in_water(this, (x, y, z) => this.level.is_fluid(x, y, z));
|
||||||
|
}
|
||||||
|
|
||||||
|
// its eyes are in water
|
||||||
|
get eyes_in_water() {
|
||||||
|
return physics.eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_fluid(x, y, z));
|
||||||
|
}
|
||||||
|
|
||||||
|
// after moving each tick. full speed is 5 blocks per second, a bit faster than walking
|
||||||
|
update_walk_animation() {
|
||||||
|
const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z);
|
||||||
|
this.prev_walk_speed = this.walk_speed;
|
||||||
|
this.walk_speed += (Math.min(moved * 4, 1) - this.walk_speed) * 0.4;
|
||||||
|
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) {
|
||||||
|
return {
|
||||||
|
position: this.walk_position - this.walk_speed * (1 - partial_tick),
|
||||||
|
speed: this.prev_walk_speed + (this.walk_speed - this.prev_walk_speed) * partial_tick,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// jumps there, without interpolating from where it was
|
// jumps there, without interpolating from where it was
|
||||||
set_position(x: number, y: number, z: number) {
|
set_position(x: number, y: number, z: number) {
|
||||||
this.x = this.prev_x = x;
|
this.x = this.prev_x = x;
|
||||||
@@ -98,10 +157,10 @@ export abstract class Entity {
|
|||||||
|
|
||||||
// falls and moves by its velocity for one tick (see move_body), then slows down from drag and friction
|
// falls and moves by its velocity for one tick (see move_body), then slows down from drag and friction
|
||||||
move() {
|
move() {
|
||||||
const is_solid = (x: number, y: number, z: number) => this.level.has_collision(x, y, z);
|
const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z);
|
||||||
const can_step = this.#air_ticks <= this.step_grace_ticks && this.vy <= 0;
|
const can_step = this.#air_ticks <= this.step_grace_ticks && this.vy <= 0;
|
||||||
const friction = this.horizontal_friction();
|
const friction = this.horizontal_friction();
|
||||||
const collisions = move_body(this, this.gravity, is_solid, this.step_height, can_step);
|
const collisions = physics.move_body(this, this.gravity, is_solid, this.step_height, can_step);
|
||||||
this.colliding_x = collisions.x;
|
this.colliding_x = collisions.x;
|
||||||
this.colliding_y = collisions.y;
|
this.colliding_y = collisions.y;
|
||||||
this.colliding_z = collisions.z;
|
this.colliding_z = collisions.z;
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { ItemStack } from "$/common/inventory.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import type { EntityInfo } from "$/common/protocol.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { ItemStack } from "@/common/inventory.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";
|
||||||
|
|
||||||
|
|||||||
+187
-15
@@ -1,5 +1,8 @@
|
|||||||
import { PLAYER_EYE_HEIGHT, TICK_DELTA } from "$/common/constants.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { back_off_from_edge } from "$/common/physics.ts";
|
// 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 { 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";
|
||||||
@@ -35,11 +38,44 @@ const SPRINT_FOV = (1 + SPRINT_SPEED) / 2;
|
|||||||
const FOV_EASE = 0.5;
|
const FOV_EASE = 0.5;
|
||||||
// like minecraft: sneaking is 30% of walking speed and lowers the eyes 0.35, which ease there by half each tick
|
// like minecraft: sneaking is 30% of walking speed and lowers the eyes 0.35, which ease there by half each tick
|
||||||
const SNEAK_SPEED = 0.3;
|
const SNEAK_SPEED = 0.3;
|
||||||
|
// using an item over time, like drawing a bow, slows walking to a fifth and stops sprinting, like minecraft
|
||||||
|
const USING_SPEED = 0.2;
|
||||||
const SNEAK_EYE_HEIGHT = PLAYER_EYE_HEIGHT - 0.35;
|
const SNEAK_EYE_HEIGHT = PLAYER_EYE_HEIGHT - 0.35;
|
||||||
const EYE_EASE = 0.5;
|
const EYE_EASE = 0.5;
|
||||||
// sneaking keeps it from walking off anything taller than this
|
// sneaking keeps it from walking off anything taller than this
|
||||||
const SNEAK_MAX_DROP = 0.6;
|
const SNEAK_MAX_DROP = 0.6;
|
||||||
|
|
||||||
|
// in water, like minecraft's LivingEntity.travel and the server's mobs: the keys add 0.02 blocks a tick, gravity is a
|
||||||
|
// sixteenth of the usual, and it slows to 0.8 of its speed each tick on every axis. walking settles at 2 blocks a
|
||||||
|
// second, and sinking at 0.45
|
||||||
|
const WATER_ACCELERATION = 0.02 / TICK_DELTA;
|
||||||
|
const WATER_GRAVITY = -32 / 16;
|
||||||
|
const WATER_DRAG = 0.8;
|
||||||
|
// holding jump in water pushes it up this much each tick, like minecraft's jumpInLiquid, rising 3.55 blocks a second
|
||||||
|
const SWIM_UP = 0.04 / TICK_DELTA;
|
||||||
|
// and sneaking pulls it down as much, like minecraft's goDownInWater, sinking 4.45 blocks a second. both cancel out
|
||||||
|
const SWIM_DOWN = 0.04 / TICK_DELTA;
|
||||||
|
// swimming into a wall with nothing solid or wet 0.6 above, like the edge of a pool, it hops up like minecraft. a bit
|
||||||
|
// harder than minecraft's 0.3, whose water is a little lower than a full block, so a ledge a block above the water can
|
||||||
|
// be climbed onto
|
||||||
|
const WATER_HOP_HEIGHT = 0.6;
|
||||||
|
const WATER_HOP = 0.36 / TICK_DELTA;
|
||||||
|
// swimming, sprinting with the eyes under water: no gravity and less drag sideways, so it goes 4 blocks a second
|
||||||
|
const SWIM_DRAG = 0.9;
|
||||||
|
// and it turns up or down toward where it's looking, this much of the way each tick, like minecraft's Player.travel
|
||||||
|
const SWIM_STEER = 0.06;
|
||||||
|
// flying, see /fly, like minecraft's creative flight: the keys add 0.05 blocks a tick and it keeps 0.91 of its speed,
|
||||||
|
// settling at 11 blocks a second, twice that sprinting. there's no gravity, jump and sneak push it up and down 0.15
|
||||||
|
// blocks a tick, and it keeps 0.6 of that each tick, rising and sinking 7.5 blocks a second
|
||||||
|
const FLY_ACCELERATION = 0.05 / TICK_DELTA;
|
||||||
|
const FLY_FRICTION = 0.91;
|
||||||
|
const FLY_SPRINT_SPEED = 2;
|
||||||
|
const FLY_VERTICAL = 0.15 / TICK_DELTA;
|
||||||
|
const FLY_VERTICAL_DRAG = 0.6;
|
||||||
|
// on land, the entity's own
|
||||||
|
const LAND_GRAVITY = -32;
|
||||||
|
const LAND_DRAG = 0.98;
|
||||||
|
|
||||||
// what the keys ask for this tick. x is right, z is back, as -1 to 1
|
// what the keys ask for this tick. x is right, z is back, as -1 to 1
|
||||||
interface MoveInput {
|
interface MoveInput {
|
||||||
x: number;
|
x: number;
|
||||||
@@ -56,33 +92,88 @@ const NO_INPUT: MoveInput = { x: 0, z: 0, jump: false, sprint: false, sneak: fal
|
|||||||
export class LocalPlayer extends Player {
|
export class LocalPlayer extends Player {
|
||||||
client: Client;
|
client: Client;
|
||||||
inventories = new ClientInventories();
|
inventories = new ClientInventories();
|
||||||
// what the server says, see server/game/vitals.ts. out of 20
|
// what the server says, see server/game/vitals.ts. food and air out of 20, health out of max_health
|
||||||
health = 20;
|
health = 20;
|
||||||
|
max_health = 20;
|
||||||
food = 20;
|
food = 20;
|
||||||
saturation = 5;
|
saturation = 5;
|
||||||
|
air = 20;
|
||||||
|
// the effects it has that show an icon, see the inventory screen. counted down here, the server only says when
|
||||||
|
// they change
|
||||||
|
effects: { id: string; amplifier: number; duration: number }[] = [];
|
||||||
|
// the attack speed attribute the server sent, and when they last attacked or switched slots, for the indicator
|
||||||
|
attack_speed = 4;
|
||||||
|
last_attack = -Infinity;
|
||||||
|
// how far it reaches blocks and entities, the attributes the server sent
|
||||||
|
block_interaction_range = 6;
|
||||||
|
entity_interaction_range = 3;
|
||||||
|
// using its held item over time, as the server says, see ctx's player.start_using
|
||||||
|
using_item = false;
|
||||||
|
|
||||||
// blocks per second, peaks about 1.25 blocks up with the entity's gravity and drag
|
// blocks per second, peaks about 1.25 blocks up with the entity's gravity and drag
|
||||||
jump_force = 9.23;
|
jump_force = 9.23;
|
||||||
|
|
||||||
|
// the last teleport from the server, sent back with every move so the server knows which moves came after it
|
||||||
|
teleport_id = 0;
|
||||||
#ticks_since_sent = 0;
|
#ticks_since_sent = 0;
|
||||||
// counts down every tick, letting go of jump clears it
|
// counts down every tick, letting go of jump clears it
|
||||||
#jump_delay = 0;
|
#jump_delay = 0;
|
||||||
|
// the sneaking pose, which flying doesn't have
|
||||||
sneaking = false;
|
sneaking = false;
|
||||||
|
// holding the sneak key, flying or not, which is what the server is told for placing and using things
|
||||||
|
holding_sneak = false;
|
||||||
// stays on after letting go of the key, see #update_sprinting
|
// stays on after letting go of the key, see #update_sprinting
|
||||||
sprinting = false;
|
sprinting = false;
|
||||||
|
// what the server says, see /fly
|
||||||
|
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;
|
||||||
|
// whether it was in water at the start of this tick, which decides how it moves for all of it
|
||||||
|
#in_water = false;
|
||||||
|
|
||||||
constructor(client: Client, id: string, name: string) {
|
constructor(client: Client, id: string, name: string) {
|
||||||
super(client.level, id, name);
|
super(client.level, id, name);
|
||||||
this.client = client;
|
this.client = client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// like the server's ServerPlayer.attack_strength, from real time so the indicator fills smoothly: 0 right after
|
||||||
|
// attacking, 1 after 20 / attack_speed ticks
|
||||||
|
attack_strength(): number {
|
||||||
|
const ticks = (performance.now() - this.last_attack) / 50;
|
||||||
|
return Math.min(1, Math.max(0, (ticks + 0.5) / (20 / this.attack_speed)));
|
||||||
|
}
|
||||||
|
|
||||||
tick() {
|
tick() {
|
||||||
this.#apply_input(this.client.screen ? NO_INPUT : this.#read_input());
|
for (const effect of this.effects) if (effect.duration > 0) effect.duration -= 1;
|
||||||
|
// flying ignores water
|
||||||
|
this.#in_water = !this.flying && this.in_water;
|
||||||
|
const was_swimming = this.swimming;
|
||||||
|
const was_holding_sneak = this.holding_sneak;
|
||||||
|
const input = this.client.screen ? NO_INPUT : this.#read_input();
|
||||||
|
this.#apply_input(input);
|
||||||
|
// after sprinting is, so letting go stands it up the same tick
|
||||||
|
this.#update_swimming();
|
||||||
|
// out of the water but still in the short box, under something low, it falls like on land
|
||||||
|
this.gravity = this.flying ? 0 : !this.#in_water ? LAND_GRAVITY : this.swimming ? 0 : WATER_GRAVITY;
|
||||||
|
this.drag = this.flying ? FLY_VERTICAL_DRAG : this.#in_water ? WATER_DRAG : LAND_DRAG;
|
||||||
|
if (this.swimming && this.#in_water) this.#steer(input);
|
||||||
|
if (!this.flying) {
|
||||||
|
physics.push_by_fluid(
|
||||||
|
this,
|
||||||
|
(x, y, z) => this.level.fluid_at(x, y, z),
|
||||||
|
(x, y, z) => this.level.collision_shape(x, y, z),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
this.#prev_eye_height = this.eye_height;
|
this.#prev_eye_height = this.eye_height;
|
||||||
const eye_height = this.sneaking ? SNEAK_EYE_HEIGHT : PLAYER_EYE_HEIGHT;
|
const eye_height = this.swimming
|
||||||
|
? PLAYER_SWIM_EYE_HEIGHT
|
||||||
|
: this.sneaking
|
||||||
|
? SNEAK_EYE_HEIGHT
|
||||||
|
: PLAYER_EYE_HEIGHT;
|
||||||
this.eye_height += (eye_height - this.eye_height) * EYE_EASE;
|
this.eye_height += (eye_height - this.eye_height) * EYE_EASE;
|
||||||
this.#prev_fov_scale = this.#fov_scale;
|
this.#prev_fov_scale = this.#fov_scale;
|
||||||
this.#fov_scale += ((this.sprinting ? SPRINT_FOV : 1) - this.#fov_scale) * FOV_EASE;
|
this.#fov_scale += ((this.sprinting ? SPRINT_FOV : 1) - this.#fov_scale) * FOV_EASE;
|
||||||
@@ -90,8 +181,8 @@ export class LocalPlayer extends Player {
|
|||||||
const was_on_ground = this.on_ground;
|
const was_on_ground = this.on_ground;
|
||||||
// not while jumping, so it can still jump off a ledge
|
// not while jumping, so it can still jump off a ledge
|
||||||
if (this.sneaking && this.on_ground && this.vy <= 0) {
|
if (this.sneaking && this.on_ground && this.vy <= 0) {
|
||||||
const is_solid = (x: number, y: number, z: number) => this.level.has_collision(x, y, z);
|
const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z);
|
||||||
const [dx, dz] = back_off_from_edge(
|
const [dx, dz] = physics.back_off_from_edge(
|
||||||
this,
|
this,
|
||||||
this.vx * TICK_DELTA,
|
this.vx * TICK_DELTA,
|
||||||
this.vz * TICK_DELTA,
|
this.vz * TICK_DELTA,
|
||||||
@@ -101,10 +192,55 @@ export class LocalPlayer extends Player {
|
|||||||
this.vx = dx / TICK_DELTA;
|
this.vx = dx / TICK_DELTA;
|
||||||
this.vz = dz / TICK_DELTA;
|
this.vz = dz / TICK_DELTA;
|
||||||
}
|
}
|
||||||
|
const from_y = this.y;
|
||||||
this.move();
|
this.move();
|
||||||
|
if (this.#in_water) this.#hop_out_of_water(from_y);
|
||||||
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.#send_position(this.on_ground && !was_on_ground);
|
this.update_swim_animation();
|
||||||
|
// creeping and flying are quiet
|
||||||
|
if (this.on_ground && !this.sneaking) this.play_steps();
|
||||||
|
this.#send_position(
|
||||||
|
(this.on_ground && !was_on_ground) || this.swimming !== was_swimming ||
|
||||||
|
this.holding_sneak !== was_holding_sneak,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// like voxelibre: sprinting with the eyes under water starts it, and it keeps going while it sprints in water, along
|
||||||
|
// the surface too. it only stands back up where there's room, until then it stays in the short box
|
||||||
|
#update_swimming() {
|
||||||
|
if (!this.swimming) {
|
||||||
|
if (this.sprinting && this.eyes_in_water && !this.flying) this.set_swimming(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.sprinting && this.#in_water) return;
|
||||||
|
const standing = {
|
||||||
|
x: this.x,
|
||||||
|
y: this.y,
|
||||||
|
z: this.z,
|
||||||
|
width: this.width,
|
||||||
|
height: PLAYER_HEIGHT,
|
||||||
|
vx: 0,
|
||||||
|
vy: 0,
|
||||||
|
vz: 0,
|
||||||
|
};
|
||||||
|
if (physics.box_is_free(standing, 0, 0, 0, (x, y, z) => this.level.collision_shape(x, y, z))) {
|
||||||
|
this.set_swimming(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// turns up or down toward where it's looking. not up once its head is out, so it swims along the surface instead
|
||||||
|
// of leaping out of the water, unless it's holding jump
|
||||||
|
#steer(input: MoveInput) {
|
||||||
|
const look_y = Math.sin(this.pitch);
|
||||||
|
const head_in_water = this.level.is_fluid(
|
||||||
|
Math.floor(this.x),
|
||||||
|
Math.floor(this.y + this.height),
|
||||||
|
Math.floor(this.z),
|
||||||
|
);
|
||||||
|
if (look_y <= 0 || input.jump || head_in_water) {
|
||||||
|
this.vy += (look_y / TICK_DELTA - this.vy) * SWIM_STEER;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// turns with the mouse every frame, not every tick, like minecraft's MouseHandler.turnPlayer
|
// turns with the mouse every frame, not every tick, like minecraft's MouseHandler.turnPlayer
|
||||||
@@ -117,9 +253,21 @@ export class LocalPlayer extends Player {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override horizontal_friction() {
|
override horizontal_friction() {
|
||||||
|
if (this.flying) return FLY_FRICTION;
|
||||||
|
if (this.#in_water) return this.swimming ? SWIM_DRAG : WATER_DRAG;
|
||||||
return this.on_ground ? GROUND_FRICTION : AIR_FRICTION;
|
return this.on_ground ? GROUND_FRICTION : AIR_FRICTION;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// like minecraft's LivingEntity.travel in water: after running into a wall, if the box one move on and 0.6 higher
|
||||||
|
// than where it started touches nothing solid or wet, it hops up, out onto the ledge
|
||||||
|
#hop_out_of_water(from_y: number) {
|
||||||
|
if (!this.colliding_x && !this.colliding_z) return;
|
||||||
|
const blocked = (x: number, y: number, z: number) =>
|
||||||
|
this.level.is_fluid(x, y, z) || this.level.collision_shape(x, y, z);
|
||||||
|
const dy = from_y - this.y + this.vy * TICK_DELTA + WATER_HOP_HEIGHT;
|
||||||
|
if (physics.box_is_free(this, this.vx * TICK_DELTA, dy, this.vz * TICK_DELTA, blocked)) this.vy = WATER_HOP;
|
||||||
|
}
|
||||||
|
|
||||||
// how much wider the view is than the fov option, between the last tick and this one
|
// how much wider the view is than the fov option, between the last tick and this one
|
||||||
override render_fov_scale(partial_tick: number) {
|
override render_fov_scale(partial_tick: number) {
|
||||||
return this.#prev_fov_scale + (this.#fov_scale - this.#prev_fov_scale) * partial_tick;
|
return this.#prev_fov_scale + (this.#fov_scale - this.#prev_fov_scale) * partial_tick;
|
||||||
@@ -147,23 +295,41 @@ export class LocalPlayer extends Player {
|
|||||||
let { x: input_x, z: input_z } = input;
|
let { x: input_x, z: input_z } = input;
|
||||||
const size = Math.hypot(input_x, input_z);
|
const size = Math.hypot(input_x, input_z);
|
||||||
if (size > 0) {
|
if (size > 0) {
|
||||||
input_x /= size;
|
const scale = (this.using_item ? USING_SPEED : 1) / size;
|
||||||
input_z /= size;
|
input_x *= scale;
|
||||||
|
input_z *= scale;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sneaking = input.sneak;
|
// sneaking while flying goes down instead
|
||||||
|
this.sneaking = input.sneak && !this.flying;
|
||||||
|
this.holding_sneak = input.sneak;
|
||||||
const sin = Math.sin(this.yaw);
|
const sin = Math.sin(this.yaw);
|
||||||
const cos = Math.cos(this.yaw);
|
const cos = Math.cos(this.yaw);
|
||||||
this.#update_sprinting(input, sin, cos);
|
this.#update_sprinting(input, sin, cos);
|
||||||
const acceleration = (this.on_ground ? GROUND_ACCELERATION : AIR_ACCELERATION) *
|
if (this.flying) {
|
||||||
(input.sneak ? SNEAK_SPEED : this.sprinting ? SPRINT_SPEED : 1);
|
const acceleration = FLY_ACCELERATION * (this.sprinting ? FLY_SPRINT_SPEED : 1);
|
||||||
|
this.vx += (sin * input_z + cos * input_x) * acceleration;
|
||||||
|
this.vz += (cos * input_z - sin * input_x) * acceleration;
|
||||||
|
this.vy += (Number(input.jump) - Number(input.sneak)) * FLY_VERTICAL;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// sprinting is no faster in water, swimming is
|
||||||
|
const acceleration = this.#in_water
|
||||||
|
? WATER_ACCELERATION * (input.sneak ? SNEAK_SPEED : 1)
|
||||||
|
: (this.on_ground ? GROUND_ACCELERATION : AIR_ACCELERATION) *
|
||||||
|
(input.sneak ? SNEAK_SPEED : this.sprinting ? SPRINT_SPEED : 1);
|
||||||
|
|
||||||
this.vx += (sin * input_z + cos * input_x) * acceleration;
|
this.vx += (sin * input_z + cos * input_x) * acceleration;
|
||||||
this.vz += (cos * input_z - sin * input_x) * acceleration;
|
this.vz += (cos * input_z - sin * input_x) * acceleration;
|
||||||
|
|
||||||
|
if (this.#in_water && input.sneak) this.vy -= SWIM_DOWN;
|
||||||
|
|
||||||
this.#jump_delay = Math.max(0, this.#jump_delay - 1);
|
this.#jump_delay = Math.max(0, this.#jump_delay - 1);
|
||||||
if (!input.jump) {
|
if (!input.jump) {
|
||||||
this.#jump_delay = 0;
|
this.#jump_delay = 0;
|
||||||
|
} else if (this.#in_water) {
|
||||||
|
// like minecraft, jumping in water swims up instead, even standing on the bottom
|
||||||
|
this.vy += SWIM_UP;
|
||||||
} else if (this.on_ground && this.#jump_delay === 0) {
|
} else if (this.on_ground && this.#jump_delay === 0) {
|
||||||
this.vy += this.jump_force;
|
this.vy += this.jump_force;
|
||||||
this.#jump_delay = JUMP_DELAY_TICKS;
|
this.#jump_delay = JUMP_DELAY_TICKS;
|
||||||
@@ -178,12 +344,15 @@ export class LocalPlayer extends Player {
|
|||||||
// like minecraft's LocalPlayer.aiStep: the key starts sprinting while moving forward, and it keeps sprinting
|
// like minecraft's LocalPlayer.aiStep: the key starts sprinting while moving forward, and it keeps sprinting
|
||||||
// until it stops moving forward, sneaks, gets hungry or runs into a wall, even after letting go of the key
|
// until it stops moving forward, sneaks, gets hungry or runs into a wall, even after letting go of the key
|
||||||
#update_sprinting(input: MoveInput, sin: number, cos: number) {
|
#update_sprinting(input: MoveInput, sin: number, cos: number) {
|
||||||
const can_sprint = input.z < 0 && !input.sneak && this.food > SPRINT_MIN_FOOD;
|
// like minecraft, flying sprints even hungry, and sneaking to go down doesn't stop it
|
||||||
|
const can_sprint = input.z < 0 && !this.using_item &&
|
||||||
|
(this.flying || (!input.sneak && this.food > SPRINT_MIN_FOOD));
|
||||||
// how far it's looking into what it hit in the last move, the way it's facing is -sin, -cos
|
// how far it's looking into what it hit in the last move, the way it's facing is -sin, -cos
|
||||||
const into_wall = sin * this.colliding_x + cos * this.colliding_z;
|
const into_wall = sin * this.colliding_x + cos * this.colliding_z;
|
||||||
if (!can_sprint || into_wall > SPRINT_WALL_ANGLE) {
|
if (!can_sprint || into_wall > SPRINT_WALL_ANGLE) {
|
||||||
this.sprinting = false;
|
this.sprinting = false;
|
||||||
} else if (input.sprint) {
|
} else if (input.sprint && (!this.#in_water || this.eyes_in_water)) {
|
||||||
|
// in water only with the eyes under, to swim, not to sprint along the bottom
|
||||||
this.sprinting = true;
|
this.sprinting = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,6 +376,9 @@ export class LocalPlayer extends Player {
|
|||||||
z: this.z,
|
z: this.z,
|
||||||
yaw: this.yaw,
|
yaw: this.yaw,
|
||||||
pitch: this.pitch,
|
pitch: this.pitch,
|
||||||
|
teleport: this.teleport_id,
|
||||||
|
...(this.swimming && { swimming: true }),
|
||||||
|
...(this.holding_sneak && { sneaking: true }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+54
-31
@@ -1,9 +1,20 @@
|
|||||||
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT, PLAYER_WIDTH } from "@/common/constants.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";
|
||||||
import { Entity } from "./entity.ts";
|
import { Entity } from "./entity.ts";
|
||||||
|
|
||||||
|
// how much of the way it tips over or stands up each tick, so it takes 10 ticks
|
||||||
|
const SWIM_EASE = 0.1;
|
||||||
|
// how much of the way the body turns toward which way it's going each tick
|
||||||
|
const SWIM_PITCH_EASE = 0.3;
|
||||||
|
// blocks a tick. slower than this the body lies the way they look instead, it's how they moved that's too jittery
|
||||||
|
const SWIM_MOVING = 0.05;
|
||||||
|
|
||||||
export abstract class Player extends Entity {
|
export abstract class Player extends Entity {
|
||||||
name: string;
|
name: string;
|
||||||
// like minecraft's players: slabs yes, full blocks need a jump
|
// like minecraft's players: slabs yes, full blocks need a jump
|
||||||
@@ -15,44 +26,56 @@ export abstract class Player extends Entity {
|
|||||||
skin: Texture | undefined;
|
skin: Texture | undefined;
|
||||||
// 3 pixel wide arms, for skins made for them
|
// 3 pixel wide arms, for skins made for them
|
||||||
slim = false;
|
slim = false;
|
||||||
#skin_version = 0;
|
// what they wear that shows, items with a worn model, see the server's player_worn
|
||||||
|
worn: ItemStack[] = [];
|
||||||
// how far the limbs have swung and how hard they swing (0 to 1), like minecraft's WalkAnimationState
|
// lying flat in the short box, see set_swimming
|
||||||
walk_position = 0;
|
swimming = false;
|
||||||
walk_speed = 0;
|
// how far over they've tipped, 0 standing to 1 lying flat, see update_swim_animation
|
||||||
prev_walk_speed = 0;
|
swim_amount = 0;
|
||||||
|
prev_swim_amount = 0;
|
||||||
|
// which way the body lies while swimming, radians up from flat: the way they're going, or looking when still
|
||||||
|
swim_pitch = 0;
|
||||||
|
prev_swim_pitch = 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);
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
// a base64 png from the server, or undefined for the default. the old skin stays until the new one is decoded
|
// swimming lies them flat in the short box, and not swimming stands them back up. the local player checks there's
|
||||||
async set_skin(skin: string | undefined, slim = false) {
|
// room first, remote players' clients already did
|
||||||
const version = ++this.#skin_version;
|
set_swimming(swimming: boolean) {
|
||||||
const texture = skin ? await decode_skin(skin) : undefined;
|
this.swimming = swimming;
|
||||||
if (version !== this.#skin_version) {
|
this.height = swimming ? PLAYER_SWIM_HEIGHT : PLAYER_HEIGHT;
|
||||||
// a newer skin came while this one was decoding
|
}
|
||||||
texture?.tex.destroy();
|
|
||||||
return;
|
// after moving each tick, for tipping over and standing up smoothly, local and remote players alike. the pitch comes
|
||||||
}
|
// from how they moved, so remote players get it without anything more from the server
|
||||||
|
update_swim_animation() {
|
||||||
|
this.prev_swim_amount = this.swim_amount;
|
||||||
|
this.prev_swim_pitch = this.swim_pitch;
|
||||||
|
const amount = this.swimming ? 1 : 0;
|
||||||
|
this.swim_amount += Math.max(-SWIM_EASE, Math.min(SWIM_EASE, amount - this.swim_amount));
|
||||||
|
const [dx, dy, dz] = [this.x - this.prev_x, this.y - this.prev_y, this.z - this.prev_z];
|
||||||
|
const moving = Math.atan2(dy, Math.hypot(dx, dz));
|
||||||
|
const weight = Math.min(Math.hypot(dx, dy, dz) / SWIM_MOVING, 1);
|
||||||
|
const pitch = this.pitch + (moving - this.pitch) * weight;
|
||||||
|
this.swim_pitch += (pitch - this.swim_pitch) * SWIM_PITCH_EASE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a frame partial_tick of the way to the next tick
|
||||||
|
render_swim(partial_tick: number) {
|
||||||
|
return {
|
||||||
|
amount: this.prev_swim_amount + (this.swim_amount - this.prev_swim_amount) * partial_tick,
|
||||||
|
pitch: this.prev_swim_pitch + (this.swim_pitch - this.prev_swim_pitch) * partial_tick,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// a base64 png from the server, or undefined for the default
|
||||||
|
set_skin(skin: string | undefined, slim = false) {
|
||||||
|
const texture = skin ? decode_skin(skin) : undefined;
|
||||||
this.skin?.tex.destroy();
|
this.skin?.tex.destroy();
|
||||||
this.skin = texture;
|
this.skin = texture;
|
||||||
this.slim = slim;
|
this.slim = slim;
|
||||||
}
|
}
|
||||||
|
|
||||||
// after moving each tick. full speed is 5 blocks per second, a bit faster than walking
|
|
||||||
update_walk_animation() {
|
|
||||||
const moved = Math.hypot(this.x - this.prev_x, this.z - this.prev_z);
|
|
||||||
this.prev_walk_speed = this.walk_speed;
|
|
||||||
this.walk_speed += (Math.min(moved * 4, 1) - this.walk_speed) * 0.4;
|
|
||||||
this.walk_position += this.walk_speed;
|
|
||||||
}
|
|
||||||
|
|
||||||
walk_animation(partial_tick: number) {
|
|
||||||
return {
|
|
||||||
position: this.walk_position - this.walk_speed * (1 - partial_tick),
|
|
||||||
speed: this.prev_walk_speed + (this.walk_speed - this.prev_walk_speed) * partial_tick,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,36 @@
|
|||||||
import type { EntityData, EntityInfo } from "$/common/protocol.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
|
||||||
|
import type { EntityData, EntityEvent, EntityInfo } from "@/common/protocol.ts";
|
||||||
|
import { type EntityJson, sound_of } from "@/common/mod_data.ts";
|
||||||
|
import { EverythingRegistry } from "@/common/everything_registry.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;
|
||||||
// how long it flashes red after being hurt, and falls over after dying, like minecraft
|
// how long it flashes red after being hurt, and falls over after dying, like minecraft
|
||||||
const HURT_TICKS = 10;
|
const HURT_TICKS = 10;
|
||||||
const DEATH_TICKS = 20;
|
const DEATH_TICKS = 20;
|
||||||
|
// how long its attack swing takes, like minecraft's mobs
|
||||||
|
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 "bworld: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;
|
||||||
@@ -24,9 +38,15 @@ export class RemoteEntity extends Entity {
|
|||||||
dead = false;
|
dead = false;
|
||||||
// what's riding it, by id
|
// what's riding it, by id
|
||||||
passengers: string[] = [];
|
passengers: string[] = [];
|
||||||
|
// ticks into its attack swing, undefined when it isn't swinging
|
||||||
|
swing_ticks: number | undefined;
|
||||||
|
|
||||||
#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
|
||||||
@@ -34,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) {
|
||||||
@@ -46,15 +74,22 @@ export class RemoteEntity extends Entity {
|
|||||||
this.#lerp_ticks = LERP_TICKS;
|
this.#lerp_ticks = LERP_TICKS;
|
||||||
}
|
}
|
||||||
|
|
||||||
on_event(event: "hurt" | "death") {
|
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") {
|
||||||
|
// 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;
|
||||||
} 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);
|
||||||
|
|
||||||
@@ -69,12 +104,27 @@ export class RemoteEntity extends Entity {
|
|||||||
this.head_yaw += wrap_angle(target.head_yaw - this.head_yaw) * t;
|
this.head_yaw += wrap_angle(target.head_yaw - this.head_yaw) * t;
|
||||||
this.#lerp_ticks -= 1;
|
this.#lerp_ticks -= 1;
|
||||||
}
|
}
|
||||||
|
this.update_walk_animation();
|
||||||
|
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
|
||||||
|
attack_animation(partial_tick: number) {
|
||||||
|
return this.swing_ticks === undefined ? 0 : Math.min(1, (this.swing_ticks + partial_tick) / SWING_TICKS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function wrap_angle(angle: number) {
|
function random_ambient_ticks() {
|
||||||
angle %= Math.PI * 2;
|
const [low, high] = AMBIENT_TICKS;
|
||||||
if (angle >= Math.PI) angle -= Math.PI * 2;
|
return low + Math.floor(Math.random() * (high - low));
|
||||||
if (angle < -Math.PI) angle += Math.PI * 2;
|
|
||||||
return angle;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import type { PlayerInfo } from "$/common/protocol.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { TICK_DELTA } from "$/common/constants.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import type { EntityEvent, PlayerInfo } from "@/common/protocol.ts";
|
||||||
|
import { TICK_DELTA } from "@/common/constants.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";
|
||||||
|
|
||||||
const SMOOTHING = 12;
|
const SMOOTHING = 12;
|
||||||
|
// how long they flash red after being hurt, like minecraft
|
||||||
|
const HURT_TICKS = 10;
|
||||||
|
|
||||||
// another player on the server, it moves where the server says instead of simulating anything
|
// another player on the server, it moves where the server says instead of simulating anything
|
||||||
export class RemotePlayer extends Player {
|
export class RemotePlayer extends Player {
|
||||||
@@ -11,6 +17,8 @@ export class RemotePlayer extends Player {
|
|||||||
target_x: number;
|
target_x: number;
|
||||||
target_y: number;
|
target_y: number;
|
||||||
target_z: number;
|
target_z: number;
|
||||||
|
// counting down after a hurt event
|
||||||
|
hurt_time = 0;
|
||||||
|
|
||||||
constructor(level: ClientLevel, info: PlayerInfo) {
|
constructor(level: ClientLevel, info: PlayerInfo) {
|
||||||
super(level, info.id, info.name);
|
super(level, info.id, info.name);
|
||||||
@@ -23,6 +31,8 @@ export class RemotePlayer extends Player {
|
|||||||
if (info.skin) {
|
if (info.skin) {
|
||||||
this.set_skin(info.skin, info.slim);
|
this.set_skin(info.skin, info.slim);
|
||||||
}
|
}
|
||||||
|
this.worn = (info.worn ?? []).map(ItemStack.from_data);
|
||||||
|
this.set_swimming(info.swimming === true);
|
||||||
}
|
}
|
||||||
|
|
||||||
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number) {
|
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number) {
|
||||||
@@ -33,11 +43,21 @@ export class RemotePlayer extends Player {
|
|||||||
this.pitch = pitch;
|
this.pitch = pitch;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// players respawn straight away, so dying doesn't show
|
||||||
|
on_event(event: EntityEvent) {
|
||||||
|
if (event === "hurt") {
|
||||||
|
this.hurt_time = HURT_TICKS;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
tick() {
|
tick() {
|
||||||
|
if (this.hurt_time > 0) this.hurt_time -= 1;
|
||||||
const t = Math.min(1, TICK_DELTA * SMOOTHING);
|
const t = Math.min(1, TICK_DELTA * SMOOTHING);
|
||||||
this.x += (this.target_x - this.x) * t;
|
this.x += (this.target_x - this.x) * t;
|
||||||
this.y += (this.target_y - this.y) * t;
|
this.y += (this.target_y - this.y) * t;
|
||||||
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.play_steps();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-13
@@ -1,3 +1,8 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// 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)
|
||||||
@@ -6,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() {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// and makes it again for each server's
|
||||||
|
import { FluidRules } from "@/common/fluids.ts";
|
||||||
|
|
||||||
|
export let fluid_rules = new FluidRules(() => undefined);
|
||||||
|
|
||||||
|
export function set_fluid_rules(rules: FluidRules) {
|
||||||
|
fluid_rules = rules;
|
||||||
|
}
|
||||||
+149
-27
@@ -1,13 +1,28 @@
|
|||||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { AIR, FACE_OFFSETS, TICK_DELTA } from "$/common/constants.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "@/common/everything_registry.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, type ContainerKey } from "$/common/protocol.ts";
|
import { AIR_ID } from "@/common/protocol.ts";
|
||||||
import { box_overlaps_block, can_place, placement_target } from "$/common/utils.ts";
|
import { box_overlaps_block, can_place, fluid_block, placement_target, waterlog_placement } from "@/common/utils.ts";
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
import { block_rules, predict_neighbors } from "./mods.ts";
|
||||||
|
import { collision_shape_at } from "@/common/block_shapes.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 { 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
|
||||||
@@ -18,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;
|
||||||
@@ -30,23 +50,45 @@ 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;
|
||||||
|
|
||||||
|
// looking at another block starts it over
|
||||||
|
const pos = this.destroy_pos;
|
||||||
|
if (!pos || pos.x !== hit.x || pos.y !== hit.y || pos.z !== hit.z) {
|
||||||
|
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.client.level.break_block(hit.x, hit.y, hit.z);
|
this.#predict((seq) => {
|
||||||
this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z });
|
// 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);
|
||||||
|
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.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;
|
||||||
@@ -54,71 +96,151 @@ export class MultiPlayerGameMode {
|
|||||||
|
|
||||||
// right click on a block
|
// right click on a block
|
||||||
use_item_on(hit: BlockHitResult) {
|
use_item_on(hit: BlockHitResult) {
|
||||||
const level = this.client.level;
|
|
||||||
// the server checks that the block isn't going inside the player with where it is now, like this does
|
// the server checks that the block isn't going inside the player with where it is now, like this does
|
||||||
this.client.player.send_position_now();
|
this.client.player.send_position_now();
|
||||||
this.client.connection.send({ type: "use_block", x: hit.x, y: hit.y, z: hit.z, face: hit.face });
|
this.#predict((seq) => {
|
||||||
|
const { x, y, z, face } = hit;
|
||||||
|
this.client.connection.send({ type: "use_block", x, y, z, face, hit: hit.hit, seq });
|
||||||
|
this.#guess_use(hit);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// what using a block will do, shown right away
|
||||||
|
#guess_use(hit: BlockHitResult) {
|
||||||
|
const level = this.client.level;
|
||||||
|
|
||||||
|
// the shared rules' on_interact, like a trapdoor opening, shows right away. the server runs them too and corrects
|
||||||
|
// this if it disagrees. when they do something nothing is placed, like on the server
|
||||||
|
// an item aimed at fluids, like a bucket, uses the fluid in a waterlogged block instead, like on the server
|
||||||
|
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
|
||||||
|
const held = this.held_item();
|
||||||
|
const value = level.get_block_value(hit.x, hit.y, hit.z);
|
||||||
|
const used = (held?.targets_fluids && fluid_block(value, block_info)) || block_info;
|
||||||
|
// sneaking with an item skips the block, like on the server
|
||||||
|
const sneaking = this.client.player.holding_sneak;
|
||||||
|
const skips_block = sneaking && held !== undefined;
|
||||||
|
const interaction = { face: hit.face, hit: hit.hit, sneaking };
|
||||||
|
if (!skips_block && block_rules.interact(used, hit.x, hit.y, hit.z, interaction, this.client.player.yaw)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// guess that it places the held block, unless the block does something when used. the same rules as the server:
|
// guess that it places the held block, unless the block does something when used. the same rules as the server:
|
||||||
// into the clicked block when it's replaceable, and only where place_in and place_on allow
|
// into the clicked block when it's replaceable, and only where place_in and place_on allow
|
||||||
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
|
|
||||||
const target = placement_target(hit.x, hit.y, hit.z, FACE_OFFSETS[hit.face], block_info);
|
const target = placement_target(hit.x, hit.y, hit.z, FACE_OFFSETS[hit.face], block_info);
|
||||||
const current = level.get_block(target.x, target.y, target.z);
|
const current = level.get_block(target.x, target.y, target.z);
|
||||||
const below = level.get_block(target.x, target.y - 1, target.z);
|
const below = level.get_block(target.x, target.y - 1, target.z);
|
||||||
const below_id = EverythingRegistry.get_by_id<BlockRegistry>("blocks", below)?.id ?? AIR_ID;
|
const below_id = EverythingRegistry.get_by_id<BlockRegistry>("blocks", below)?.id ?? AIR_ID;
|
||||||
const held = this.#held_item();
|
|
||||||
// items with components might do something else on the server, like on_use
|
// items with components might do something else on the server, like on_use
|
||||||
const place_id = held?.components ? undefined : held?.block_id;
|
const place_id = held?.components ? undefined : held?.block_id;
|
||||||
const place_block = place_id !== undefined
|
const place_block = place_id !== undefined
|
||||||
? EverythingRegistry.get<BlockRegistry>("blocks", place_id)
|
? EverythingRegistry.get<BlockRegistry>("blocks", place_id)
|
||||||
: undefined;
|
: undefined;
|
||||||
const placeable = place_id !== undefined && can_place(
|
// with the states the server will give it, see BlockRules.placement_value, and holding the fluid it goes into.
|
||||||
|
// undefined when its rules say it can't go there
|
||||||
|
const ruled_value = place_block &&
|
||||||
|
block_rules.placement_value(place_block, this.client.player.yaw, this.client.player.pitch, {
|
||||||
|
...target,
|
||||||
|
face: hit.face,
|
||||||
|
hit: hit.hit,
|
||||||
|
sneaking,
|
||||||
|
item: this.#held_slot().type_id!,
|
||||||
|
});
|
||||||
|
const place_value = ruled_value !== undefined
|
||||||
|
? waterlog_placement(
|
||||||
|
ruled_value,
|
||||||
|
place_block!,
|
||||||
|
level.get_block_value(target.x, target.y, target.z),
|
||||||
|
EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
const placeable = place_value !== undefined && place_id !== undefined && can_place(
|
||||||
place_block,
|
place_block,
|
||||||
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
|
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
|
||||||
|
level.get_block_value(target.x, target.y, target.z),
|
||||||
below_id,
|
below_id,
|
||||||
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z));
|
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, place_value!));
|
||||||
if (!block_info.interactive && place_id && placeable) {
|
if ((!block_info.interactive || skips_block) && place_id && placeable) {
|
||||||
level.add_block({ ...target, id: place_id });
|
// the server sends it to everyone else, see GameServer.#use_block
|
||||||
const slot = this.#held_slot();
|
sounds.play_of(place_block!.sounds, "place", { at: middle(target) });
|
||||||
slot.amount = slot.amount! - 1;
|
level.add_block({ ...target, id: place_id }, place_value! >>> 16);
|
||||||
|
predict_neighbors(target.x, target.y, target.z);
|
||||||
|
if (!this.client.player.creative) {
|
||||||
|
const slot = this.#held_slot();
|
||||||
|
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
|
||||||
drop_item(container: Container, key: ContainerKey, index: number, all: boolean) {
|
// q on a menu's slot, whose item is in container at index on this client
|
||||||
|
drop_item(container: Container, index: number, menu: number, slot: number, all: boolean) {
|
||||||
const item = container.get_item(index);
|
const item = container.get_item(index);
|
||||||
if (!item) {
|
if (!item) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.client.connection.send({ type: "drop_item", container: key, index, all });
|
this.client.connection.send({ type: "drop_item", menu, slot, all });
|
||||||
item.amount = all ? 0 : item.amount - 1;
|
item.amount = all ? 0 : item.amount - 1;
|
||||||
container.set_item(index, item.amount > 0 ? item : undefined);
|
container.set_item(index, item.amount > 0 ? item : undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// left click on an entity or another player, the server decides whether it's hurt
|
||||||
|
attack(entity: Entity) {
|
||||||
|
this.client.player.send_position_now();
|
||||||
|
this.client.connection.send({ type: "attack_entity", id: entity.id });
|
||||||
|
this.client.player.last_attack = performance.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
// left click on nothing: a swing at the air, which uses up the attack cooldown like an attack
|
||||||
|
swing() {
|
||||||
|
this.client.connection.send({ type: "swing" });
|
||||||
|
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) {
|
#occupied(x: number, y: number, z: number, block: BlockRegistry, value: number) {
|
||||||
|
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 ||
|
||||||
if (blocks && box_overlaps_block(entity, x, y, z)) return true;
|
(json !== undefined && json.behavior !== "scripted" && json.behavior !== "object");
|
||||||
|
if (blocks && box_overlaps_block(entity, x, y, z, shape)) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runs guess with the blocks it changes kept track of, like minecraft's startPrediction. what the server says about
|
||||||
|
// them waits until it answers the message guess sends with seq, see client/level/block_predictions.ts
|
||||||
|
#predict(guess: (seq: number) => void) {
|
||||||
|
const predictions = this.client.level.predictions;
|
||||||
|
const seq = predictions.start();
|
||||||
|
try {
|
||||||
|
guess(seq);
|
||||||
|
} finally {
|
||||||
|
predictions.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#held_slot() {
|
#held_slot() {
|
||||||
const inventories = this.client.player.inventories;
|
const inventories = this.client.player.inventories;
|
||||||
return inventories.inventory.get_slot(inventories.hotbar_selected);
|
return inventories.inventory.get_slot(inventories.hotbar_selected);
|
||||||
}
|
}
|
||||||
|
|
||||||
#held_item() {
|
held_item() {
|
||||||
return EverythingRegistry.get<ItemRegistry>("items", this.#held_slot().type_id ?? "");
|
return EverythingRegistry.get<ItemRegistry>("items", this.#held_slot().type_id ?? "");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { canvas, draw_rect, draw_text } from "$/client/renderer/mod.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// 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
|
||||||
@@ -52,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("");
|
||||||
@@ -69,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 {
|
||||||
@@ -88,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, """);
|
||||||
}
|
}
|
||||||
|
|||||||
+146
-4
@@ -1,12 +1,39 @@
|
|||||||
import type { Client } from "$/client/client.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { DebugUI } from "$/client/debug_ui.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { format_clock } from "$/common/time.ts";
|
|
||||||
|
|
||||||
// f3: every entity's fields, editable
|
import type { Client } from "@/client/client.ts";
|
||||||
|
import { DebugUI } from "@/client/debug_ui.ts";
|
||||||
|
import { format_clock } from "@/common/time.ts";
|
||||||
|
import { profiler, type SectionStats } from "@/client/profiler.ts";
|
||||||
|
import { canvas, gpu_timer, render_debug, render_stats } from "@/client/renderer/mod.ts";
|
||||||
|
import { RENDER_LAYERS } from "@/common/everything_registry.ts";
|
||||||
|
import { atlas_png } from "@/client/atlas.ts";
|
||||||
|
import { RenderBenchmark } from "@/client/benchmark/benchmark.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
|
||||||
|
// measuring
|
||||||
|
const CHUNK_STATS_MS = 1000;
|
||||||
|
|
||||||
|
// f3: every entity's fields, editable, and what frames cost
|
||||||
export class DebugOverlay {
|
export class DebugOverlay {
|
||||||
|
#chunk_stats = { meshed: 0, bytes: 0 };
|
||||||
|
#chunk_stats_time = -Infinity;
|
||||||
|
// the last benchmark's, see client/benchmark/
|
||||||
|
#benchmark_report: string | undefined;
|
||||||
|
#benchmark_status = "";
|
||||||
|
|
||||||
render(client: Client) {
|
render(client: Client) {
|
||||||
|
this.#render_performance(client);
|
||||||
|
|
||||||
DebugUI.begin("Entities", 10, 10, 300);
|
DebugUI.begin("Entities", 10, 10, 300);
|
||||||
DebugUI.text(`${format_clock(client.level.time)} (tick ${client.level.time})`);
|
DebugUI.text(`${format_clock(client.level.time)} (tick ${client.level.time})`);
|
||||||
|
if (DebugUI.button("Copy texture atlas")) {
|
||||||
|
// the promise goes in as is, so the copy still counts as coming from the click while the png encodes
|
||||||
|
const png = atlas_png();
|
||||||
|
if (png) navigator.clipboard?.write([new ClipboardItem({ "image/png": png })]).catch(() => {});
|
||||||
|
}
|
||||||
DebugUI.separator();
|
DebugUI.separator();
|
||||||
|
|
||||||
for (const entity of client.level.entities.values()) {
|
for (const entity of client.level.entities.values()) {
|
||||||
@@ -24,6 +51,121 @@ export class DebugOverlay {
|
|||||||
DebugUI.end();
|
DebugUI.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// where a frame's time goes. if the time between frames is much more than the javascript takes, the frame is
|
||||||
|
// waiting on the gpu (or vsync), and the gpu times say what it's doing
|
||||||
|
#render_performance(client: Client) {
|
||||||
|
const ms = (value: number) => value.toFixed(2);
|
||||||
|
const stats = (name: string, { avg, max }: SectionStats) => `${name}: ${ms(avg)} ms (max ${ms(max)})`;
|
||||||
|
const { interval, frame } = profiler;
|
||||||
|
|
||||||
|
DebugUI.begin("Performance", 320, 10, 340, 600);
|
||||||
|
const copy = DebugUI.button("Copy");
|
||||||
|
if (DebugUI.button("Run the render benchmark")) this.#start_benchmark(client);
|
||||||
|
if (this.#benchmark_report && DebugUI.button("Copy the benchmark's results")) this.#copy_benchmark();
|
||||||
|
if (this.#benchmark_status) DebugUI.text(this.#benchmark_status);
|
||||||
|
// what's shown, for the copy button
|
||||||
|
const lines: string[] = [];
|
||||||
|
const text = (line: string) => {
|
||||||
|
lines.push(line);
|
||||||
|
DebugUI.text(line);
|
||||||
|
};
|
||||||
|
const separator = () => {
|
||||||
|
lines.push("");
|
||||||
|
DebugUI.separator();
|
||||||
|
};
|
||||||
|
const msaa = render_debug.msaa ? "4x" : "off";
|
||||||
|
text(`${interval.fps.toFixed(0)} fps, ${canvas.width}x${canvas.height}, msaa ${msaa}`);
|
||||||
|
text(stats("between frames", interval));
|
||||||
|
text(stats("javascript", frame));
|
||||||
|
text(`waiting: ${ms(Math.max(0, interval.avg - frame.avg))} ms`);
|
||||||
|
separator();
|
||||||
|
|
||||||
|
text("cpu per frame");
|
||||||
|
for (const [name, section] of profiler.cpu) text(stats(` ${name}`, section));
|
||||||
|
separator();
|
||||||
|
|
||||||
|
if (!gpu_timer?.supported) {
|
||||||
|
text("gpu: no timestamp-query on this device");
|
||||||
|
} else {
|
||||||
|
text(`gpu per frame: ${ms(gpu_timer.total)} ms`);
|
||||||
|
if (!render_debug.split_passes) text(" (split_passes times each section)");
|
||||||
|
for (const [label, time] of gpu_timer.results) text(` ${label}: ${ms(time)} ms`);
|
||||||
|
}
|
||||||
|
separator();
|
||||||
|
|
||||||
|
const { draw_calls, passes, quads } = render_stats;
|
||||||
|
text(`draw calls: ${draw_calls}, passes: ${passes}`);
|
||||||
|
for (const layer of RENDER_LAYERS) text(` ${layer}: ${quads[layer].toLocaleString()} quads`);
|
||||||
|
const level = client.level;
|
||||||
|
const level_renderer = client.game_renderer.level_renderer;
|
||||||
|
const { meshed, bytes } = this.#count_chunks(client);
|
||||||
|
text(`chunks: ${level.chunks.size} loaded`);
|
||||||
|
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(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`);
|
||||||
|
separator();
|
||||||
|
|
||||||
|
text("switches");
|
||||||
|
this.#render_fields(render_debug);
|
||||||
|
this.#render_fields(level_renderer.draw);
|
||||||
|
DebugUI.end();
|
||||||
|
|
||||||
|
if (copy) {
|
||||||
|
const switches = { ...render_debug, ...level_renderer.draw };
|
||||||
|
lines.push(Object.entries(switches).map(([key, on]) => ` ${key}: ${on}`).join("\n"));
|
||||||
|
platform.write_clipboard(lines.join("\n")).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#start_benchmark(client: Client) {
|
||||||
|
try {
|
||||||
|
client.benchmark = new RenderBenchmark(client.game_renderer, client.connection.mods, (result) => {
|
||||||
|
client.benchmark = undefined;
|
||||||
|
if (typeof result === "string") {
|
||||||
|
this.#benchmark_status = result;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.#benchmark_report = format_report(result);
|
||||||
|
console.log(this.#benchmark_report);
|
||||||
|
this.#copy_benchmark();
|
||||||
|
});
|
||||||
|
this.#benchmark_status = "";
|
||||||
|
} catch (e) {
|
||||||
|
this.#benchmark_status = e instanceof Error ? e.message : String(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// right after the benchmark, firefox and safari only let the page copy from a click
|
||||||
|
#copy_benchmark() {
|
||||||
|
platform.write_clipboard(this.#benchmark_report!).then(
|
||||||
|
() => this.#benchmark_status = "The benchmark's results are on the clipboard",
|
||||||
|
() => this.#benchmark_status = "Click above to copy the benchmark's results",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// sections with meshes and what their meshes take on the gpu, once a second
|
||||||
|
#count_chunks(client: Client) {
|
||||||
|
const now = performance.now();
|
||||||
|
if (now - this.#chunk_stats_time < CHUNK_STATS_MS) return this.#chunk_stats;
|
||||||
|
this.#chunk_stats_time = now;
|
||||||
|
let meshed = 0;
|
||||||
|
let bytes = 0;
|
||||||
|
for (const chunk of client.level.chunks.values()) {
|
||||||
|
for (const section of chunk.sections) {
|
||||||
|
const meshes = Object.values(section.meshes);
|
||||||
|
if (meshes.length > 0) meshed += 1;
|
||||||
|
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 };
|
||||||
|
return this.#chunk_stats;
|
||||||
|
}
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
#render_fields(object: any) {
|
#render_fields(object: any) {
|
||||||
for (const key in object) {
|
for (const key in object) {
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
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";
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// made by tools/pack_gui.ts, where each gui sprite is in assets/sprites/gui.png. border is the nine slice border as
|
// made by tools/pack_gui.ts, where each gui sprite is in assets/sprites/gui.png. border is the nine slice border as
|
||||||
// left, top, right, bottom, all 0 for sprites drawn whole
|
// left, top, right, bottom, all 0 for sprites drawn whole
|
||||||
export const GUI_ATLAS = {
|
export const GUI_ATLAS = {
|
||||||
@@ -24,6 +27,12 @@ export const GUI_ATLAS = {
|
|||||||
saturation_2: { x: 70, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
saturation_2: { x: 70, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
||||||
saturation_3: { x: 80, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
saturation_3: { x: 80, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
||||||
saturation_4: { x: 90, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
saturation_4: { x: 90, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
||||||
|
// drawn by hand, not from a resource pack
|
||||||
|
air_empty: { x: 100, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
||||||
|
air_full: { x: 110, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
||||||
|
air_half: { x: 120, y: 213, width: 9, height: 9, border: [0, 0, 0, 0] },
|
||||||
|
// the slot with modern industrialization's fluid slot droplet, drawn over it by hand
|
||||||
|
fluid_slot: { x: 160, y: 0, width: 18, height: 18, border: [0, 0, 0, 0] },
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type GuiSprite = keyof typeof GUI_ATLAS;
|
export type GuiSprite = keyof typeof GUI_ATLAS;
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// 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,104 +0,0 @@
|
|||||||
import { add_player_hotbar, add_player_inventory, GuiInventoryScreen, Slot } from "./gui_screen.ts";
|
|
||||||
import { canvas, draw_rect, draw_texture_region, Texture } from "$/client/renderer/mod.ts";
|
|
||||||
import { AssetManager } from "../assets.ts";
|
|
||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
|
||||||
import { ClientMessage, ScreenLayout } from "$/common/protocol.ts";
|
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
|
||||||
import { ClientInventories } from "../inventory.ts";
|
|
||||||
|
|
||||||
// around the slots, and between the hotbar, the rest of the inventory and what's below, like minecraft's
|
|
||||||
const MARGIN = 7 * GUI_SCALE;
|
|
||||||
const GAP = 4 * GUI_SCALE;
|
|
||||||
// where the screen's own slots start, below the player's
|
|
||||||
const AREA_Y = MARGIN + GAP * 2 + SLOT_SIZE * 4;
|
|
||||||
|
|
||||||
// a screen opened by the server (chest, furnace, ...), drawn from the layout it sent
|
|
||||||
export class GuiContainer extends GuiInventoryScreen {
|
|
||||||
layout: ScreenLayout;
|
|
||||||
properties: Record<string, number>;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
inventories: ClientInventories,
|
|
||||||
send: (message: ClientMessage) => void,
|
|
||||||
layout: ScreenLayout,
|
|
||||||
properties: Record<string, number>,
|
|
||||||
) {
|
|
||||||
super(inventories, send);
|
|
||||||
this.layout = layout;
|
|
||||||
this.properties = properties;
|
|
||||||
|
|
||||||
this.inventory_width = MARGIN * 2 + SLOT_SIZE * 9;
|
|
||||||
this.inventory_height = MARGIN * 2 + GAP * 2 + SLOT_SIZE * (4 + layout.rows);
|
|
||||||
|
|
||||||
add_player_hotbar(this, MARGIN, MARGIN);
|
|
||||||
add_player_inventory(this, MARGIN, MARGIN + GAP + SLOT_SIZE);
|
|
||||||
|
|
||||||
for (const slot of layout.slots) {
|
|
||||||
this.slots.push(
|
|
||||||
new Slot("screen", slot.index, MARGIN + slot.x * SLOT_SIZE, AREA_Y + slot.y * SLOT_SIZE, slot.output),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override on_render(): void {
|
|
||||||
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
|
|
||||||
|
|
||||||
draw_gui_sprite("panel", this.x, this.y, this.inventory_width, this.inventory_height);
|
|
||||||
|
|
||||||
this.draw_bars();
|
|
||||||
|
|
||||||
super.on_render();
|
|
||||||
}
|
|
||||||
|
|
||||||
draw_bars() {
|
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
|
||||||
for (const bar of this.layout.bars) {
|
|
||||||
const x = this.x + MARGIN + bar.x * SLOT_SIZE;
|
|
||||||
const y = this.y + AREA_Y + bar.y * SLOT_SIZE;
|
|
||||||
const max = this.properties[bar.max] ?? 0;
|
|
||||||
const pct = max > 0 ? Math.max(0, Math.min(1, (this.properties[bar.value] ?? 0) / max)) : 0;
|
|
||||||
|
|
||||||
const empty = get_sprite_region(bar.empty_texture);
|
|
||||||
draw_texture_region(
|
|
||||||
atlas,
|
|
||||||
empty.x,
|
|
||||||
empty.y,
|
|
||||||
empty.width,
|
|
||||||
empty.height,
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
SLOT_SIZE,
|
|
||||||
SLOT_SIZE,
|
|
||||||
);
|
|
||||||
|
|
||||||
const full = get_sprite_region(bar.full_texture);
|
|
||||||
if (bar.direction === "right") {
|
|
||||||
draw_texture_region(
|
|
||||||
atlas,
|
|
||||||
full.x,
|
|
||||||
full.y,
|
|
||||||
full.width * pct,
|
|
||||||
full.height,
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
SLOT_SIZE * pct,
|
|
||||||
SLOT_SIZE,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// fills from the bottom up
|
|
||||||
draw_texture_region(
|
|
||||||
atlas,
|
|
||||||
full.x,
|
|
||||||
full.y + full.height * (1 - pct),
|
|
||||||
full.width,
|
|
||||||
full.height * pct,
|
|
||||||
x,
|
|
||||||
y + SLOT_SIZE * (1 - pct),
|
|
||||||
SLOT_SIZE,
|
|
||||||
SLOT_SIZE * pct,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// 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
|
||||||
|
import { TICK_DELTA } from "@/common/constants.ts";
|
||||||
|
import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "@/common/mod_api/client.ts";
|
||||||
|
import { canvas } from "../renderer/mod.ts";
|
||||||
|
import type { Client } from "../client.ts";
|
||||||
|
import type { ClientMenu } from "../menu.ts";
|
||||||
|
import { GuiMenuScreen, GuiScreen } from "./gui_screen.ts";
|
||||||
|
import { ModGraphics } from "./mod_graphics.ts";
|
||||||
|
import { GUI_SCALE } from "./gui_sprites.ts";
|
||||||
|
|
||||||
|
// runs on_tick 20 times a second from the frames' deltas, like the game's own ticks
|
||||||
|
class Ticker {
|
||||||
|
#pending = 0;
|
||||||
|
|
||||||
|
run(delta: number, tick: () => void) {
|
||||||
|
this.#pending += delta;
|
||||||
|
for (let i = 0; this.#pending >= TICK_DELTA && i < 10; i++) {
|
||||||
|
this.#pending -= TICK_DELTA;
|
||||||
|
tick();
|
||||||
|
}
|
||||||
|
this.#pending = Math.min(this.#pending, TICK_DELTA);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a menu the server opened, drawn by the screen its mod registered for the menu type
|
||||||
|
export class GuiModMenuScreen extends GuiMenuScreen {
|
||||||
|
#client: Client;
|
||||||
|
#mod: string;
|
||||||
|
#screen: MenuScreen;
|
||||||
|
#ticker = new Ticker();
|
||||||
|
|
||||||
|
constructor(client: Client, mod: string, menu: ClientMenu, create: (menu: ModClientMenu) => MenuScreen) {
|
||||||
|
const send = client.connection.send.bind(client.connection);
|
||||||
|
// this, once super has run
|
||||||
|
const self: { screen?: GuiModMenuScreen } = {};
|
||||||
|
const api: ModClientMenu = {
|
||||||
|
type: menu.type,
|
||||||
|
title: menu.title,
|
||||||
|
open_data: menu.open_data,
|
||||||
|
get data() {
|
||||||
|
return menu.data;
|
||||||
|
},
|
||||||
|
item: (slot) => menu.item(slot),
|
||||||
|
click_button: (id) => {
|
||||||
|
if (!Number.isInteger(id)) throw new Error(`a menu button is a whole number, not ${id}`);
|
||||||
|
if (self.screen && client.screens.includes(self.screen)) {
|
||||||
|
send({ type: "menu_button", menu: menu.id, button: id });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
close: () => {
|
||||||
|
if (self.screen) client.close_screen(self.screen);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const screen = create(api);
|
||||||
|
if (!(screen.width > 0 && screen.height > 0)) throw new Error(`the screen for ${menu.type} has no size`);
|
||||||
|
super(client.player.inventories, send, menu, screen.width, screen.height);
|
||||||
|
this.#client = client;
|
||||||
|
this.#mod = mod;
|
||||||
|
this.#screen = screen;
|
||||||
|
self.screen = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#guarded(what: string, fn: () => void) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${this.#mod}] the ${this.menu.type} screen's ${what} threw, closing it:`, e);
|
||||||
|
this.#client.close_screen(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override on_tick(delta: number): void {
|
||||||
|
super.on_tick(delta);
|
||||||
|
const tick = this.#screen.on_tick;
|
||||||
|
if (tick) this.#ticker.run(delta, () => this.#guarded("on_tick", () => tick.call(this.#screen)));
|
||||||
|
}
|
||||||
|
|
||||||
|
override get dim_background(): boolean {
|
||||||
|
return this.#screen.dim_background !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
override get inventory_overlays(): boolean {
|
||||||
|
return this.#screen.inventory_overlays !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
render_background(g: ModGraphics): void {
|
||||||
|
const render = this.#screen.on_render_background;
|
||||||
|
if (render) this.#guarded("on_render_background", () => render.call(this.#screen, g));
|
||||||
|
}
|
||||||
|
|
||||||
|
render_labels(g: ModGraphics): void {
|
||||||
|
const render = this.#screen.on_render_labels;
|
||||||
|
if (render) this.#guarded("on_render_labels", () => render.call(this.#screen, g));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a screen with no menu, opened by a mod's client phase
|
||||||
|
export class GuiModScreen extends GuiScreen {
|
||||||
|
#mod: string;
|
||||||
|
#screen: Screen;
|
||||||
|
#client: Client;
|
||||||
|
#ticker = new Ticker();
|
||||||
|
graphics = new ModGraphics();
|
||||||
|
// the window size on_init last saw, it runs again when it changes
|
||||||
|
#size = "";
|
||||||
|
|
||||||
|
constructor(client: Client, mod: string, screen: Screen) {
|
||||||
|
super();
|
||||||
|
this.#client = client;
|
||||||
|
this.#mod = mod;
|
||||||
|
this.#screen = screen;
|
||||||
|
}
|
||||||
|
|
||||||
|
#guarded(what: string, fn: () => void) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${this.#mod}] a screen's ${what} threw, closing it:`, e);
|
||||||
|
this.#client.close_screen(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override get typing() {
|
||||||
|
return this.graphics.typing;
|
||||||
|
}
|
||||||
|
|
||||||
|
override close_on_escape(): boolean {
|
||||||
|
let close = true;
|
||||||
|
const should = this.#screen.should_close_on_escape;
|
||||||
|
if (should) this.#guarded("should_close_on_escape", () => close = should.call(this.#screen) !== false);
|
||||||
|
return close;
|
||||||
|
}
|
||||||
|
|
||||||
|
on_tick(delta: number): void {
|
||||||
|
const size = `${canvas.width}x${canvas.height}`;
|
||||||
|
if (size !== this.#size) {
|
||||||
|
this.#size = size;
|
||||||
|
const init = this.#screen.on_init;
|
||||||
|
const [w, h] = [canvas.width / GUI_SCALE, canvas.height / GUI_SCALE];
|
||||||
|
if (init) this.#guarded("on_init", () => init.call(this.#screen, w, h));
|
||||||
|
}
|
||||||
|
const tick = this.#screen.on_tick;
|
||||||
|
if (tick) this.#ticker.run(delta, () => this.#guarded("on_tick", () => tick.call(this.#screen)));
|
||||||
|
}
|
||||||
|
|
||||||
|
on_render(): void {
|
||||||
|
this.graphics.begin();
|
||||||
|
this.#guarded("on_render", () => this.#screen.on_render(this.graphics));
|
||||||
|
this.graphics.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_close(): void {
|
||||||
|
const close = this.#screen.on_close;
|
||||||
|
if (close) this.#guarded("on_close", () => close.call(this.#screen));
|
||||||
|
}
|
||||||
|
|
||||||
|
override on_removed(): void {
|
||||||
|
const removed = this.#screen.on_removed;
|
||||||
|
if (removed) this.#guarded("on_removed", () => removed.call(this.#screen));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,46 +1,122 @@
|
|||||||
import { add_player_hotbar, add_player_inventory, GuiInventoryScreen, Slot } from "./gui_screen.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { canvas, draw_rect } from "$/client/renderer/mod.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { SLOT_SIZE } from "../../common/constants.ts";
|
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
|
||||||
import { ClientInventories } from "../inventory.ts";
|
|
||||||
import { ClientMessage, CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
|
|
||||||
|
|
||||||
// around the slots, and between the hotbar, the rest of the inventory and what's below, like minecraft's
|
import { GuiMenuScreen } from "./gui_screen.ts";
|
||||||
const MARGIN = 7 * GUI_SCALE;
|
import type { LocalPlayer } from "../entity/local_player.ts";
|
||||||
const GAP = 4 * GUI_SCALE;
|
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import type { EffectJson } from "@/common/mod_data.ts";
|
||||||
|
import { TICKS_PER_SECOND } from "@/common/constants.ts";
|
||||||
|
import { display_name } from "@/common/utils.ts";
|
||||||
|
import { ClientMessage, PLAYER_MENU_EXTRA } from "@/common/protocol.ts";
|
||||||
|
import { player_menu } from "../menu.ts";
|
||||||
|
import type { ModGraphics } from "./mod_graphics.ts";
|
||||||
|
import { draw_gui_player } from "../rendering/gui_player.ts";
|
||||||
|
import { InputManager } from "../input_manager.ts";
|
||||||
|
import { AssetManager } from "../assets.ts";
|
||||||
|
import type { Texture } from "../renderer/mod.ts";
|
||||||
|
import { GUI_SCALE } from "./gui_sprites.ts";
|
||||||
|
|
||||||
// the recipes live on the server, which fills in the result slot
|
const WIDTH = 176;
|
||||||
export class GuiPlayerInventory extends GuiInventoryScreen {
|
const HEIGHT = 166;
|
||||||
override inventory_width = MARGIN * 2 + SLOT_SIZE * 9;
|
const SLOT = 18;
|
||||||
override inventory_height = MARGIN * 2 + GAP * 2 + SLOT_SIZE * 7;
|
// around the slots, like minecraft's
|
||||||
|
const MARGIN = 7;
|
||||||
|
// effect icons in a row on a panel of their own, just above the inventory's
|
||||||
|
const ICON = 16;
|
||||||
|
const ICON_GAP = 2;
|
||||||
|
const ICON_MARGIN = 4;
|
||||||
|
const TIME_COLOR: [number, number, number, number] = [0.66, 0.66, 0.66, 1];
|
||||||
|
// the box the player stands in, left of the crafting grid, like minecraft's
|
||||||
|
const PLAYER_BOX = { x: MARGIN, y: MARGIN, size: 64 };
|
||||||
|
const PLAYER_BOX_COLOR: [number, number, number, number] = [0, 0, 0, 0.6];
|
||||||
|
// gui pixels to a skin pixel, so the player's 32 fit in the box with room to look around
|
||||||
|
const PLAYER_PIXEL = 1.6;
|
||||||
|
// the feet, above the box's bottom
|
||||||
|
const PLAYER_FEET = 4;
|
||||||
|
|
||||||
constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) {
|
// menu 0's screen: the player looking at the mouse beside the crafting grid, over the inventory, and any slots mods
|
||||||
super(inventories, send);
|
// added, with the player's effects above. the recipes live on the server, which fills in the result
|
||||||
|
export class GuiPlayerInventory extends GuiMenuScreen {
|
||||||
|
#player: LocalPlayer;
|
||||||
|
|
||||||
add_player_hotbar(this, MARGIN, MARGIN);
|
constructor(player: LocalPlayer, send: (message: ClientMessage) => void) {
|
||||||
add_player_inventory(this, MARGIN, MARGIN + GAP + SLOT_SIZE);
|
super(player.inventories, send, player_menu(player.inventories), WIDTH, HEIGHT);
|
||||||
|
this.#player = player;
|
||||||
|
}
|
||||||
|
|
||||||
const crafting_x = MARGIN;
|
render_background(g: ModGraphics): void {
|
||||||
const crafting_y = MARGIN + GAP * 2 + SLOT_SIZE * 4;
|
g.panel(0, 0, WIDTH, HEIGHT);
|
||||||
|
this.#render_player(g);
|
||||||
for (let i = 0; i < 3; i += 1) {
|
this.#render_effects(g);
|
||||||
for (let j = 0; j < 3; j += 1) {
|
// the slots mods added outside the panel get one of their own, around them with the same margin
|
||||||
this.slots.push(
|
const outside = this.menu.slots.slice(PLAYER_MENU_EXTRA)
|
||||||
new Slot("crafting", j * 3 + i, crafting_x + i * SLOT_SIZE, crafting_y + j * SLOT_SIZE),
|
.filter((s) => s.x + SLOT < 0 || s.x > WIDTH || s.y + SLOT < 0 || s.y > HEIGHT);
|
||||||
);
|
if (outside.length > 0) {
|
||||||
}
|
const left = Math.min(...outside.map((s) => s.x)) - MARGIN;
|
||||||
|
const top = Math.min(...outside.map((s) => s.y)) - MARGIN;
|
||||||
|
const right = Math.max(...outside.map((s) => s.x)) + SLOT + MARGIN;
|
||||||
|
const bottom = Math.max(...outside.map((s) => s.y)) + SLOT + MARGIN;
|
||||||
|
g.panel(left, top, right - left, bottom - top);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.slots.push(
|
// the player in their box, in their skin and what they wear, turned toward the mouse
|
||||||
new Slot("crafting", CRAFTING_RESULT_SLOT, crafting_x + 5 * SLOT_SIZE, crafting_y + 1 * SLOT_SIZE, true),
|
#render_player(g: ModGraphics) {
|
||||||
|
const { x, y, size } = PLAYER_BOX;
|
||||||
|
g.rect(x, y, size, size, PLAYER_BOX_COLOR);
|
||||||
|
const skin = this.#player.skin ?? AssetManager.instance.get<Texture>("cubi:skin");
|
||||||
|
const mouse = InputManager.get_mouse_position();
|
||||||
|
draw_gui_player(
|
||||||
|
skin,
|
||||||
|
this.#player.slim,
|
||||||
|
this.x + (x + size / 2) * GUI_SCALE,
|
||||||
|
this.y + (y + size - PLAYER_FEET) * GUI_SCALE,
|
||||||
|
PLAYER_PIXEL * GUI_SCALE,
|
||||||
|
GUI_SCALE,
|
||||||
|
mouse.x,
|
||||||
|
mouse.y,
|
||||||
|
this.#player.worn,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
override on_render(): void {
|
// the ones with an icon, left to right in the order they were added. hovering one says what it is
|
||||||
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
|
#render_effects(g: ModGraphics) {
|
||||||
|
const shown = this.#player.effects.flatMap((effect) => {
|
||||||
|
const icon = EverythingRegistry.get<EffectJson>("effects", effect.id)?.icon;
|
||||||
|
return icon ? [{ ...effect, icon }] : [];
|
||||||
|
});
|
||||||
|
if (shown.length === 0) return;
|
||||||
|
const width = shown.length * (ICON + ICON_GAP) - ICON_GAP + ICON_MARGIN * 2;
|
||||||
|
const height = ICON + ICON_MARGIN * 2;
|
||||||
|
const top = -height - ICON_GAP;
|
||||||
|
g.panel(0, top, width, height);
|
||||||
|
const mouse = g.mouse;
|
||||||
|
shown.forEach((effect, i) => {
|
||||||
|
const x = ICON_MARGIN + i * (ICON + ICON_GAP);
|
||||||
|
const y = top + ICON_MARGIN;
|
||||||
|
g.texture(effect.icon, x, y, ICON, ICON);
|
||||||
|
if (mouse.x >= x && mouse.x < x + ICON && mouse.y >= y && mouse.y < y + ICON) {
|
||||||
|
const name = display_name(effect.id) + level(effect.amplifier);
|
||||||
|
g.tooltip([name, { text: time_left(effect.duration), color: TIME_COLOR }], mouse.x, mouse.y);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
draw_gui_sprite("panel", this.x, this.y, this.inventory_width, this.inventory_height);
|
render_labels(g: ModGraphics): void {
|
||||||
|
g.text(this.menu.title, 79, 6);
|
||||||
super.on_render();
|
g.text("Inventory", 8, 73);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// like minecraft: nothing for level 1, then II, III...
|
||||||
|
function level(amplifier: number) {
|
||||||
|
const numerals = ["", " II", " III", " IV", " V", " VI", " VII", " VIII", " IX", " X"];
|
||||||
|
return numerals[amplifier] ?? ` ${amplifier + 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// minutes and seconds, like 1:05
|
||||||
|
function time_left(ticks: number) {
|
||||||
|
if (ticks < 0) return "Forever";
|
||||||
|
const seconds = Math.ceil(ticks / TICKS_PER_SECOND);
|
||||||
|
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|||||||
+171
-111
@@ -1,79 +1,76 @@
|
|||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
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, Container } from "$/common/inventory.ts";
|
import { click_slot } from "@/common/inventory.ts";
|
||||||
import { ClientMessage, ContainerKey, CRAFTING_RESULT_SLOT } 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";
|
||||||
import { canvas } from "../renderer/mod.ts";
|
import { canvas, draw_rect, draw_texture_region, Texture } from "../renderer/mod.ts";
|
||||||
import { draw_item } from "../rendering/render_utils.ts";
|
import { AssetManager } from "../assets.ts";
|
||||||
import { draw_tooltip, item_tooltip } from "./tooltip.ts";
|
import { get_sprite_region } from "../sprites.ts";
|
||||||
|
import { draw_fluid, draw_item } from "../rendering/render_utils.ts";
|
||||||
|
import { draw_tooltip, item_tooltip, tank_tooltip } from "./tooltip.ts";
|
||||||
import { ModGraphics } from "./mod_graphics.ts";
|
import { ModGraphics } from "./mod_graphics.ts";
|
||||||
import { inventory_overlays } from "../mods.ts";
|
import { inventory_overlays } from "../mods.ts";
|
||||||
|
import type { ClientFluidSlot, ClientMenu, ClientSlot } from "../menu.ts";
|
||||||
|
|
||||||
// how far past the slot's edge its highlight goes
|
// how far past the slot's edge its highlight goes
|
||||||
const HIGHLIGHT_OVERHANG = 3 * GUI_SCALE;
|
const HIGHLIGHT_OVERHANG = 3 * GUI_SCALE;
|
||||||
|
|
||||||
export class Slot {
|
|
||||||
container: ContainerKey;
|
|
||||||
index: number;
|
|
||||||
// relative to screen top left
|
|
||||||
x: number;
|
|
||||||
y: number;
|
|
||||||
// can only be taken from, like the crafting or furnace result
|
|
||||||
output: boolean;
|
|
||||||
|
|
||||||
constructor(container: ContainerKey, index: number, x: number, y: number, output = false) {
|
|
||||||
this.container = container;
|
|
||||||
this.index = index;
|
|
||||||
this.x = x;
|
|
||||||
this.y = y;
|
|
||||||
this.output = output;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export abstract class GuiScreen {
|
export abstract class GuiScreen {
|
||||||
x: number = 0;
|
x: number = 0;
|
||||||
y: number = 0;
|
y: number = 0;
|
||||||
|
|
||||||
abstract on_tick(_delta: number): void;
|
abstract on_tick(_delta: number): void;
|
||||||
abstract on_render(): void;
|
abstract on_render(): void;
|
||||||
|
// the player closed it
|
||||||
abstract on_close(): void;
|
abstract on_close(): void;
|
||||||
|
|
||||||
|
// it's gone for any reason, after on_close when the player closed it
|
||||||
|
on_removed(): void {}
|
||||||
|
|
||||||
// something in it has the keyboard, like a text field, so keybinds (inventory, drop) don't fire
|
// something in it has the keyboard, like a text field, so keybinds (inventory, drop) don't fire
|
||||||
get typing(): boolean {
|
get typing(): boolean {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
close_on_escape(): boolean {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// a screen of slots. the server owns the contents: clicks are sent to it and guessed locally
|
// a menu's screen, like minecraft's AbstractContainerScreen: in the middle of the window, it draws the menu's slots and
|
||||||
// so they feel instant, then whatever the server syncs back wins
|
// fluid slots, the item on the cursor and tooltips, and sends clicks. the server owns what's in the slots: clicks are guessed
|
||||||
export class GuiInventoryScreen extends GuiScreen {
|
// locally so they feel instant, then whatever the server syncs back wins. subclasses draw the rest
|
||||||
|
export abstract class GuiMenuScreen extends GuiScreen {
|
||||||
inventories: ClientInventories;
|
inventories: ClientInventories;
|
||||||
send: (message: ClientMessage) => void;
|
send: (message: ClientMessage) => void;
|
||||||
|
menu: ClientMenu;
|
||||||
|
// in gui pixels
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
|
||||||
slots: Slot[] = [];
|
hovering: ClientSlot | undefined;
|
||||||
hovering: Slot | undefined;
|
hovering_fluid: ClientFluidSlot | undefined;
|
||||||
inventory_width: number = 500;
|
// what the screen and mods draw with, in gui pixels
|
||||||
inventory_height: number = 500;
|
|
||||||
// what mods draw over it, like a recipe viewer
|
|
||||||
graphics = new ModGraphics();
|
graphics = new ModGraphics();
|
||||||
|
|
||||||
constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) {
|
constructor(
|
||||||
|
inventories: ClientInventories,
|
||||||
|
send: (message: ClientMessage) => void,
|
||||||
|
menu: ClientMenu,
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
) {
|
||||||
super();
|
super();
|
||||||
this.inventories = inventories;
|
this.inventories = inventories;
|
||||||
this.send = send;
|
this.send = send;
|
||||||
}
|
this.menu = menu;
|
||||||
|
this.width = width;
|
||||||
get_container(key: ContainerKey): Container | undefined {
|
this.height = height;
|
||||||
switch (key) {
|
|
||||||
case "inventory":
|
|
||||||
return this.inventories.inventory;
|
|
||||||
case "crafting":
|
|
||||||
return this.inventories.crafting;
|
|
||||||
case "screen":
|
|
||||||
return this.inventories.screen;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override get typing() {
|
override get typing() {
|
||||||
@@ -81,35 +78,39 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
on_tick(_delta: number): void {
|
on_tick(_delta: number): void {
|
||||||
this.x = canvas.width / 2 - (this.inventory_width / 2);
|
this.x = Math.floor((canvas.width - this.width * GUI_SCALE) / 2);
|
||||||
this.y = canvas.height / 2 - (this.inventory_height / 2);
|
this.y = Math.floor((canvas.height - this.height * GUI_SCALE) / 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
on_render(): void {
|
// whether the world behind it is darkened, and mods' inventory overlays show on it
|
||||||
for (const slot of this.slots) {
|
get dim_background(): boolean {
|
||||||
draw_gui_sprite("slot", this.x + slot.x, this.y + slot.y);
|
return true;
|
||||||
}
|
}
|
||||||
|
get inventory_overlays(): boolean {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
// like minecraft's, the highlight is a bit bigger than the slot, part of it under the item and part over
|
// under the slots, from the screen's top left
|
||||||
const highlight = (sprite: "slot_highlight_back" | "slot_highlight_front") => {
|
abstract render_background(g: ModGraphics): void;
|
||||||
if (this.hovering) {
|
// over the slots
|
||||||
const x = this.x + this.hovering.x - HIGHLIGHT_OVERHANG;
|
abstract render_labels(g: ModGraphics): void;
|
||||||
draw_gui_sprite(sprite, x, this.y + this.hovering.y - HIGHLIGHT_OVERHANG);
|
|
||||||
}
|
on_render(): void {
|
||||||
};
|
if (this.dim_background) draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
|
||||||
highlight("slot_highlight_back");
|
const g = this.graphics;
|
||||||
for (const slot of this.slots) {
|
g.begin();
|
||||||
const item = this.get_container(slot.container)?.get_item(slot.index);
|
g.origin_x = this.x;
|
||||||
if (item) {
|
g.origin_y = this.y;
|
||||||
draw_item(item, this.x + slot.x, this.y + slot.y);
|
this.render_background(g);
|
||||||
}
|
this.#render_slots();
|
||||||
}
|
this.render_labels(g);
|
||||||
highlight("slot_highlight_front");
|
|
||||||
|
|
||||||
// mods' overlays go on top and get the mouse first, then the slots get what they left
|
// mods' overlays go on top and get the mouse first, then the slots get what they left
|
||||||
this.#render_overlays();
|
g.origin_x = g.origin_y = 0;
|
||||||
if (this.graphics.mouse_blocked()) {
|
if (this.inventory_overlays) this.#render_overlays();
|
||||||
|
if (g.mouse_blocked()) {
|
||||||
this.hovering = undefined;
|
this.hovering = undefined;
|
||||||
|
this.hovering_fluid = undefined;
|
||||||
} else {
|
} else {
|
||||||
this.handle_interaction();
|
this.handle_interaction();
|
||||||
}
|
}
|
||||||
@@ -119,28 +120,74 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
draw_item(this.inventories.cursor.item, mouse.x, mouse.y);
|
draw_item(this.inventories.cursor.item, mouse.x, mouse.y);
|
||||||
} else if (this.hovering) {
|
} else if (this.hovering) {
|
||||||
// what's in the slot under the mouse, while not carrying anything
|
// what's in the slot under the mouse, while not carrying anything
|
||||||
const item = this.get_container(this.hovering.container)?.get_item(this.hovering.index);
|
const item = this.hovering.container.get_item(this.hovering.index);
|
||||||
if (item) {
|
if (item) {
|
||||||
draw_tooltip(item_tooltip(item), mouse.x, mouse.y);
|
draw_tooltip(item_tooltip(item), mouse.x, mouse.y);
|
||||||
}
|
}
|
||||||
|
} else if (this.hovering_fluid) {
|
||||||
|
draw_tooltip(tank_tooltip(this.hovering_fluid.tank, this.hovering_fluid.output === true), mouse.x, mouse.y);
|
||||||
}
|
}
|
||||||
this.graphics.end();
|
g.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
#slot_x(slot: { x: number }) {
|
||||||
|
return this.x + slot.x * GUI_SCALE;
|
||||||
|
}
|
||||||
|
|
||||||
|
#slot_y(slot: { y: number }) {
|
||||||
|
return this.y + slot.y * GUI_SCALE;
|
||||||
|
}
|
||||||
|
|
||||||
|
#render_slots() {
|
||||||
|
for (const slot of this.menu.slots) {
|
||||||
|
draw_gui_sprite("slot", this.#slot_x(slot), this.#slot_y(slot));
|
||||||
|
}
|
||||||
|
// like modern industrialization's, an empty one shows a droplet
|
||||||
|
for (const slot of this.menu.fluid_slots) {
|
||||||
|
draw_gui_sprite(slot.tank.fluid ? "slot" : "fluid_slot", this.#slot_x(slot), this.#slot_y(slot));
|
||||||
|
}
|
||||||
|
|
||||||
|
// like minecraft's, the highlight is a bit bigger than the slot, part of it under the item and part over
|
||||||
|
const highlight = (sprite: "slot_highlight_back" | "slot_highlight_front") => {
|
||||||
|
const hovered = this.hovering ?? this.hovering_fluid;
|
||||||
|
if (hovered) {
|
||||||
|
const x = this.#slot_x(hovered) - HIGHLIGHT_OVERHANG;
|
||||||
|
draw_gui_sprite(sprite, x, this.#slot_y(hovered) - HIGHLIGHT_OVERHANG);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
highlight("slot_highlight_back");
|
||||||
|
// the whole slot in its fluid while there's any, whatever the amount, like modern industrialization's
|
||||||
|
for (const slot of this.menu.fluid_slots) {
|
||||||
|
if (slot.tank.fluid) draw_fluid(slot.tank.fluid, this.#slot_x(slot), this.#slot_y(slot));
|
||||||
|
}
|
||||||
|
for (const slot of this.menu.slots) {
|
||||||
|
const item = slot.container.get_item(slot.index);
|
||||||
|
if (item) {
|
||||||
|
draw_item(item, this.#slot_x(slot), this.#slot_y(slot));
|
||||||
|
} else if (slot.icon) {
|
||||||
|
// where an item's sprite would be
|
||||||
|
const icon = get_sprite_region(slot.icon);
|
||||||
|
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];
|
||||||
|
draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
highlight("slot_highlight_front");
|
||||||
}
|
}
|
||||||
|
|
||||||
#render_overlays() {
|
#render_overlays() {
|
||||||
const g = this.graphics;
|
const hovered = this.hovering && this.hovering.container.get_item(this.hovering.index);
|
||||||
g.begin();
|
|
||||||
const hovered = this.hovering && this.get_container(this.hovering.container)?.get_item(this.hovering.index);
|
|
||||||
const view = {
|
const view = {
|
||||||
x: this.x,
|
menu_type: this.menu.id === PLAYER_MENU ? undefined : this.menu.type,
|
||||||
y: this.y,
|
x: this.x / GUI_SCALE,
|
||||||
width: this.inventory_width,
|
y: this.y / GUI_SCALE,
|
||||||
height: this.inventory_height,
|
width: this.width,
|
||||||
|
height: this.height,
|
||||||
hovered_item: hovered ? { id: hovered.type_id, count: hovered.amount, data: hovered.data } : undefined,
|
hovered_item: hovered ? { id: hovered.type_id, count: hovered.amount, data: hovered.data } : undefined,
|
||||||
};
|
};
|
||||||
for (const entry of [...inventory_overlays]) {
|
for (const entry of [...inventory_overlays]) {
|
||||||
try {
|
try {
|
||||||
entry.overlay.on_render(g, view);
|
entry.overlay.on_render(this.graphics, view);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// a broken overlay is taken off, not left to throw every frame
|
// a broken overlay is taken off, not left to throw every frame
|
||||||
console.error(`[${entry.mod}] inventory overlay threw, removing it:`, e);
|
console.error(`[${entry.mod}] inventory overlay threw, removing it:`, e);
|
||||||
@@ -149,19 +196,33 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override on_removed(): void {
|
||||||
|
if (!this.inventory_overlays) return;
|
||||||
|
for (const entry of [...inventory_overlays]) {
|
||||||
|
try {
|
||||||
|
entry.overlay.on_close?.();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${entry.mod}] inventory overlay's on_close threw, removing it:`, e);
|
||||||
|
inventory_overlays.splice(inventory_overlays.indexOf(entry), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
on_close(): void {
|
on_close(): void {
|
||||||
this.send({ type: "close_screen" });
|
this.send({ type: "close_menu", menu: this.menu.id });
|
||||||
|
|
||||||
// the server puts these back in the inventory, show it right away
|
// the server puts these back in the inventory, show it right away
|
||||||
const { inventory, crafting, cursor } = this.inventories;
|
const { inventory, crafting, cursor } = this.inventories;
|
||||||
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
|
if (this.menu.id === PLAYER_MENU) {
|
||||||
const item = crafting.get_item(i);
|
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
|
||||||
if (item) {
|
const item = crafting.get_item(i);
|
||||||
inventory.add_item(item);
|
if (item) {
|
||||||
crafting.set_item(i, undefined);
|
inventory.add_item(item);
|
||||||
|
crafting.set_item(i, undefined);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
crafting.set_item(CRAFTING_RESULT_SLOT, undefined);
|
||||||
}
|
}
|
||||||
crafting.set_item(CRAFTING_RESULT_SLOT, undefined);
|
|
||||||
if (cursor.item) {
|
if (cursor.item) {
|
||||||
inventory.add_item(cursor.item);
|
inventory.add_item(cursor.item);
|
||||||
cursor.item = undefined;
|
cursor.item = undefined;
|
||||||
@@ -170,11 +231,28 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
|
|
||||||
handle_interaction() {
|
handle_interaction() {
|
||||||
this.hovering = undefined;
|
this.hovering = undefined;
|
||||||
|
this.hovering_fluid = undefined;
|
||||||
const mouse = InputManager.get_mouse_position();
|
const mouse = InputManager.get_mouse_position();
|
||||||
|
|
||||||
for (const slot of this.slots) {
|
for (const [index, slot] of this.menu.fluid_slots.entries()) {
|
||||||
const hovering = point_inside_rec(mouse.x, mouse.y, this.x + slot.x, this.y + slot.y, SLOT_SIZE, SLOT_SIZE);
|
const [x, y] = [this.#slot_x(slot), this.#slot_y(slot)];
|
||||||
if (!hovering) {
|
if (!point_inside_rec(mouse.x, mouse.y, x, y, SLOT_SIZE, SLOT_SIZE)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
this.hovering_fluid = slot;
|
||||||
|
for (const button of [0, 2]) {
|
||||||
|
if (InputManager.is_mouse_pressed(button)) {
|
||||||
|
InputManager.consume_mouse(button);
|
||||||
|
// what the cursor's container turns into depends on the tank, the server says
|
||||||
|
this.send({ type: "click_fluid", menu: this.menu.id, slot: index });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [index, slot] of this.menu.slots.entries()) {
|
||||||
|
const [x, y] = [this.#slot_x(slot), this.#slot_y(slot)];
|
||||||
|
if (!point_inside_rec(mouse.x, mouse.y, x, y, SLOT_SIZE, SLOT_SIZE)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
this.hovering = slot;
|
this.hovering = slot;
|
||||||
@@ -182,40 +260,22 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
for (const button of [0, 2]) {
|
for (const button of [0, 2]) {
|
||||||
if (InputManager.is_mouse_pressed(button)) {
|
if (InputManager.is_mouse_pressed(button)) {
|
||||||
InputManager.consume_mouse(button);
|
InputManager.consume_mouse(button);
|
||||||
this.click(slot, button);
|
this.click(index, button);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
click(slot: Slot, button: number) {
|
click(index: number, button: number) {
|
||||||
|
const slot = this.menu.slots[index];
|
||||||
const shift = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight");
|
const shift = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight");
|
||||||
this.send({ type: "click", container: slot.container, index: slot.index, button, shift });
|
this.send({ type: "click", menu: this.menu.id, slot: index, button, shift });
|
||||||
|
|
||||||
// output slots depend on server side things like recipes, and where a shift click goes on slot filters only the
|
// output slots depend on server side things like recipes, and where a shift click goes on slot filters only the
|
||||||
// server has, just wait for the server
|
// server has, just wait for the server
|
||||||
const container = this.get_container(slot.container);
|
if (!slot.output && !shift) {
|
||||||
if (container && !slot.output && !shift) {
|
click_slot(slot.container, slot.index, this.inventories.cursor, button, slot.max_count);
|
||||||
click_slot(container, slot.index, this.inventories.cursor, button);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// generic methods that is often needed
|
|
||||||
|
|
||||||
export function add_player_inventory(handler: GuiInventoryScreen, offset_x: number, offset_y: number) {
|
|
||||||
for (let i = 0; i < 3; ++i) {
|
|
||||||
for (let l = 0; l < 9; ++l) {
|
|
||||||
handler.slots.push(
|
|
||||||
new Slot("inventory", l + i * 9 + 9, offset_x + l * SLOT_SIZE, offset_y + i * SLOT_SIZE),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function add_player_hotbar(handler: GuiInventoryScreen, offset_x: number, offset_y: number) {
|
|
||||||
for (let i = 0; i < 9; ++i) {
|
|
||||||
handler.slots.push(new Slot("inventory", i, offset_x + i * SLOT_SIZE, offset_y));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { AssetManager } from "$/client/assets.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import type { Texture } from "$/client/renderer/mod.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { draw_nine_slice } from "$/client/rendering/render_utils.ts";
|
|
||||||
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
|
import type { Texture } from "@/client/renderer/mod.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
|
||||||
@@ -16,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(
|
||||||
|
|||||||
+19
-135
@@ -1,142 +1,26 @@
|
|||||||
import type { Client } from "$/client/client.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import type { ClientInventories } from "$/client/inventory.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { draw_item } from "$/client/rendering/render_utils.ts";
|
|
||||||
import { canvas, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
|
||||||
import { display_name } from "$/common/utils.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
|
import type { Client } from "@/client/client.ts";
|
||||||
const HOTBAR_WIDTH = 182;
|
import { render_hud_layers } from "@/client/mods.ts";
|
||||||
const HOTBAR_HEIGHT = 22;
|
import { canvas } from "@/client/renderer/mod.ts";
|
||||||
// each slot is 20 across, the item sits 3 in from its corner and the selection 1 out
|
import type { HudSpace } from "@/common/mod_api/client.ts";
|
||||||
const HOTBAR_CELL = 20;
|
import { ModGraphics } from "./mod_graphics.ts";
|
||||||
const HOTBAR_ITEM_INSET = 3;
|
import { GUI_SCALE } from "./gui_sprites.ts";
|
||||||
// hearts and hunger: 10 icons each, 8 apart, above the hotbar's top
|
|
||||||
const ICON_SIZE = 9;
|
|
||||||
const ICON_SPACING = 8;
|
|
||||||
const ICONS_ABOVE_HOTBAR = 17;
|
|
||||||
const MAX_VITAL = 20;
|
|
||||||
// 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;
|
|
||||||
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];
|
|
||||||
|
|
||||||
// what's drawn over the world while playing, like minecraft's Gui: hotbar, crosshair and chat
|
// between the top of the hud and the bottom of chat, in gui pixels
|
||||||
|
const CHAT_GAP = 4;
|
||||||
|
|
||||||
|
// 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;
|
|
||||||
|
|
||||||
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();
|
||||||
this.#render_held_name(client.player.inventories);
|
render_hud_layers(this.#graphics, space);
|
||||||
this.#render_crosshair();
|
this.#graphics.end();
|
||||||
client.chat.render(false, icons_y() - HELD_NAME_GAP);
|
const top = Math.max(space.left_height, space.right_height) + CHAT_GAP;
|
||||||
}
|
client.chat.render(false, canvas.height - top * GUI_SCALE);
|
||||||
|
|
||||||
#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
|
|
||||||
#render_held_name(inventories: ClientInventories) {
|
|
||||||
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);
|
|
||||||
const name = display_name(item.type_id);
|
|
||||||
const x = (canvas.width - measure_text(name, TEXT_SCALE)) / 2;
|
|
||||||
const y = icons_y() - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE;
|
|
||||||
// a shadow so it reads over bright sky and snow
|
|
||||||
draw_text(name, x + TEXT_SCALE, y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, alpha]);
|
|
||||||
draw_text(name, x, y, TEXT_SCALE, [1, 1, 1, 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
|
|
||||||
#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);
|
|
||||||
|
|
||||||
for (let i = 0; i < MAX_VITAL / 2; i++) {
|
|
||||||
const heart_x = left + i * ICON_SPACING * GUI_SCALE;
|
|
||||||
draw_gui_sprite("heart_container", heart_x, y);
|
|
||||||
const heart = icon_fill(health, i);
|
|
||||||
if (heart) {
|
|
||||||
draw_gui_sprite(heart === "full" ? "heart_full" : "heart_half", heart_x, y);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#render_crosshair() {
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// whether icon i of a 0 to 20 value 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;
|
||||||
|
}
|
||||||
+142
-75
@@ -1,13 +1,16 @@
|
|||||||
// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer.
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// one per screen, so text inputs keep their text and focus while it's open
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
|
||||||
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
// the immediate mode drawing mods' client phases get (Graphics in common/mod_api/client.ts), on top of the renderer.
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
// one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas
|
||||||
import type { Color, Graphics } from "$/common/mod_api/client.ts";
|
// pixels each
|
||||||
import type { KeyCode } from "$/common/mod_api/shared.ts";
|
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { point_inside_rec } from "$/common/utils.ts";
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import type { Color, Graphics, TooltipLine } from "@/common/mod_api/client.ts";
|
||||||
import { InputManager, type KeyCode as InputKey } from "$/client/input_manager.ts";
|
import type { FluidVariant, ItemStack as ApiItemStack, KeyCode } from "@/common/mod_api/shared.ts";
|
||||||
|
import { point_inside_rec } from "@/common/utils.ts";
|
||||||
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
|
import { InputManager, type KeyCode as InputKey } from "@/client/input_manager.ts";
|
||||||
import {
|
import {
|
||||||
begin_clip,
|
begin_clip,
|
||||||
canvas,
|
canvas,
|
||||||
@@ -17,41 +20,60 @@ import {
|
|||||||
end_clip,
|
end_clip,
|
||||||
measure_text,
|
measure_text,
|
||||||
Texture,
|
Texture,
|
||||||
} from "$/client/renderer/mod.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { 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;
|
||||||
|
|
||||||
|
// gui pixels to the canvas's, see GUI_SCALE
|
||||||
|
const S = GUI_SCALE;
|
||||||
|
|
||||||
export class ModGraphics implements Graphics {
|
export class ModGraphics implements Graphics {
|
||||||
|
// where gui pixel 0, 0 is on the canvas: a menu screen's top left, or the window's
|
||||||
|
origin_x = 0;
|
||||||
|
origin_y = 0;
|
||||||
// text inputs by id, and which one has the keyboard
|
// text inputs by id, and which one has the keyboard
|
||||||
#inputs = new Map<string, TextInput>();
|
#inputs = new Map<string, TextInput>();
|
||||||
#focused: string | undefined;
|
#focused: string | undefined;
|
||||||
#tooltip: { lines: TooltipLine[]; x: number; y: number } | undefined;
|
#tooltip: { lines: TooltipLine[]; x: number; y: number } | undefined;
|
||||||
// areas the screen underneath shouldn't take the mouse in, this frame
|
// areas the screen underneath shouldn't take the mouse in this frame, on the canvas
|
||||||
#blocked: { x: number; y: number; w: number; h: number }[] = [];
|
#blocked: { x: number; y: number; w: number; h: number }[] = [];
|
||||||
#clicks_consumed = false;
|
#clicks_consumed = false;
|
||||||
|
|
||||||
|
// the whole window, in gui pixels
|
||||||
get width() {
|
get width() {
|
||||||
return canvas.width;
|
return canvas.width / S;
|
||||||
}
|
}
|
||||||
|
|
||||||
get height() {
|
get height() {
|
||||||
return canvas.height;
|
return canvas.height / S;
|
||||||
|
}
|
||||||
|
|
||||||
|
get text_height() {
|
||||||
|
return TEXT_HEIGHT * TEXT_SCALE / S;
|
||||||
}
|
}
|
||||||
|
|
||||||
get mouse() {
|
get mouse() {
|
||||||
const { x, y } = InputManager.get_mouse_position();
|
const { x, y } = InputManager.get_mouse_position();
|
||||||
return {
|
return {
|
||||||
x,
|
x: (x - this.origin_x) / S,
|
||||||
y,
|
y: (y - this.origin_y) / S,
|
||||||
down: InputManager.is_mouse_down(0),
|
down: InputManager.is_mouse_down(0),
|
||||||
pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(0),
|
pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(0),
|
||||||
right_pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(2),
|
right_pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(2),
|
||||||
@@ -77,51 +99,113 @@ export class ModGraphics implements Graphics {
|
|||||||
|
|
||||||
// whether the screen underneath should ignore the mouse
|
// whether the screen underneath should ignore the mouse
|
||||||
mouse_blocked() {
|
mouse_blocked() {
|
||||||
const { x, y } = this.mouse;
|
const { x, y } = InputManager.get_mouse_position();
|
||||||
return this.#clicks_consumed || this.#blocked.some((r) => point_inside_rec(x, y, r.x, r.y, r.w, r.h));
|
return this.#clicks_consumed || this.#blocked.some((r) => point_inside_rec(x, y, r.x, r.y, r.w, r.h));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// a gui position on the canvas
|
||||||
|
#x(x: number) {
|
||||||
|
return this.origin_x + x * S;
|
||||||
|
}
|
||||||
|
|
||||||
|
#y(y: number) {
|
||||||
|
return this.origin_y + y * S;
|
||||||
|
}
|
||||||
|
|
||||||
rect(x: number, y: number, w: number, h: number, color: Color = WHITE) {
|
rect(x: number, y: number, w: number, h: number, color: Color = WHITE) {
|
||||||
draw_rect(x, y, w, h, color);
|
draw_rect(this.#x(x), this.#y(y), w * S, h * S, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
panel(x: number, y: number, w: number, h: number) {
|
panel(x: number, y: number, w: number, h: number) {
|
||||||
draw_gui_sprite("panel", x, y, w, h);
|
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, x, y, options.scale ?? TEXT_SCALE, 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 = TEXT_SCALE) {
|
measure_text(text: string, scale = 1) {
|
||||||
return measure_text(text, scale);
|
return measure_text(text, TEXT_SCALE * scale) / S;
|
||||||
}
|
}
|
||||||
|
|
||||||
texture(id: string, x: number, y: number, w: number, h: number) {
|
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;
|
||||||
draw_texture_region(
|
draw_texture_region(
|
||||||
atlas,
|
atlas,
|
||||||
region.x,
|
region.x + region.width * u,
|
||||||
region.y,
|
region.y + region.height * v,
|
||||||
region.width,
|
region.width * pw,
|
||||||
region.height,
|
region.height * ph,
|
||||||
x,
|
this.#x(x),
|
||||||
y,
|
this.#y(y),
|
||||||
w,
|
w * S,
|
||||||
h,
|
h * S,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
item(id: string, x: number, y: number, count = 1) {
|
progress(
|
||||||
|
empty: string,
|
||||||
|
full: string,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
w: number,
|
||||||
|
h: number,
|
||||||
|
filled: number,
|
||||||
|
direction: "right" | "up" = "right",
|
||||||
|
) {
|
||||||
|
// nothing filled for NaN too, like progress / max before there's a max
|
||||||
|
const done = filled > 0 ? Math.min(1, filled) : 0;
|
||||||
|
this.texture(empty, x, y, w, h);
|
||||||
|
if (direction === "right") {
|
||||||
|
this.texture(full, x, y, w * done, h, [0, 0, done, 1]);
|
||||||
|
} else {
|
||||||
|
this.texture(full, x, y + h * (1 - done), w, h * done, [0, 1 - done, 1, done]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
if (count === 1) stack.max_amount = 1;
|
draw_item(stack, this.#x(x), this.#y(y), count !== 1 && stack.max_amount !== 1);
|
||||||
draw_item(stack, x, y);
|
}
|
||||||
|
|
||||||
|
fluid(fluid: FluidVariant, x: number, y: number, filled = 1) {
|
||||||
|
draw_fluid(fluid, this.#x(x), this.#y(y), filled);
|
||||||
}
|
}
|
||||||
|
|
||||||
clip(x: number, y: number, w: number, h: number, draw: () => void) {
|
clip(x: number, y: number, w: number, h: number, draw: () => void) {
|
||||||
|
this.#clip_canvas(this.#x(x), this.#y(y), w * S, h * S, draw);
|
||||||
|
}
|
||||||
|
|
||||||
|
#clip_canvas(x: number, y: number, w: number, h: number, draw: () => void) {
|
||||||
begin_clip(x, y, w, h);
|
begin_clip(x, y, w, h);
|
||||||
try {
|
try {
|
||||||
draw();
|
draw();
|
||||||
@@ -132,9 +216,10 @@ export class ModGraphics implements Graphics {
|
|||||||
|
|
||||||
button(label: string, x: number, y: number, w: number, h: number): boolean {
|
button(label: string, x: number, y: number, w: number, h: number): boolean {
|
||||||
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, h);
|
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, h);
|
||||||
draw_gui_sprite(hovered ? "button_highlighted" : "button", x, y, w, h);
|
const [cx, cy, cw, ch] = [this.#x(x), this.#y(y), w * S, h * S];
|
||||||
|
draw_gui_sprite(hovered ? "button_highlighted" : "button", cx, cy, cw, ch);
|
||||||
const text_width = measure_text(label, TEXT_SCALE);
|
const text_width = measure_text(label, TEXT_SCALE);
|
||||||
draw_text(label, x + (w - text_width) / 2, y + (h - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE, WHITE);
|
draw_text(label, cx + (cw - text_width) / 2, cy + (ch - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE, WHITE);
|
||||||
if (hovered && this.mouse.pressed) {
|
if (hovered && this.mouse.pressed) {
|
||||||
this.consume_click();
|
this.consume_click();
|
||||||
return true;
|
return true;
|
||||||
@@ -142,15 +227,17 @@ export class ModGraphics implements Graphics {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// INPUT_HEIGHT canvas pixels tall
|
||||||
text_input(id: string, x: number, y: number, w: number): string {
|
text_input(id: string, x: number, y: number, w: number): string {
|
||||||
let input = this.#inputs.get(id);
|
let input = this.#inputs.get(id);
|
||||||
if (!input) {
|
if (!input) {
|
||||||
input = new TextInput("", 256);
|
input = new TextInput("", 256);
|
||||||
this.#inputs.set(id, input);
|
this.#inputs.set(id, input);
|
||||||
}
|
}
|
||||||
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT);
|
const [cx, cy, cw] = [this.#x(x), this.#y(y), w * S];
|
||||||
|
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT / S);
|
||||||
if (this.#focused === id || (hovered && this.mouse.pressed)) {
|
if (this.#focused === id || (hovered && this.mouse.pressed)) {
|
||||||
input.handle_mouse({ x, y, width: w, height: INPUT_HEIGHT }, x + 6);
|
input.handle_mouse({ x: cx, y: cy, width: cw, height: INPUT_HEIGHT }, cx + 6);
|
||||||
}
|
}
|
||||||
if (this.mouse.pressed) {
|
if (this.mouse.pressed) {
|
||||||
if (hovered) {
|
if (hovered) {
|
||||||
@@ -169,15 +256,15 @@ export class ModGraphics implements Graphics {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
draw_gui_sprite(focused ? "text_field_highlighted" : "text_field", x, y, w, INPUT_HEIGHT);
|
draw_gui_sprite(focused ? "text_field_highlighted" : "text_field", cx, cy, cw, INPUT_HEIGHT);
|
||||||
// inside the field's border, so long text doesn't go over it
|
// inside the field's border, so long text doesn't go over it
|
||||||
this.clip(x + FIELD_BORDER, y + 2, w - FIELD_BORDER * 2, INPUT_HEIGHT - 4, () => {
|
this.#clip_canvas(cx + FIELD_BORDER, cy + 2, cw - FIELD_BORDER * 2, INPUT_HEIGHT - 4, () => {
|
||||||
if (focused) {
|
if (focused) {
|
||||||
input.draw_selection(x + 6, y + 6, INPUT_HEIGHT - 12);
|
input.draw_selection(cx + 6, cy + 6, INPUT_HEIGHT - 12);
|
||||||
}
|
}
|
||||||
draw_text(input.value, x + 6, y + 4, TEXT_SCALE, WHITE);
|
draw_text(input.value, cx + 6, cy + 4, TEXT_SCALE, WHITE);
|
||||||
if (focused && TextInput.caret_visible()) {
|
if (focused && TextInput.caret_visible()) {
|
||||||
draw_rect(input.caret_x(x + 6), y + 6, 2, INPUT_HEIGHT - 12, WHITE);
|
draw_rect(input.caret_x(cx + 6), cy + 6, 2, INPUT_HEIGHT - 12, WHITE);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return input.value;
|
return input.value;
|
||||||
@@ -187,38 +274,21 @@ export class ModGraphics implements Graphics {
|
|||||||
throw new Error("g.slider isn't implemented yet");
|
throw new Error("g.slider isn't implemented yet");
|
||||||
}
|
}
|
||||||
|
|
||||||
slots(): void {
|
|
||||||
throw new Error("g.slots isn't implemented yet");
|
|
||||||
}
|
|
||||||
|
|
||||||
key_pressed(key: KeyCode): boolean {
|
key_pressed(key: KeyCode): boolean {
|
||||||
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,
|
|
||||||
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)),
|
this.#tooltip = { lines, x: this.#x(x), y: this.#y(y) };
|
||||||
...extra.map((line) =>
|
|
||||||
typeof line === "string" ? { text: line, color: GREY } : { text: line.text, color: line.color ?? GREY }
|
|
||||||
),
|
|
||||||
];
|
|
||||||
this.#tooltip = { lines, x, y };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
block_mouse(x: number, y: number, w: number, h: number) {
|
block_mouse(x: number, y: number, w: number, h: number) {
|
||||||
this.#blocked.push({ x, y, w, h });
|
this.#blocked.push({ x: this.#x(x), y: this.#y(y), w: w * S, h: h * S });
|
||||||
}
|
}
|
||||||
|
|
||||||
consume_click() {
|
consume_click() {
|
||||||
@@ -227,6 +297,3 @@ export class ModGraphics implements Graphics {
|
|||||||
InputManager.consume_mouse(2);
|
InputManager.consume_mouse(2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// how big an item is drawn, for laying out around g.item
|
|
||||||
export const ITEM_SIZE = SLOT_SIZE;
|
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import type { Client } from "$/client/client.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import type { Client } from "@/client/client.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;
|
||||||
@@ -17,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()),
|
||||||
];
|
];
|
||||||
|
|||||||
+57
-56
@@ -1,14 +1,17 @@
|
|||||||
import { MAX_NAME_LENGTH } from "$/common/protocol.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { InputManager } from "$/client/input_manager.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
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 { MAX_NAME_LENGTH } from "@/common/protocol.ts";
|
||||||
import { default_player_name } from "$/client/network.ts";
|
import { InputManager } from "@/client/input_manager.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_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;
|
||||||
@@ -20,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;
|
||||||
|
|
||||||
@@ -33,13 +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());
|
||||||
|
// the desktop app for this computer's os
|
||||||
|
download_button = 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;
|
||||||
@@ -79,13 +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();
|
||||||
}
|
}
|
||||||
|
|
||||||
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,
|
||||||
@@ -97,15 +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();
|
||||||
|
|
||||||
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.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]);
|
||||||
}
|
}
|
||||||
@@ -117,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() {
|
||||||
@@ -127,23 +128,18 @@ 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 total = 2 * (LABEL_GAP + ROW_HEIGHT + GAP) + singleplayer_height + 2 * ROW_HEIGHT + GAP;
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
this.join_button.x = x;
|
for (const button of [this.join_button, this.credits_button, this.download_button]) {
|
||||||
this.join_button.y = y;
|
button.x = x;
|
||||||
this.credits_button.x = x;
|
button.y = y;
|
||||||
this.credits_button.y = y + ROW_HEIGHT + GAP;
|
y += ROW_HEIGHT + GAP;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#label(text: string, field: EditBox) {
|
#label(text: string, field: EditBox) {
|
||||||
@@ -166,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);
|
||||||
@@ -190,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) {
|
||||||
@@ -203,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;
|
||||||
}
|
}
|
||||||
@@ -222,25 +207,41 @@ 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
|
||||||
|
// gets linux's
|
||||||
|
function download_os() {
|
||||||
|
return /windows/i.test(navigator.userAgent)
|
||||||
|
? { name: "Windows", file: "/dist/windows.zip" }
|
||||||
|
: { name: "Linux", file: "/dist/linux.zip" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function download_desktop_app() {
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = download_os().file;
|
||||||
|
link.download = "";
|
||||||
|
link.click();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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);
|
||||||
}
|
}
|
||||||
|
|||||||
+87
-21
@@ -1,47 +1,97 @@
|
|||||||
// the box next to the mouse saying what an item is, like minecraft's: its name, then its lore
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import type { ItemStack } from "$/common/inventory.ts";
|
|
||||||
import { display_name } from "$/common/utils.ts";
|
// the box next to the mouse saying what an item is, like minecraft's: its name, the fluid in it, its food, mods' lines,
|
||||||
import { canvas, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
// then its lore
|
||||||
|
import { EverythingRegistry, ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import { contained_fluid, type ItemStack } from "@/common/inventory.ts";
|
||||||
|
import { type Color, TOOLTIP_PRIORITY, type TooltipLine } from "@/common/mod_api/client.ts";
|
||||||
|
import type { ItemStack as ApiItemStack } from "@/common/mod_api/shared.ts";
|
||||||
|
import { display_name } from "@/common/utils.ts";
|
||||||
|
import { fluid_rules } from "@/client/fluid_rules.ts";
|
||||||
|
import { canvas, draw_text, draw_texture_region, measure_text, type Texture } from "@/client/renderer/mod.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 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
|
||||||
|
const ICON_GAP = 4;
|
||||||
// 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)[] = [];
|
||||||
}
|
|
||||||
|
|
||||||
// its name, the item's lore from its json, then what the server's scripts said about this stack
|
// its name, the fluid a full container holds, its food, the lines mods add, then the item's lore from its json and what
|
||||||
export function item_tooltip(item: ItemStack): TooltipLine[] {
|
// the server's scripts said about this stack. extra lines go under all of it unless they have a priority
|
||||||
const lines: TooltipLine[] = [{ text: display_name(item.type_id), color: NAME_COLOR }];
|
export function item_tooltip(item: ItemStack, extra: TooltipLine[] = []): TooltipLine[] {
|
||||||
|
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);
|
||||||
if (info?.food) {
|
const fluid = contained_fluid(item.type_id, item.data);
|
||||||
lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR });
|
if (fluid) {
|
||||||
|
lines.push({
|
||||||
|
text: `${fluid_rules.name(fluid)}, ${info!.fluid_container!.capacity} mB`,
|
||||||
|
color: FLUID_COLOR,
|
||||||
|
priority: TOOLTIP_PRIORITY.fluid,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const static_lore = info?.lore;
|
if (info?.food) {
|
||||||
for (const lore of [static_lore, item.lore]) {
|
lines.push({
|
||||||
|
text: `Restores ${info.food.nutrition} hunger`,
|
||||||
|
color: FOOD_COLOR,
|
||||||
|
priority: TOOLTIP_PRIORITY.food,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const lore of [info?.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
|
||||||
|
// with a fluid container does
|
||||||
|
export function tank_tooltip(tank: MenuTank, output: boolean): TooltipLine[] {
|
||||||
|
return [
|
||||||
|
tank.fluid ? { text: fluid_rules.name(tank.fluid), color: NAME_COLOR } : { text: "Empty", color: LORE_COLOR },
|
||||||
|
{ text: `${tank.amount} / ${tank.capacity} mB`, color: FLUID_COLOR },
|
||||||
|
{
|
||||||
|
text: output ? "Fluid Output, Click to Extract" : "Fluid Input, Click to Insert or Extract",
|
||||||
|
color: LORE_COLOR,
|
||||||
|
},
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
// below and right of the mouse, moved back inside the window when it would go past its edge
|
// below and right of the mouse, moved back inside the window when it would go past its edge
|
||||||
export function draw_tooltip(lines: TooltipLine[], mouse_x: number, mouse_y: number) {
|
export function draw_tooltip(lines: TooltipLine[], mouse_x: number, mouse_y: number) {
|
||||||
const line_height = TEXT_HEIGHT * TEXT_SCALE;
|
const line_height = TEXT_HEIGHT * TEXT_SCALE;
|
||||||
const width = Math.max(...lines.map((line) => measure_text(line.text, TEXT_SCALE))) + PADDING * 2;
|
const icon_width = (line: TooltipLine) => line.icon ? line_height + ICON_GAP : 0;
|
||||||
|
const width = Math.max(...lines.map((line) => icon_width(line) + measure_text(line.text, TEXT_SCALE))) +
|
||||||
|
PADDING * 2;
|
||||||
const height = lines.length * line_height + (lines.length - 1) * LINE_GAP + PADDING * 2;
|
const height = lines.length * line_height + (lines.length - 1) * LINE_GAP + PADDING * 2;
|
||||||
|
|
||||||
let x = mouse_x + OFFSET;
|
let x = mouse_x + OFFSET;
|
||||||
@@ -52,7 +102,23 @@ 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>("cubi:textures");
|
||||||
lines.forEach((line, i) => {
|
lines.forEach((line, i) => {
|
||||||
draw_text(line.text, x + PADDING, y + PADDING + i * (line_height + LINE_GAP), TEXT_SCALE, line.color);
|
const line_y = y + PADDING + i * (line_height + LINE_GAP);
|
||||||
|
if (line.icon) {
|
||||||
|
const { x: sx, y: sy, width: sw, height: sh } = get_sprite_region(line.icon);
|
||||||
|
draw_texture_region(
|
||||||
|
atlas,
|
||||||
|
sx,
|
||||||
|
sy,
|
||||||
|
sw,
|
||||||
|
sh,
|
||||||
|
x + PADDING - line_height / 2,
|
||||||
|
line_y - line_height / 2,
|
||||||
|
line_height * 2,
|
||||||
|
line_height * 2,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
draw_text(line.text, x + PADDING + icon_width(line), line_y, TEXT_SCALE, line.color ?? WHITE);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+103
-5
@@ -1,7 +1,11 @@
|
|||||||
import { point_inside_rec } from "$/common/utils.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { InputManager, type KeyCode } from "$/client/input_manager.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
|
|
||||||
|
import { point_inside_rec } from "@/common/utils.ts";
|
||||||
|
import { InputManager, type KeyCode } from "@/client/input_manager.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
|
||||||
@@ -121,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);
|
||||||
@@ -342,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;
|
||||||
|
}
|
||||||
|
|||||||
+10
-6
@@ -1,9 +1,13 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// 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" }>;
|
||||||
@@ -20,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;
|
||||||
@@ -206,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;
|
||||||
}
|
}
|
||||||
@@ -214,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
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-11
@@ -1,20 +1,23 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
|
<!-- SPDX-FileCopyrightText: 2026 Paula Wisnievski -->
|
||||||
|
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<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, body {
|
html,
|
||||||
width: 100vw;
|
body {
|
||||||
height: 100vh;
|
width: 100vw;
|
||||||
margin: 0;
|
height: 100vh;
|
||||||
overflow: hidden;
|
margin: 0;
|
||||||
}
|
overflow: hidden;
|
||||||
canvas {
|
}
|
||||||
display: block;
|
canvas {
|
||||||
image-rendering: pixelated;
|
display: block;
|
||||||
}
|
image-rendering: pixelated;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
+73
-182
@@ -1,4 +1,7 @@
|
|||||||
import { canvas } from "./renderer/core.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { platform } from "./platform.ts";
|
||||||
|
|
||||||
export type KeyCode =
|
export type KeyCode =
|
||||||
// letters
|
// letters
|
||||||
@@ -76,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>();
|
||||||
@@ -105,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
|
||||||
@@ -114,127 +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;
|
this.keys_down.add(code);
|
||||||
|
if (key.length === 1) {
|
||||||
static initialize(canvas: HTMLCanvasElement) {
|
if (shortcut) {
|
||||||
self.addEventListener("keydown", (e) => {
|
this.shortcuts.push(key.toLowerCase());
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
if (!this.keys_down.has(e.code)) {
|
|
||||||
this.keys_pressed.add(e.code);
|
|
||||||
}
|
|
||||||
this.keys_down.add(e.code);
|
|
||||||
if (e.key.length === 1) {
|
|
||||||
if (this.#is_shortcut(e)) {
|
|
||||||
this.shortcuts.push(e.key.toLowerCase());
|
|
||||||
} else {
|
|
||||||
this.typed_characters.push(e.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);
|
|
||||||
}
|
|
||||||
this.mouse_buttons_down.add(e.button);
|
|
||||||
});
|
|
||||||
|
|
||||||
self.addEventListener("mouseup", (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
this.mouse_buttons_down.delete(e.button);
|
|
||||||
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) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (document.pointerLockElement === canvas) {
|
|
||||||
if (this.#skip_look_event) {
|
|
||||||
this.#skip_look_event = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.look_delta_x += e.movementX;
|
|
||||||
this.look_delta_y += e.movementY;
|
|
||||||
} else {
|
} else {
|
||||||
const rect = canvas.getBoundingClientRect();
|
this.typed_characters.push(key);
|
||||||
const new_x = e.clientX - rect.left;
|
|
||||||
const new_y = e.clientY - rect.top;
|
|
||||||
|
|
||||||
// not from where it was before the mouse was grabbed, that's -1
|
|
||||||
if (this.mouse_x >= 0 && this.mouse_y >= 0) {
|
|
||||||
this.mouse_delta_x += new_x - this.mouse_x;
|
|
||||||
this.mouse_delta_y += new_y - this.mouse_y;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.mouse_x = new_x;
|
|
||||||
this.mouse_y = new_y;
|
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
|
||||||
document.addEventListener("pointerlockchange", () => {
|
// for where typing comes apart from keys, the desktop app's window
|
||||||
this.#skip_look_event = document.pointerLockElement === canvas;
|
static type_text(text: string) {
|
||||||
self.setTimeout(() => {
|
this.typed_characters.push(...text);
|
||||||
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,
|
static key_up(code: string) {
|
||||||
// instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before
|
this.keys_down.delete(code);
|
||||||
document.addEventListener("fullscreenchange", () => {
|
this.keys_released.add(code);
|
||||||
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", () => {
|
// buttons are numbered like the dom's: 0 left, 1 middle, 2 right
|
||||||
this.pointer_lock_waiting = false;
|
static mouse_down(button: number) {
|
||||||
});
|
if (!this.mouse_buttons_down.has(button)) {
|
||||||
|
this.mouse_buttons_pressed.add(button);
|
||||||
|
}
|
||||||
|
this.mouse_buttons_down.add(button);
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
if (this.mouse_x >= 0 && this.mouse_y >= 0) {
|
||||||
|
this.mouse_delta_x += x - this.mouse_x;
|
||||||
|
this.mouse_delta_y += y - this.mouse_y;
|
||||||
|
}
|
||||||
|
this.mouse_x = x;
|
||||||
|
this.mouse_y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the grabbed mouse moved
|
||||||
|
static look(x: number, y: number) {
|
||||||
|
this.look_delta_x += x;
|
||||||
|
this.look_delta_y += y;
|
||||||
|
}
|
||||||
|
|
||||||
|
// down is positive, about 100 for a notch of a wheel
|
||||||
|
static scroll(amount: number) {
|
||||||
|
this.wheel_delta += amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// keys and buttons let go while the game didn't have focus never come up, so they'd stay held
|
||||||
|
static release_all() {
|
||||||
|
this.keys_down.clear();
|
||||||
|
this.mouse_buttons_down.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
static is_key_down(code: KeyCode): boolean {
|
static is_key_down(code: KeyCode): boolean {
|
||||||
@@ -283,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);
|
||||||
}
|
}
|
||||||
@@ -314,61 +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) {
|
||||||
// a retry to grab it again mustn't happen once it shouldn't be grabbed
|
platform.set_mouse_grabbed(grab);
|
||||||
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;
|
|
||||||
}
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-3
@@ -1,11 +1,16 @@
|
|||||||
import { Container, Cursor } from "$/common/inventory.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { Container, Cursor } from "@/common/inventory.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 {
|
||||||
inventory = new Container(9 * 4);
|
inventory = new Container(9 * 4);
|
||||||
crafting = new Container(10);
|
crafting = new Container(10);
|
||||||
// the open server screen's container
|
// the slots mods added to menu 0 and what's in them, see join's player_menu
|
||||||
screen: Container | undefined;
|
extra_slots: MenuSlotInfo[] = [];
|
||||||
|
extra = new Container(0);
|
||||||
cursor: Cursor = { item: undefined };
|
cursor: Cursor = { item: undefined };
|
||||||
hotbar_selected = 0;
|
hotbar_selected = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// what this client changed ahead of the server, like minecraft's BlockStatePredictionHandler. each break_block and
|
||||||
|
// use_block gets a sequence number, and the server sends block_ack with it once it's handled it, after the set_blocks
|
||||||
|
// it caused. until then, what the server says about a block a guess changed is kept here instead of shown, so the
|
||||||
|
// answer to an older click can't undo a newer guess, like a trapdoor clicked twice flickering open again
|
||||||
|
|
||||||
|
// a block as the server sends it, see set_block
|
||||||
|
export interface ServerBlock {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
z: number;
|
||||||
|
id: string;
|
||||||
|
state: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BlockPredictions {
|
||||||
|
// the last sequence number handed out
|
||||||
|
#seq = 0;
|
||||||
|
// whether a guess is running, see start
|
||||||
|
#predicting = false;
|
||||||
|
// the blocks guesses changed, by "x,y,z": the newest guess that changed it, and what the server last said is there
|
||||||
|
#server = new Map<string, { seq: number; block: ServerBlock }>();
|
||||||
|
|
||||||
|
// a guess is starting: the blocks it changes are kept track of until end. returns its sequence number, for the
|
||||||
|
// message that tells the server what the player did
|
||||||
|
start(): number {
|
||||||
|
this.#seq++;
|
||||||
|
this.#predicting = true;
|
||||||
|
return this.#seq;
|
||||||
|
}
|
||||||
|
|
||||||
|
end() {
|
||||||
|
this.#predicting = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// this client is about to change the block at x y z, which is what current gives now. the first guess to change it
|
||||||
|
// keeps that as what the server said, later ones only make it wait for their ack too
|
||||||
|
retain(x: number, y: number, z: number, current: () => ServerBlock) {
|
||||||
|
if (!this.#predicting) return;
|
||||||
|
const key = `${x},${y},${z}`;
|
||||||
|
const known = this.#server.get(key);
|
||||||
|
if (known) {
|
||||||
|
known.seq = this.#seq;
|
||||||
|
} else {
|
||||||
|
this.#server.set(key, { seq: this.#seq, block: current() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the server says x y z is id with state. returns true when a guess about it is waiting for its ack, then it's kept
|
||||||
|
// for then instead of shown
|
||||||
|
from_server(x: number, y: number, z: number, id: string, state: number): boolean {
|
||||||
|
const known = this.#server.get(`${x},${y},${z}`);
|
||||||
|
if (!known) return false;
|
||||||
|
known.block = { x, y, z, id, state };
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the server handled everything up to seq: the blocks only those guesses changed, as the server says they are now,
|
||||||
|
// to show instead of the guesses
|
||||||
|
ack(seq: number): ServerBlock[] {
|
||||||
|
const done: ServerBlock[] = [];
|
||||||
|
for (const [key, { seq: newest, block }] of this.#server) {
|
||||||
|
if (newest > seq) continue;
|
||||||
|
this.#server.delete(key);
|
||||||
|
done.push(block);
|
||||||
|
}
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
}
|
||||||
+585
-247
File diff suppressed because it is too large
Load Diff
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
-197
@@ -1,167 +1,17 @@
|
|||||||
import { AssetManager } from "./assets.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { Client } from "./client.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
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 } from "./handshake.ts";
|
|
||||||
import { build_atlas, engine_textures } from "./atlas.ts";
|
|
||||||
import { confirm_mods } from "./confirm_mods.ts";
|
|
||||||
import { ModLoadError } from "$/common/mod_loader.ts";
|
|
||||||
import {
|
|
||||||
begin_drawing,
|
|
||||||
canvas,
|
|
||||||
clear_background,
|
|
||||||
end_drawing,
|
|
||||||
init_font,
|
|
||||||
init_window,
|
|
||||||
load_texture,
|
|
||||||
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";
|
|
||||||
|
|
||||||
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
|
// the client in a browser page, drawing on index.html's canvas. the desktop app's starts at native/main.ts
|
||||||
export // while playing, the browser asks before leaving the page. sprinting is ctrl and walking is w, and ctrl+w closes the
|
import { set_platform } from "./platform.ts";
|
||||||
// tab without the page getting a say. in fullscreen the keyboard lock catches it instead (see input_manager.ts)
|
import { browser_platform } from "./browser_platform.ts";
|
||||||
function confirm_leaving(confirm: boolean) {
|
import { listen_to_page } from "./browser_input.ts";
|
||||||
self.onbeforeunload = confirm ? (event) => event.preventDefault() : null;
|
import { init_window, resize_canvas } from "./renderer/mod.ts";
|
||||||
}
|
import { show_fatal_error } from "./fatal.ts";
|
||||||
|
import { sounds } from "./sounds.ts";
|
||||||
|
import { WebAudioOutput } from "./audio_output.ts";
|
||||||
|
import { start_client } from "./client_loop.ts";
|
||||||
|
|
||||||
class ClientLoop {
|
set_platform(browser_platform);
|
||||||
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.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");
|
|
||||||
}
|
|
||||||
|
|
||||||
loop(time: number) {
|
|
||||||
if (!this.running || is_stopped()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const delta = (time - this.last_time) / 1000;
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
end_drawing();
|
|
||||||
|
|
||||||
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;
|
|
||||||
requestAnimationFrame((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): 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();
|
|
||||||
for (const bmod of bmods) {
|
|
||||||
for (const [id, png] of bmod.textures) textures.set(id, png);
|
|
||||||
}
|
|
||||||
const atlas = await build_atlas(textures);
|
|
||||||
loaded_mods = true;
|
|
||||||
AssetManager.instance.assets["bworld:textures"] = load_texture(atlas.image);
|
|
||||||
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) {
|
||||||
@@ -175,39 +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:player", "/assets/sprites/player.png");
|
|
||||||
AssetManager.instance.load("bworld:skin", "/assets/sprites/skin_template.png");
|
|
||||||
AssetManager.instance.load("bworld:roguelike", "/assets/sprites/roguelike.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();
|
|
||||||
|
|||||||
+131
@@ -0,0 +1,131 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// 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
|
||||||
|
import { Container } from "@/common/inventory.ts";
|
||||||
|
import {
|
||||||
|
CRAFTING_RESULT_SLOT,
|
||||||
|
type MenuFluidSlotInfo,
|
||||||
|
type MenuSlotInfo,
|
||||||
|
type MenuTank,
|
||||||
|
PLAYER_MENU,
|
||||||
|
PLAYER_MENU_EXTRA,
|
||||||
|
} from "@/common/protocol.ts";
|
||||||
|
import type { ClientInventories } from "./inventory.ts";
|
||||||
|
import type { ItemStack as ApiItemStack } from "@/common/mod_api/client.ts";
|
||||||
|
|
||||||
|
export interface ClientSlot {
|
||||||
|
// where its item is on this client
|
||||||
|
container: Container;
|
||||||
|
index: number;
|
||||||
|
// gui pixels from the screen's top left to its frame
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
// can only be taken from, like the crafting or furnace result
|
||||||
|
output: boolean;
|
||||||
|
// a texture drawn while it's empty, like minecraft's armor slots
|
||||||
|
icon: string | undefined;
|
||||||
|
// the most it holds of anything, when that's less than a stack
|
||||||
|
max_count?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a tank the server's menu shows, which clicks with a fluid container on the cursor fill it from or empty it into
|
||||||
|
export interface ClientFluidSlot extends MenuFluidSlotInfo {
|
||||||
|
// what the server last said is in it
|
||||||
|
tank: MenuTank;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ClientMenu {
|
||||||
|
readonly id: number;
|
||||||
|
readonly type: string;
|
||||||
|
readonly title: string;
|
||||||
|
readonly open_data: unknown;
|
||||||
|
data: Record<string, number>;
|
||||||
|
slots: ClientSlot[];
|
||||||
|
fluid_slots: ClientFluidSlot[] = [];
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
id: number,
|
||||||
|
type: string,
|
||||||
|
title: string,
|
||||||
|
open_data: unknown,
|
||||||
|
slots: ClientSlot[],
|
||||||
|
data: Record<string, number> = {},
|
||||||
|
) {
|
||||||
|
this.id = id;
|
||||||
|
this.type = type;
|
||||||
|
this.title = title;
|
||||||
|
this.open_data = open_data;
|
||||||
|
this.slots = slots;
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what's in a slot, by menu slot index, the way mods see items. a copy
|
||||||
|
item(slot: number): ApiItemStack | undefined {
|
||||||
|
const info = this.slots[slot];
|
||||||
|
const item = info?.container.get_item(info.index);
|
||||||
|
return item && { id: item.type_id, count: item.amount, data: structuredClone(item.data) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// one the server opened: its slots' items come in menu_content, into a container of its own
|
||||||
|
static opened(
|
||||||
|
id: number,
|
||||||
|
type: string,
|
||||||
|
title: string,
|
||||||
|
open_data: unknown,
|
||||||
|
slots: MenuSlotInfo[],
|
||||||
|
fluid_slots: MenuFluidSlotInfo[] = [],
|
||||||
|
) {
|
||||||
|
const items = new Container(slots.length);
|
||||||
|
const menu = new ClientMenu(
|
||||||
|
id,
|
||||||
|
type,
|
||||||
|
title,
|
||||||
|
open_data,
|
||||||
|
slots.map((slot, index) => ({
|
||||||
|
container: items,
|
||||||
|
index,
|
||||||
|
x: slot.x,
|
||||||
|
y: slot.y,
|
||||||
|
output: slot.output === true,
|
||||||
|
icon: slot.icon,
|
||||||
|
max_count: slot.max_count,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
menu.fluid_slots = fluid_slots.map((slot) => ({ ...slot, tank: { amount: 0, capacity: 0 } }));
|
||||||
|
return menu;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// menu 0, the player's inventory and crafting grid, laid out for the inventory screen, then the slots mods added. its
|
||||||
|
// slots are the player's own containers, which the server syncs whether or not a menu is open
|
||||||
|
export function player_menu(inventories: ClientInventories): ClientMenu {
|
||||||
|
const slot = (container: Container, index: number, x: number, y: number, output = false): ClientSlot => ({
|
||||||
|
container,
|
||||||
|
index,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
output,
|
||||||
|
icon: undefined,
|
||||||
|
});
|
||||||
|
const slots: ClientSlot[] = [];
|
||||||
|
for (let i = 0; i < 36; i++) {
|
||||||
|
const row = Math.floor(i / 9);
|
||||||
|
slots.push(slot(inventories.inventory, i, 7 + (i % 9) * 18, i < 9 ? 141 : 83 + (row - 1) * 18));
|
||||||
|
}
|
||||||
|
// the crafting grid on the right, the player drawn left of it, see GuiPlayerInventory
|
||||||
|
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
|
||||||
|
slots.push(slot(inventories.crafting, i, 79 + (i % 3) * 18, 16 + Math.floor(i / 3) * 18));
|
||||||
|
}
|
||||||
|
slots.push(slot(inventories.crafting, CRAFTING_RESULT_SLOT, 151, 34, true));
|
||||||
|
if (slots.length !== PLAYER_MENU_EXTRA) throw new Error("menu 0 has the wrong slots");
|
||||||
|
for (const [i, info] of inventories.extra_slots.entries()) {
|
||||||
|
slots.push({
|
||||||
|
...slot(inventories.extra, i, info.x, info.y, info.output === true),
|
||||||
|
icon: info.icon,
|
||||||
|
max_count: info.max_count,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new ClientMenu(PLAYER_MENU, "", "Crafting", null, slots);
|
||||||
|
}
|
||||||
+380
-39
@@ -1,14 +1,55 @@
|
|||||||
// loads the mods the server lists: downloads their .bmod files, registers their data, then runs their client scripts.
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// see docs/modding/networking/index.md
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { AIR } from "$/common/constants.ts";
|
|
||||||
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
// loads the mods the server lists: downloads their .cubi files, registers their data, then runs their scripts' shared
|
||||||
import type { ClientContext, InventoryOverlay } from "$/common/mod_api/client.ts";
|
// and client phases. see docs/modding/networking/index.md
|
||||||
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
|
import { AIR } from "@/common/constants.ts";
|
||||||
import { type Bmod, read_bmod } from "$/common/bmod.ts";
|
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { display_name } from "$/common/utils.ts";
|
import type {
|
||||||
import { AIR_ID } from "$/common/protocol.ts";
|
ClientContext,
|
||||||
|
ClientMenu,
|
||||||
|
Graphics,
|
||||||
|
HudLayer,
|
||||||
|
HudSpace,
|
||||||
|
InventoryOverlay,
|
||||||
|
KeyMappings,
|
||||||
|
MenuScreen,
|
||||||
|
} from "@/common/mod_api/client.ts";
|
||||||
|
import {
|
||||||
|
check_recipe_types,
|
||||||
|
ModListing,
|
||||||
|
ModLoadError,
|
||||||
|
type Phase,
|
||||||
|
recipe_lookup,
|
||||||
|
RecipeBook,
|
||||||
|
register_mod_data,
|
||||||
|
registrar,
|
||||||
|
run_phase,
|
||||||
|
} from "@/common/mod_loader.ts";
|
||||||
|
import { blocks_api, shared_context } from "@/common/shared_context.ts";
|
||||||
|
import { type Mod, read_mod } from "@/common/mod.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 { covers_face, EMPTY_SHAPE, FULL_SHAPE } from "@/common/block_shapes.ts";
|
||||||
|
import type { SharedWorld } from "@/common/mod_api/shared.ts";
|
||||||
|
import { tag_api } from "@/common/tags.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 { item_tooltips } from "./gui/tooltip.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 { block_visuals } from "./rendering/visuals.ts";
|
||||||
|
import { entity_animators } from "./rendering/entity_animators.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 }[] = [];
|
||||||
@@ -19,51 +60,196 @@ let client: Client | undefined;
|
|||||||
// what mods draw on inventory screens, see GuiInventoryScreen
|
// what mods draw on inventory screens, see GuiInventoryScreen
|
||||||
export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = [];
|
export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = [];
|
||||||
|
|
||||||
|
// each menu type's screen, see ctx.ui.register_menu_screen
|
||||||
|
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
|
||||||
|
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
|
||||||
|
|
||||||
|
// the server sent a mod message
|
||||||
|
export function receive_mod_message(channel: string, data: unknown) {
|
||||||
|
for (const { mod, handler } of net_handlers.get(channel) ?? []) {
|
||||||
|
try {
|
||||||
|
handler(data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${mod}] a ${channel} handler threw:`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the world shared rules see on this client: what it shows. what they change is a guess the server corrects
|
||||||
|
const rules_world: SharedWorld = {
|
||||||
|
get_block(x, y, z) {
|
||||||
|
const nid = client?.level.get_block(x, y, z);
|
||||||
|
if (nid === undefined) return undefined;
|
||||||
|
if (nid === AIR) return AIR_ID;
|
||||||
|
return EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id;
|
||||||
|
},
|
||||||
|
get_state(x, y, z, name) {
|
||||||
|
const level = client?.level;
|
||||||
|
const info = level && EverythingRegistry.get_by_id<BlockRegistry>("blocks", level.get_block(x, y, z));
|
||||||
|
if (!info?.states?.some((state) => state.name === name)) return undefined;
|
||||||
|
return get_state_value(level!.get_block_value(x, y, z), info, name);
|
||||||
|
},
|
||||||
|
set_state(x, y, z, name, value) {
|
||||||
|
const level = client?.level;
|
||||||
|
const info = level && EverythingRegistry.get_by_id<BlockRegistry>("blocks", level.get_block(x, y, z));
|
||||||
|
if (!info?.states?.some((state) => state.name === name)) return false;
|
||||||
|
const old_value = level!.get_block_value(x, y, z);
|
||||||
|
const new_value = set_state_value(old_value, info, name, value);
|
||||||
|
if (new_value === undefined) return false;
|
||||||
|
if (new_value !== old_value) {
|
||||||
|
level!.add_block({ x, y, z, id: info.id }, new_value >>> 16);
|
||||||
|
predict_neighbors(x, y, z);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
is_face_sturdy(x, y, z, face) {
|
||||||
|
const shape = client?.level.collision_shape(x, y, z) ?? false;
|
||||||
|
return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face);
|
||||||
|
},
|
||||||
|
biome_at: (x, y, z) => client?.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z)),
|
||||||
|
season_at(x, y, z) {
|
||||||
|
const biome = this.biome_at(x, y, z);
|
||||||
|
return biome === undefined ? undefined : biome_season(biome, client!.level.time);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
// whether shared phases are being set up, the only time they can register rules
|
||||||
|
let rules_setup = false;
|
||||||
|
// 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
|
||||||
|
let client_setup = false;
|
||||||
|
|
||||||
|
function run_mod<T>(mod: string, what: string, fn: () => T): T | undefined {
|
||||||
|
try {
|
||||||
|
return fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${mod}] ${what} threw:`, e);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// this client changed the block at x y z ahead of the server, the blocks beside it change with it the way they will
|
||||||
|
// on the server
|
||||||
|
export function predict_neighbors(x: number, y: number, z: number) {
|
||||||
|
block_rules.notify_neighbors(x, y, z);
|
||||||
|
}
|
||||||
|
|
||||||
// the loaded mods' recipes, and their names by id
|
// the loaded mods' recipes, and their names by id
|
||||||
let recipe_book = new RecipeBook();
|
let recipe_book = new RecipeBook();
|
||||||
const mod_names = new Map<string, string>();
|
const mod_names = new Map<string, string>();
|
||||||
|
|
||||||
|
// the name of the mod whose namespace an id is in, or the namespace when no loaded mod has it
|
||||||
|
function mod_name(id: string) {
|
||||||
|
const namespace = id.split(":")[0];
|
||||||
|
return mod_names.get(namespace) ?? namespace;
|
||||||
|
}
|
||||||
|
|
||||||
export function set_mods_client(game_client: Client) {
|
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}`);
|
||||||
return bmod;
|
// the confirm screen said whether it has engine access, going by the listing
|
||||||
|
if ((mod.manifest.engine_access ?? false) !== (listing.engine_access ?? false)) {
|
||||||
|
throw new Error("its engine access isn't what the server listed");
|
||||||
|
}
|
||||||
|
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();
|
||||||
|
net_handlers.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 (const [i, bmod] of bmods.entries()) {
|
// for engine access mods. the last server's hooks go first
|
||||||
if (!bmod.scripts.client) continue;
|
clear_hooks();
|
||||||
const module = await import(script_url(bmod.scripts.client));
|
expose_engine({ common: common_engine(), client: client_engine() });
|
||||||
if (typeof module.setup !== "function") {
|
|
||||||
throw new ModLoadError(bmod.manifest.id, "the client script doesn't export a setup function");
|
// 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));
|
||||||
}
|
}
|
||||||
await module.setup(client_context(listings[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);
|
||||||
|
set_fluid_rules(new FluidRules(run_mod));
|
||||||
|
rules_setup = true;
|
||||||
|
await run("shared", (i) =>
|
||||||
|
shared_context({ id: listings[i].id, version: listings[i].version }, {
|
||||||
|
side: "client",
|
||||||
|
world: rules_world,
|
||||||
|
block_rules,
|
||||||
|
fluid_rules,
|
||||||
|
recipes: () => recipe_book,
|
||||||
|
running: () => rules_setup,
|
||||||
|
// 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;
|
||||||
|
check_recipe_types(recipe_book);
|
||||||
|
|
||||||
|
client_setup = true;
|
||||||
|
await run("client", (i) => client_context(listings[i]));
|
||||||
|
client_setup = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function script_url(code: string) {
|
function script_url(code: string) {
|
||||||
@@ -85,9 +271,7 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
return client;
|
return client;
|
||||||
};
|
};
|
||||||
|
|
||||||
const not_yet_fn = (name: string) => () => {
|
const register = registrar(mod, "client", () => client_setup);
|
||||||
throw new Error(`[${mod}] ctx.ui.${name} isn't implemented yet (custom screens, see docs/modding_plan.md)`);
|
|
||||||
};
|
|
||||||
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}`);
|
||||||
@@ -97,15 +281,52 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
return {
|
return {
|
||||||
mod: { id: mod, version: listing.version },
|
mod: { id: mod, version: listing.version },
|
||||||
ui: {
|
ui: {
|
||||||
register_screen: not_yet_fn("register_screen"),
|
register_menu_screen(type, create) {
|
||||||
open: not_yet_fn("open"),
|
register.own("menu type", type);
|
||||||
|
if (menu_screens.has(type)) register.fail(`the screen of ${type} is registered twice`);
|
||||||
|
menu_screens.set(type, { mod, create });
|
||||||
|
},
|
||||||
|
open(screen) {
|
||||||
|
if (typeof screen?.on_render !== "function") throw new Error(`[${mod}] a screen needs an on_render`);
|
||||||
|
const game = need_client();
|
||||||
|
game.push_screen(new GuiModScreen(game, mod, screen));
|
||||||
|
},
|
||||||
|
close() {
|
||||||
|
need_client().pop_screen();
|
||||||
|
},
|
||||||
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"],
|
||||||
net: not_yet("net", "mod channels") as ClientContext["net"],
|
options: key_mappings(need_client),
|
||||||
|
net: {
|
||||||
|
on(channel, handler) {
|
||||||
|
register.own("channel", channel);
|
||||||
|
const handlers = net_handlers.get(channel) ?? [];
|
||||||
|
handlers.push({ mod, handler: handler as (data: unknown) => void });
|
||||||
|
net_handlers.set(channel, handlers);
|
||||||
|
},
|
||||||
|
send(channel, data) {
|
||||||
|
register.own("channel", channel);
|
||||||
|
need_client().connection.send({ type: "mod", channel, data });
|
||||||
|
},
|
||||||
|
},
|
||||||
player: {
|
player: {
|
||||||
get name() {
|
get name() {
|
||||||
return need_client().connection.name;
|
return need_client().connection.name;
|
||||||
@@ -114,6 +335,45 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
const { x, y, z } = need_client().player;
|
const { x, y, z } = need_client().player;
|
||||||
return { x, y, z };
|
return { x, y, z };
|
||||||
},
|
},
|
||||||
|
get biome() {
|
||||||
|
const { x, y, z } = need_client().player;
|
||||||
|
return rules_world.biome_at(x, y, z);
|
||||||
|
},
|
||||||
|
get season() {
|
||||||
|
const { x, y, z } = need_client().player;
|
||||||
|
return rules_world.season_at(x, y, z);
|
||||||
|
},
|
||||||
|
is_swimming: () => need_client().player.swimming,
|
||||||
|
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) {
|
||||||
@@ -121,24 +381,105 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
if (nid === AIR) return AIR_ID;
|
if (nid === AIR) return AIR_ID;
|
||||||
return EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id;
|
return EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id;
|
||||||
},
|
},
|
||||||
|
get_client_data: (x, y, z, field) =>
|
||||||
|
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
|
||||||
|
biome_at: (x, y, z) => rules_world.biome_at(x, y, 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: {
|
||||||
ids: () => EverythingRegistry.entries("items").map(([id]) => id),
|
...shared_items_api(mod, fluid_rules),
|
||||||
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
|
|
||||||
name: (id) => (known_item(id), display_name(id)),
|
|
||||||
mod(id) {
|
mod(id) {
|
||||||
known_item(id);
|
known_item(id);
|
||||||
const namespace = id.split(":")[0];
|
return mod_name(id);
|
||||||
return mod_names.get(namespace) ?? namespace;
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
blocks: blocks_api(),
|
||||||
|
fluids: {
|
||||||
|
...fluid_rules.api(),
|
||||||
|
mod(id) {
|
||||||
|
if (!EverythingRegistry.get("fluids", id)) throw new Error(`[${mod}] unknown fluid ${id}`);
|
||||||
|
return mod_name(id);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
loot: {
|
||||||
|
table: (id) => structuredClone(EverythingRegistry.get<LootTableJson>("loot_tables", id)),
|
||||||
|
},
|
||||||
recipes: {
|
recipes: {
|
||||||
list: (type) =>
|
list: (type) =>
|
||||||
structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all),
|
structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all),
|
||||||
|
...recipe_lookup(() => recipe_book),
|
||||||
|
},
|
||||||
|
tags: tag_api(),
|
||||||
|
render: {
|
||||||
|
register_visual(block, create, options) {
|
||||||
|
register.running("visual");
|
||||||
|
const nid = EverythingRegistry.get_id("blocks", 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`);
|
||||||
|
const other = block_visuals.get(nid);
|
||||||
|
if (other) register.fail(`${block} already has a visual, from ${other.mod}`);
|
||||||
|
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),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the client's key settings as they are when read, so changing them reaches mods
|
||||||
|
function key_mappings(client: () => Client): KeyMappings {
|
||||||
|
const keys = [
|
||||||
|
"key_forward",
|
||||||
|
"key_back",
|
||||||
|
"key_left",
|
||||||
|
"key_right",
|
||||||
|
"key_jump",
|
||||||
|
"key_sprint",
|
||||||
|
"key_sneak",
|
||||||
|
"key_inventory",
|
||||||
|
"key_drop",
|
||||||
|
"key_chat",
|
||||||
|
] as const;
|
||||||
|
const mappings = {} as KeyMappings;
|
||||||
|
for (const key of keys) {
|
||||||
|
Object.defineProperty(mappings, key, { get: () => client().options[key], enumerable: true });
|
||||||
|
}
|
||||||
|
return Object.freeze(mappings);
|
||||||
|
}
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
+14
-3
@@ -1,6 +1,11 @@
|
|||||||
import { ClientMessage, EntityInfo, PlayerInfo, ServerMessage } from "$/common/protocol.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import type { ModListing } from "$/common/mod_loader.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } from "@/common/protocol.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;
|
||||||
@@ -9,8 +14,12 @@ 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
|
||||||
|
player_menu: MenuSlotInfo[];
|
||||||
time: number;
|
time: number;
|
||||||
// who was already there when we joined, they become entities in the level
|
// who was already there when we joined, they become entities in the level
|
||||||
initial_players: PlayerInfo[];
|
initial_players: PlayerInfo[];
|
||||||
@@ -22,8 +31,10 @@ 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.time = join.time;
|
this.time = join.time;
|
||||||
this.initial_players = join.players;
|
this.initial_players = join.players;
|
||||||
this.initial_entities = join.entities;
|
this.initial_entities = join.entities;
|
||||||
@@ -49,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") ?? "";
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-1
@@ -1,8 +1,14 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// 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 = 6;
|
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";
|
||||||
|
|||||||
+143
-37
@@ -1,12 +1,18 @@
|
|||||||
import type { ServerMessage } from "$/common/protocol.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { Container, ItemStack } from "$/common/inventory.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import type { ServerMessage } from "@/common/protocol.ts";
|
||||||
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
import type { Client } from "./client.ts";
|
import type { Client } from "./client.ts";
|
||||||
import { GuiContainer } from "./gui/gui_container.ts";
|
import { GuiModMenuScreen } from "./gui/gui_mod_screens.ts";
|
||||||
|
import { ClientMenu } from "./menu.ts";
|
||||||
import { GuiChat } from "./gui/gui_chat.ts";
|
import { GuiChat } from "./gui/gui_chat.ts";
|
||||||
import { RemotePlayer } from "./entity/remote_player.ts";
|
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, 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
|
||||||
@@ -74,8 +80,27 @@ export class ClientPacketListener {
|
|||||||
break;
|
break;
|
||||||
case "vitals":
|
case "vitals":
|
||||||
client.player.health = message.health;
|
client.player.health = message.health;
|
||||||
|
client.player.max_health = message.max_health;
|
||||||
client.player.food = message.food;
|
client.player.food = message.food;
|
||||||
client.player.saturation = message.saturation;
|
client.player.saturation = message.saturation;
|
||||||
|
client.player.air = message.air;
|
||||||
|
break;
|
||||||
|
case "attributes":
|
||||||
|
client.player.attack_speed = message.attack_speed;
|
||||||
|
client.player.block_interaction_range = message.block_interaction_range;
|
||||||
|
client.player.entity_interaction_range = message.entity_interaction_range;
|
||||||
|
break;
|
||||||
|
case "using_item":
|
||||||
|
client.player.using_item = message.using;
|
||||||
|
break;
|
||||||
|
case "flying":
|
||||||
|
client.player.flying = message.flying;
|
||||||
|
break;
|
||||||
|
case "creative":
|
||||||
|
client.player.creative = message.creative;
|
||||||
|
break;
|
||||||
|
case "effects":
|
||||||
|
client.player.effects = message.effects;
|
||||||
break;
|
break;
|
||||||
case "player_leave":
|
case "player_leave":
|
||||||
level.remove_entity(message.id);
|
level.remove_entity(message.id);
|
||||||
@@ -84,6 +109,14 @@ export class ClientPacketListener {
|
|||||||
const player = level.entities.get(message.id);
|
const player = level.entities.get(message.id);
|
||||||
if (player instanceof RemotePlayer) {
|
if (player instanceof RemotePlayer) {
|
||||||
player.lerp_to(message.x, message.y, message.z, message.yaw, message.pitch);
|
player.lerp_to(message.x, message.y, message.z, message.yaw, message.pitch);
|
||||||
|
player.set_swimming(message.swimming === true);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "player_worn": {
|
||||||
|
const player = level.entities.get(message.id);
|
||||||
|
if (player instanceof Player) {
|
||||||
|
player.worn = message.worn.map(ItemStack.from_data);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -113,13 +146,13 @@ 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;
|
||||||
}
|
}
|
||||||
case "entity_event": {
|
case "entity_event": {
|
||||||
const entity = level.entities.get(message.id);
|
const entity = level.entities.get(message.id);
|
||||||
if (entity instanceof RemoteEntity) {
|
if (entity instanceof RemoteEntity || entity instanceof RemotePlayer) {
|
||||||
entity.on_event(message.event);
|
entity.on_event(message.event);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -154,14 +187,36 @@ export class ClientPacketListener {
|
|||||||
case "set_block":
|
case "set_block":
|
||||||
level.apply_change(message.x, message.y, message.z, message.id, message.state);
|
level.apply_change(message.x, message.y, message.z, message.id, message.state);
|
||||||
break;
|
break;
|
||||||
case "set_block_item":
|
case "block_ack":
|
||||||
level.set_block_item(
|
level.ack_predictions(message.seq);
|
||||||
message.x,
|
|
||||||
message.y,
|
|
||||||
message.z,
|
|
||||||
message.item ? ItemStack.from_data(message.item) : undefined,
|
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
|
case "block_data":
|
||||||
|
level.set_block_data(message.x, message.y, message.z, message.data);
|
||||||
|
break;
|
||||||
|
case "break_progress":
|
||||||
|
level.set_break_progress(message.x, message.y, message.z, message.stage);
|
||||||
|
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": {
|
||||||
|
const player = client.player;
|
||||||
|
player.vx += message.motion[0];
|
||||||
|
player.vy += message.motion[1];
|
||||||
|
player.vz += message.motion[2];
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "chunk_batch_start":
|
case "chunk_batch_start":
|
||||||
this.#chunk_batch.on_batch_start();
|
this.#chunk_batch.on_batch_start();
|
||||||
break;
|
break;
|
||||||
@@ -186,49 +241,100 @@ export class ClientPacketListener {
|
|||||||
level.set_center(message.x, message.z);
|
level.set_center(message.x, message.z);
|
||||||
break;
|
break;
|
||||||
case "chat":
|
case "chat":
|
||||||
client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
|
if (message.overlay) receive_overlay_message(message.text);
|
||||||
|
else client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
|
||||||
break;
|
break;
|
||||||
case "suggestions":
|
case "suggestions":
|
||||||
if (client.screen instanceof GuiChat) {
|
if (client.screen instanceof GuiChat) {
|
||||||
client.screen.receive_suggestions(message);
|
client.screen.receive_suggestions(message);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "container": {
|
case "container":
|
||||||
let container = message.container === "screen" ? inventories.screen : inventories[message.container];
|
inventories[message.container]?.load(message.items);
|
||||||
if (message.container === "screen" && container?.size !== message.items.length) {
|
|
||||||
container = inventories.screen = new Container(message.items.length);
|
|
||||||
}
|
|
||||||
container?.load(message.items);
|
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
case "cursor":
|
case "cursor":
|
||||||
inventories.cursor.item = message.item ? ItemStack.from_data(message.item) : undefined;
|
inventories.cursor.item = message.item ? ItemStack.from_data(message.item) : undefined;
|
||||||
break;
|
break;
|
||||||
case "open_screen": {
|
case "open_menu":
|
||||||
// replace anything open locally without telling the server, it just opened this one
|
this.#open_menu(message);
|
||||||
client.screens.length = 0;
|
break;
|
||||||
const size = Math.max(0, ...message.layout.slots.map((slot) => slot.index + 1));
|
case "menu_content": {
|
||||||
inventories.screen = new Container(size);
|
const menu = this.#menu(message.id);
|
||||||
client.push_screen(
|
// every slot's item is in the menu's own container, at the slot's index
|
||||||
new GuiContainer(inventories, (m) => client.connection.send(m), message.layout, message.properties),
|
menu?.slots[0]?.container.load(message.items);
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "screen_properties": {
|
case "menu_tanks": {
|
||||||
const screen = client.screen;
|
const menu = this.#menu(message.id);
|
||||||
if (screen instanceof GuiContainer) {
|
for (const [i, tank] of message.tanks.entries()) {
|
||||||
screen.properties = message.properties;
|
if (menu?.fluid_slots[i]) menu.fluid_slots[i].tank = tank;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "teleport":
|
case "menu_data": {
|
||||||
client.player.set_position(message.x, message.y, message.z);
|
const menu = this.#menu(message.id);
|
||||||
|
if (menu) menu.data = message.data;
|
||||||
break;
|
break;
|
||||||
case "close_screen":
|
}
|
||||||
|
case "teleport": {
|
||||||
|
const player = client.player;
|
||||||
|
player.teleport_id = message.id;
|
||||||
|
if (message.motion) {
|
||||||
|
// moved by the server, like knockback: drawn easing there, and keeps going until the next one
|
||||||
|
player.x = message.x;
|
||||||
|
player.y = message.y;
|
||||||
|
player.z = message.z;
|
||||||
|
[player.vx, player.vy, player.vz] = message.motion;
|
||||||
|
} else {
|
||||||
|
player.set_position(message.x, message.y, message.z);
|
||||||
|
player.vx = player.vy = player.vz = 0;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "mod":
|
||||||
|
receive_mod_message(message.channel, message.data);
|
||||||
|
break;
|
||||||
|
case "close_menu":
|
||||||
// closed by the server (the block broke), it already put everything back
|
// closed by the server (the block broke), it already put everything back
|
||||||
client.screens = client.screens.filter((s) => !(s instanceof GuiContainer));
|
client.remove_screens((s) => s instanceof GuiModMenuScreen && s.menu.id === message.id);
|
||||||
inventories.screen = undefined;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the open menu with this id, if it's still open here
|
||||||
|
#menu(id: number): ClientMenu | undefined {
|
||||||
|
const screen = this.client.screens.find((s) => s instanceof GuiModMenuScreen && s.menu.id === id);
|
||||||
|
return (screen as GuiModMenuScreen | undefined)?.menu;
|
||||||
|
}
|
||||||
|
|
||||||
|
#open_menu(message: Extract<ServerMessage, { type: "open_menu" }>) {
|
||||||
|
const client = this.client;
|
||||||
|
const close = () => client.connection.send({ type: "close_menu", menu: message.id });
|
||||||
|
const registered = menu_screens.get(message.menu_type);
|
||||||
|
if (!registered) {
|
||||||
|
console.error(`No screen for the menu type ${message.menu_type}, closing it`);
|
||||||
|
close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const menu = ClientMenu.opened(
|
||||||
|
message.id,
|
||||||
|
message.menu_type,
|
||||||
|
message.title,
|
||||||
|
message.open_data,
|
||||||
|
message.slots,
|
||||||
|
message.fluid_slots,
|
||||||
|
);
|
||||||
|
menu.data = message.data;
|
||||||
|
let screen: GuiModMenuScreen;
|
||||||
|
try {
|
||||||
|
screen = new GuiModMenuScreen(client, registered.mod, menu, registered.create);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${registered.mod}] the ${message.menu_type} screen threw, closing it:`, e);
|
||||||
|
close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// replace anything open locally without telling the server, it just opened this one
|
||||||
|
client.remove_screens(() => true);
|
||||||
|
client.push_screen(screen);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { gpu_section } from "./renderer/mod.ts";
|
||||||
|
|
||||||
|
// how long the numbers are averaged over, so they hold still long enough to read
|
||||||
|
const WINDOW_MS = 1000;
|
||||||
|
|
||||||
|
export interface SectionStats {
|
||||||
|
// per frame, over the last window
|
||||||
|
avg: number;
|
||||||
|
max: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// one frame, in ms
|
||||||
|
export interface FrameSample {
|
||||||
|
// since the frame before started
|
||||||
|
interval: number;
|
||||||
|
// the javascript part
|
||||||
|
frame: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what the client spends its time on, for the f3 performance window. each section is timed on the cpu, and on the gpu
|
||||||
|
// too when the renderer can, see gpu_section
|
||||||
|
class Profiler {
|
||||||
|
// what the last window came to, in ms
|
||||||
|
cpu = new Map<string, SectionStats>();
|
||||||
|
frame: SectionStats = { avg: 0, max: 0 };
|
||||||
|
// the time between frames, which is what the player feels, and the javascript part of it
|
||||||
|
interval: SectionStats & { fps: number } = { avg: 0, max: 0, fps: 0 };
|
||||||
|
// every frame, while something reads them, like the benchmark
|
||||||
|
samples: FrameSample[] | undefined;
|
||||||
|
|
||||||
|
#window_start = performance.now();
|
||||||
|
#frames = 0;
|
||||||
|
#frame_start = 0;
|
||||||
|
#last_frame_start = 0;
|
||||||
|
#interval = 0;
|
||||||
|
#sums = new Map<string, number>();
|
||||||
|
#maxes = new Map<string, number>();
|
||||||
|
// this frame's time per section, added to the sums when it ends
|
||||||
|
#this_frame = new Map<string, number>();
|
||||||
|
|
||||||
|
begin_frame() {
|
||||||
|
const now = performance.now();
|
||||||
|
if (this.#last_frame_start > 0) {
|
||||||
|
this.#interval = now - this.#last_frame_start;
|
||||||
|
this.#add("interval", this.#interval);
|
||||||
|
}
|
||||||
|
this.#last_frame_start = this.#frame_start = now;
|
||||||
|
this.#this_frame.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
end_frame() {
|
||||||
|
const now = performance.now();
|
||||||
|
const frame = now - this.#frame_start;
|
||||||
|
this.#add("frame", frame);
|
||||||
|
this.samples?.push({ interval: this.#interval, frame });
|
||||||
|
for (const [name, ms] of this.#this_frame) this.#add(`cpu:${name}`, ms);
|
||||||
|
this.#frames += 1;
|
||||||
|
if (now - this.#window_start >= WINDOW_MS) this.#publish(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
// runs fn as a named part of the frame. the gpu work it records is timed under the same name
|
||||||
|
section<T>(name: string, fn: () => T): T {
|
||||||
|
gpu_section(name);
|
||||||
|
const start = performance.now();
|
||||||
|
try {
|
||||||
|
return fn();
|
||||||
|
} finally {
|
||||||
|
this.#this_frame.set(name, (this.#this_frame.get(name) ?? 0) + performance.now() - start);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#add(key: string, ms: number) {
|
||||||
|
this.#sums.set(key, (this.#sums.get(key) ?? 0) + ms);
|
||||||
|
this.#maxes.set(key, Math.max(this.#maxes.get(key) ?? 0, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
#publish(now: number) {
|
||||||
|
const frames = Math.max(1, this.#frames);
|
||||||
|
const stats = (key: string) => ({ avg: (this.#sums.get(key) ?? 0) / frames, max: this.#maxes.get(key) ?? 0 });
|
||||||
|
this.frame = stats("frame");
|
||||||
|
this.interval = { ...stats("interval"), fps: this.#frames * 1000 / (now - this.#window_start) };
|
||||||
|
this.cpu = new Map(
|
||||||
|
[...this.#sums.keys()].filter((key) => key.startsWith("cpu:")).map((key) => [key.slice(4), stats(key)]),
|
||||||
|
);
|
||||||
|
this.#sums.clear();
|
||||||
|
this.#maxes.clear();
|
||||||
|
this.#frames = 0;
|
||||||
|
this.#window_start = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const profiler = new Profiler();
|
||||||
+380
-56
@@ -1,28 +1,63 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
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";
|
||||||
|
|
||||||
|
// 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;
|
||||||
const FLOATS_PER_VERT = 9;
|
const FLOATS_PER_VERT = 9;
|
||||||
const VERTEX_STRIDE = FLOATS_PER_VERT * 4;
|
const VERTEX_STRIDE = FLOATS_PER_VERT * 4;
|
||||||
|
|
||||||
|
// msaa when it's turned on in the f3 performance window. off by default like minecraft and sodium, it's costly at
|
||||||
|
// large window sizes
|
||||||
const SAMPLE_COUNT = 4;
|
const SAMPLE_COUNT = 4;
|
||||||
|
// what the pipelines and render targets were made for
|
||||||
|
let sample_count = 1;
|
||||||
const DEPTH_FORMAT: GPUTextureFormat = "depth24plus";
|
const DEPTH_FORMAT: GPUTextureFormat = "depth24plus";
|
||||||
|
|
||||||
// dynamic uniform offsets have to be 256 aligned
|
// dynamic uniform offsets have to be 256 aligned
|
||||||
const UNIFORM_SLOT_SIZE = 256;
|
const UNIFORM_SLOT_SIZE = 256;
|
||||||
|
// the matrix, then the render time and padding to 16 bytes
|
||||||
|
const UNIFORM_FLOATS = 20;
|
||||||
|
// the render time wraps around after this many ticks, so a 32 bit float keeps it precise however long the game runs.
|
||||||
|
// a whole number of turns for every speed in steps of 0.05 rpm, so those don't jump when it wraps
|
||||||
|
const RENDER_TIME_PERIOD = 24000;
|
||||||
|
|
||||||
|
// a vertex of an instanced model, 24 bytes: position as float32x3, atlas uv as unorm16x2, tint as unorm8x3 with alpha 1
|
||||||
|
// when the face is shaded by the way it faces, and the face's normal as snorm8x3 and a padding byte
|
||||||
|
export const MODEL_VERTEX_BYTES = 24;
|
||||||
|
// an instance, 24 floats: the matrix placing its model in the world (4 columns), the axis it spins around and its rpm,
|
||||||
|
// then its offset in degrees, its block light and sky light as lightmap coordinates and a padding float
|
||||||
|
export const INSTANCE_FLOATS = 24;
|
||||||
|
|
||||||
let context: GPUCanvasContext;
|
let context: GPUCanvasContext;
|
||||||
let canvas_format: GPUTextureFormat;
|
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 };
|
||||||
// 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
|
||||||
let quad_index_buffer: GPUBuffer | undefined;
|
let quad_index_buffer: GPUBuffer | undefined;
|
||||||
let quad_index_capacity = 0;
|
let quad_index_capacity = 0;
|
||||||
@@ -32,6 +67,8 @@ let sampler: GPUSampler;
|
|||||||
// minecraft's lightmap: the color for every block light (x) and sky light (y) pair, see update_lightmap
|
// minecraft's lightmap: the color for every block light (x) and sky light (y) pair, see update_lightmap
|
||||||
let lightmap: GPUTexture;
|
let lightmap: GPUTexture;
|
||||||
let lightmap_bind_group: GPUBindGroup;
|
let lightmap_bind_group: GPUBindGroup;
|
||||||
|
// the same colors on the cpu, r g b from 0 to 1 by sky * 16 + block, for lighting entities, see light_color
|
||||||
|
const lightmap_colors = new Float32Array(16 * 16 * 3);
|
||||||
|
|
||||||
const vertex_data = new Float32Array(MAX_SPRITES * VERTS_PER_SPRITE * FLOATS_PER_VERT);
|
const vertex_data = new Float32Array(MAX_SPRITES * VERTS_PER_SPRITE * FLOATS_PER_VERT);
|
||||||
let vert_index = 0;
|
let vert_index = 0;
|
||||||
@@ -43,6 +80,9 @@ let stream_offset = 0;
|
|||||||
let uniform_buffer: GPUBuffer;
|
let uniform_buffer: GPUBuffer;
|
||||||
let uniform_bind_group: GPUBindGroup;
|
let uniform_bind_group: GPUBindGroup;
|
||||||
let uniform_slot = -1;
|
let uniform_slot = -1;
|
||||||
|
const uniform_data = new Float32Array(UNIFORM_FLOATS);
|
||||||
|
// in ticks, see set_render_time
|
||||||
|
let render_time = 0;
|
||||||
|
|
||||||
const texture_bind_groups = new WeakMap<GPUTexture, GPUBindGroup>();
|
const texture_bind_groups = new WeakMap<GPUTexture, GPUBindGroup>();
|
||||||
|
|
||||||
@@ -50,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;
|
||||||
|
|
||||||
@@ -71,6 +112,32 @@ let pending_depth_clear = false;
|
|||||||
let scissor: { x: number; y: number; width: number; height: number } | undefined;
|
let scissor: { x: number; y: number; width: number; height: number } | undefined;
|
||||||
let pending_destroy: GPUBuffer[] = [];
|
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
|
||||||
|
// 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
|
||||||
|
// the display's refresh, see the game loop in main.ts. render_regions draws terrain by region, see
|
||||||
|
// 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
|
||||||
|
export interface RenderStats {
|
||||||
|
draw_calls: number;
|
||||||
|
passes: number;
|
||||||
|
quads: Record<RenderLayer, number>;
|
||||||
|
}
|
||||||
|
const empty_stats = (): RenderStats => ({ draw_calls: 0, passes: 0, quads: { solid: 0, cutout: 0, translucent: 0 } });
|
||||||
|
export let render_stats = empty_stats();
|
||||||
|
let frame_stats = empty_stats();
|
||||||
|
export let gpu_timer: GpuTimer | undefined;
|
||||||
|
// what the gpu is, for the benchmark's report
|
||||||
|
export let adapter_info: GPUAdapterInfo | undefined;
|
||||||
|
// see set_canvas_size
|
||||||
|
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;
|
||||||
|
// what the passes starting now are timed as
|
||||||
|
let gpu_label = "other";
|
||||||
|
|
||||||
const shader_src = /* wgsl */ `
|
const shader_src = /* wgsl */ `
|
||||||
struct Uniforms {
|
struct Uniforms {
|
||||||
mvp: mat4x4<f32>,
|
mvp: mat4x4<f32>,
|
||||||
@@ -112,9 +179,11 @@ fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
|
|||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const terrain_shader_src = /* wgsl */ `
|
export const terrain_shader_src = /* wgsl */ `
|
||||||
struct Uniforms {
|
struct Uniforms {
|
||||||
mvp: mat4x4<f32>,
|
mvp: mat4x4<f32>,
|
||||||
|
// ticks, see set_render_time
|
||||||
|
time: f32,
|
||||||
}
|
}
|
||||||
|
|
||||||
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
|
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
|
||||||
@@ -147,10 +216,51 @@ fn vs_terrain(
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// v turned angle radians around axis, counterclockwise seen from the axis's end
|
||||||
|
fn spun(v: vec3<f32>, axis: vec3<f32>, angle: f32) -> vec3<f32> {
|
||||||
|
return v * cos(angle) + cross(axis, v) * sin(angle) + axis * dot(axis, v) * (1.0 - cos(angle));
|
||||||
|
}
|
||||||
|
|
||||||
|
// a model drawn many times, once per instance, see client/rendering/visuals.ts. it's turned around its block's middle
|
||||||
|
// by spin (rpm times a minute, plus the offset) before placement puts it in the world. its faces are shaded by the
|
||||||
|
// way they face after that, like the chunk mesher's, and lit by the light the instance has
|
||||||
|
@vertex
|
||||||
|
fn vs_instance(
|
||||||
|
@location(0) position: vec3<f32>,
|
||||||
|
@location(1) tex_coord: vec2<f32>,
|
||||||
|
@location(2) color: vec4<f32>,
|
||||||
|
@location(3) normal: vec4<f32>,
|
||||||
|
@location(4) placement0: vec4<f32>,
|
||||||
|
@location(5) placement1: vec4<f32>,
|
||||||
|
@location(6) placement2: vec4<f32>,
|
||||||
|
@location(7) placement3: vec4<f32>,
|
||||||
|
// the axis, then rpm
|
||||||
|
@location(8) spin: vec4<f32>,
|
||||||
|
// the offset in degrees, then block light and sky light as lightmap coordinates
|
||||||
|
@location(9) offset_light: vec4<f32>,
|
||||||
|
) -> VertexOut {
|
||||||
|
let placement = mat4x4<f32>(placement0, placement1, placement2, placement3);
|
||||||
|
// in turns first, which fract keeps small. a minute is 1200 ticks
|
||||||
|
let angle = fract(uniforms.time * spin.w / 1200.0 + offset_light.x / 360.0) * 6.2831853;
|
||||||
|
let local = spun(position - vec3<f32>(0.5), spin.xyz, angle) + vec3<f32>(0.5);
|
||||||
|
let n = normalize((placement * vec4<f32>(spun(normal.xyz, spin.xyz, angle), 0.0)).xyz);
|
||||||
|
let shade = n.x * n.x * 0.6 + n.z * n.z * 0.8 + n.y * n.y * select(0.5, 1.0, n.y > 0.0);
|
||||||
|
var out: VertexOut;
|
||||||
|
out.position = uniforms.mvp * placement * vec4<f32>(local, 1.0);
|
||||||
|
out.tex_coord = tex_coord;
|
||||||
|
out.color = vec4<f32>(color.rgb * select(1.0, shade, color.a > 0.5), 1.0);
|
||||||
|
out.light = offset_light.yz;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
fn lit(in: VertexOut) -> vec4<f32> {
|
fn lit(in: VertexOut) -> vec4<f32> {
|
||||||
let texel = textureSample(texture0, sampler0, in.tex_coord);
|
let texel = textureSample(texture0, sampler0, in.tex_coord);
|
||||||
let light = textureSample(lightmap, lightmap_sampler, in.light).rgb;
|
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), texel.a * in.color.a);
|
||||||
return vec4<f32>(texel.rgb * in.color.rgb * light, texel.a * in.color.a);
|
}
|
||||||
|
|
||||||
|
// the lightmap has no mipmaps, so a level is the same as textureSample, and it can be read after a branch
|
||||||
|
fn light_at(in: VertexOut) -> vec3<f32> {
|
||||||
|
return textureSampleLevel(lightmap, lightmap_sampler, in.light, 0.0).rgb;
|
||||||
}
|
}
|
||||||
|
|
||||||
// no discard, so the gpu can reject hidden fragments before running the shader
|
// no discard, so the gpu can reject hidden fragments before running the shader
|
||||||
@@ -159,14 +269,26 @@ fn fs_solid(in: VertexOut) -> @location(0) vec4<f32> {
|
|||||||
return vec4<f32>(lit(in).rgb, 1.0);
|
return vec4<f32>(lit(in).rgb, 1.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// alpha tested instead of blended, so it doesn't need sorting
|
// alpha tested instead of blended, so it doesn't need sorting. with msaa on, alpha to coverage instead of discard:
|
||||||
|
// alpha is 0 or 1, so a texel covers none or all of a pixel's samples, the same as discarding below 0.1, but the gpu
|
||||||
|
// can still reject hidden fragments before running the shader. clear texels skip the lightmap
|
||||||
@fragment
|
@fragment
|
||||||
fn fs_cutout(in: VertexOut) -> @location(0) vec4<f32> {
|
fn fs_cutout(in: VertexOut) -> @location(0) vec4<f32> {
|
||||||
let color = lit(in);
|
let texel = textureSample(texture0, sampler0, in.tex_coord);
|
||||||
if (color.a < 0.1) {
|
if (texel.a < 0.1) {
|
||||||
|
return vec4<f32>(0.0);
|
||||||
|
}
|
||||||
|
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// without msaa, the default, there's no alpha to coverage, so clear texels are discarded like minecraft and sodium
|
||||||
|
@fragment
|
||||||
|
fn fs_cutout_discard(in: VertexOut) -> @location(0) vec4<f32> {
|
||||||
|
let texel = textureSample(texture0, sampler0, in.tex_coord);
|
||||||
|
if (texel.a < 0.1) {
|
||||||
discard;
|
discard;
|
||||||
}
|
}
|
||||||
return vec4<f32>(color.rgb, 1.0);
|
return vec4<f32>(texel.rgb * in.color.rgb * light_at(in), 1.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@fragment
|
@fragment
|
||||||
@@ -179,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");
|
||||||
@@ -191,7 +313,11 @@ export async function init_window(canvas_element: HTMLCanvasElement) {
|
|||||||
if (!adapter) {
|
if (!adapter) {
|
||||||
throw new Error("No WebGPU adapter found");
|
throw new Error("No WebGPU adapter found");
|
||||||
}
|
}
|
||||||
device = await adapter.requestDevice();
|
adapter_info = adapter.info;
|
||||||
|
device = await adapter.requestDevice({
|
||||||
|
requiredFeatures: adapter.features.has("timestamp-query") ? ["timestamp-query"] : [],
|
||||||
|
});
|
||||||
|
gpu_timer = new GpuTimer(device);
|
||||||
device.addEventListener("uncapturederror", (event) => {
|
device.addEventListener("uncapturederror", (event) => {
|
||||||
console.error("WebGPU error:", (event as GPUUncapturedErrorEvent).error.message);
|
console.error("WebGPU error:", (event as GPUUncapturedErrorEvent).error.message);
|
||||||
});
|
});
|
||||||
@@ -257,12 +383,26 @@ export function update_lightmap(daylight = 1) {
|
|||||||
pixels[i + 1] = Math.round(color[1] * 255);
|
pixels[i + 1] = Math.round(color[1] * 255);
|
||||||
pixels[i + 2] = Math.round(color[2] * 255);
|
pixels[i + 2] = Math.round(color[2] * 255);
|
||||||
pixels[i + 3] = 255;
|
pixels[i + 3] = 255;
|
||||||
|
for (let c = 0; c < 3; c++) lightmap_colors[(sky * 16 + block) * 3 + c] = pixels[i + c] / 255;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
device.queue.writeTexture({ texture: lightmap }, pixels, { bytesPerRow: 16 * 4 }, [16, 16]);
|
device.queue.writeTexture({ texture: lightmap }, pixels, { bytesPerRow: 16 * 4 }, [16, 16]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function begin_drawing() {
|
export function begin_drawing() {
|
||||||
|
if (resize_pending) {
|
||||||
|
resize_pending = false;
|
||||||
|
resize_canvas();
|
||||||
|
}
|
||||||
|
const wanted_samples = render_debug.msaa ? SAMPLE_COUNT : 1;
|
||||||
|
if (wanted_samples !== sample_count) {
|
||||||
|
sample_count = wanted_samples;
|
||||||
|
create_pipelines();
|
||||||
|
}
|
||||||
|
render_stats = frame_stats;
|
||||||
|
frame_stats = empty_stats();
|
||||||
|
gpu_label = "other";
|
||||||
|
gpu_timer?.begin_frame();
|
||||||
encoder = device.createCommandEncoder();
|
encoder = device.createCommandEncoder();
|
||||||
frame_view = context.getCurrentTexture().createView();
|
frame_view = context.getCurrentTexture().createView();
|
||||||
ensure_render_targets();
|
ensure_render_targets();
|
||||||
@@ -284,8 +424,11 @@ export function end_drawing() {
|
|||||||
|
|
||||||
pass!.end();
|
pass!.end();
|
||||||
pass = undefined;
|
pass = undefined;
|
||||||
|
gpu_timer?.resolve(encoder!);
|
||||||
device.queue.submit([encoder!.finish()]);
|
device.queue.submit([encoder!.finish()]);
|
||||||
encoder = undefined;
|
encoder = undefined;
|
||||||
|
canvas.present?.();
|
||||||
|
gpu_timer?.read();
|
||||||
|
|
||||||
for (const buffer of pending_destroy) {
|
for (const buffer of pending_destroy) {
|
||||||
buffer.destroy();
|
buffer.destroy();
|
||||||
@@ -307,6 +450,16 @@ function update_2d_mvp() {
|
|||||||
mat4.orthoZO(ortho, l, r, b, t, n, f);
|
mat4.orthoZO(ortho, l, r, b, t, n, f);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// what the gpu work recorded from now on is timed as. with render_debug.split_passes the current pass ends here, so
|
||||||
|
// the next one is timed apart
|
||||||
|
export function gpu_section(label: string) {
|
||||||
|
gpu_label = label;
|
||||||
|
if (!render_debug.split_passes || !pass) return;
|
||||||
|
flush_batch();
|
||||||
|
pass.end();
|
||||||
|
pass = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export function begin_clip(x: number, y: number, width: number, height: number) {
|
export function begin_clip(x: number, y: number, width: number, height: number) {
|
||||||
flush_batch();
|
flush_batch();
|
||||||
scissor = { x, y, width, height };
|
scissor = { x, y, width, height };
|
||||||
@@ -348,6 +501,27 @@ export function begin_view_model(fov: number) {
|
|||||||
write_mvp();
|
write_mvp();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the lightmap's color for light packed as block light << 4 | sky light (see ClientLevel.get_light), what terrain
|
||||||
|
// lit like that is multiplied by. entities multiply it into their vertex colors, like minecraft's packed light coords
|
||||||
|
export function light_color(packed: number): [number, number, number] {
|
||||||
|
const i = ((packed & 15) * 16 + (packed >> 4)) * 3;
|
||||||
|
return [lightmap_colors[i], lightmap_colors[i + 1], lightmap_colors[i + 2]];
|
||||||
|
}
|
||||||
|
|
||||||
|
// the time rotating instances turn by, in ticks with the part of the next one (see ClientLevel.ticks). the frame's 3d
|
||||||
|
// drawing uses the time set before begin_mode_3d
|
||||||
|
export function set_render_time(ticks: number) {
|
||||||
|
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;
|
||||||
@@ -392,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
|
||||||
@@ -431,10 +607,56 @@ 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);
|
||||||
|
}
|
||||||
|
terrain_binds = { slot: uniform_slot, texture: current_texture, index_buffer, vertex_buffer };
|
||||||
|
|
||||||
render_pass.setVertexBuffer(0, 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.quads[layer] += quad_count;
|
||||||
|
}
|
||||||
|
|
||||||
|
// draws a model's quads (4 vertices each, see MODEL_VERTEX_BYTES) once for each of the first instance_count instances
|
||||||
|
// in instances (see INSTANCE_FLOATS), in one draw call. cut out like cutout terrain, or blended like translucent
|
||||||
|
// terrain, which needs drawing back to front
|
||||||
|
export function draw_instances(
|
||||||
|
model: GPUBuffer,
|
||||||
|
quad_count: number,
|
||||||
|
instances: GPUBuffer,
|
||||||
|
instance_count: number,
|
||||||
|
translucent = false,
|
||||||
|
) {
|
||||||
|
if (!current_texture || quad_count === 0 || instance_count === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ensure_quad_indices(quad_count);
|
||||||
|
const render_pass = ensure_pass();
|
||||||
|
const pipeline = translucent ? instance_pipelines.translucent : instance_pipelines.cutout;
|
||||||
|
if (current_pipeline !== pipeline) {
|
||||||
|
render_pass.setPipeline(pipeline);
|
||||||
|
current_pipeline = pipeline;
|
||||||
|
terrain_binds = undefined;
|
||||||
|
}
|
||||||
|
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
|
||||||
|
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
|
||||||
|
render_pass.setBindGroup(2, lightmap_bind_group);
|
||||||
|
render_pass.setIndexBuffer(quad_index_buffer!, "uint32");
|
||||||
|
render_pass.setVertexBuffer(0, model);
|
||||||
|
render_pass.setVertexBuffer(1, instances);
|
||||||
|
render_pass.drawIndexed(quad_count * 6, instance_count);
|
||||||
|
frame_stats.draw_calls += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 | Uint8Array<ArrayBuffer>,
|
||||||
|
first: number,
|
||||||
|
count: number,
|
||||||
|
) {
|
||||||
|
device.queue.writeBuffer(buffer, byte_offset, data, first, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
// the camera's view and projection, for frustum culling. only meaningful in 3d mode
|
// the camera's view and projection, for frustum culling. only meaningful in 3d mode
|
||||||
@@ -451,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),
|
||||||
@@ -469,17 +710,30 @@ 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 = self.innerWidth;
|
export function resize_canvas(view_width = view_size.width, view_height = view_size.height) {
|
||||||
const 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
|
||||||
|
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;
|
||||||
canvas.style.width = canvas.width + "px";
|
|
||||||
canvas.style.height = canvas.height + "px";
|
|
||||||
// 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.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
|
||||||
|
// undefined. it changes at the start of the next frame, since resizing the canvas takes away the texture being drawn to
|
||||||
|
export function set_canvas_size(size: { width: number; height: number } | undefined) {
|
||||||
|
fixed_canvas_size = size;
|
||||||
|
resize_pending = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function get_current_texture(): GPUTexture | null {
|
export function get_current_texture(): GPUTexture | null {
|
||||||
@@ -490,6 +744,14 @@ export function set_current_texture(texture: GPUTexture) {
|
|||||||
current_texture = texture;
|
current_texture = texture;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// draws with texture from now on, flushing what was batched with another one first
|
||||||
|
export function use_texture(texture: GPUTexture) {
|
||||||
|
if (current_texture !== texture) {
|
||||||
|
flush_batch();
|
||||||
|
current_texture = texture;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function create_texture(width: number, height: number): GPUTexture {
|
export function create_texture(width: number, height: number): GPUTexture {
|
||||||
return device.createTexture({
|
return device.createTexture({
|
||||||
size: [width, height],
|
size: [width, height],
|
||||||
@@ -600,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;
|
||||||
@@ -610,6 +872,7 @@ function draw(buffer: GPUBuffer, offset: number, vertex_count: number) {
|
|||||||
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
|
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
|
||||||
render_pass.setVertexBuffer(0, buffer, offset);
|
render_pass.setVertexBuffer(0, buffer, offset);
|
||||||
render_pass.draw(vertex_count);
|
render_pass.draw(vertex_count);
|
||||||
|
frame_stats.draw_calls += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensure_pass(): GPURenderPassEncoder {
|
function ensure_pass(): GPURenderPassEncoder {
|
||||||
@@ -617,10 +880,11 @@ function ensure_pass(): GPURenderPassEncoder {
|
|||||||
return pass;
|
return pass;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const multisampled = sample_count > 1;
|
||||||
pass = encoder!.beginRenderPass({
|
pass = encoder!.beginRenderPass({
|
||||||
colorAttachments: [{
|
colorAttachments: [{
|
||||||
view: msaa_texture!.createView(),
|
view: multisampled ? msaa_texture!.createView() : frame_view,
|
||||||
resolveTarget: frame_view,
|
resolveTarget: multisampled ? frame_view : undefined,
|
||||||
clearValue: clear_color,
|
clearValue: clear_color,
|
||||||
loadOp: pending_color_clear ? "clear" : "load",
|
loadOp: pending_color_clear ? "clear" : "load",
|
||||||
storeOp: "store",
|
storeOp: "store",
|
||||||
@@ -631,7 +895,9 @@ function ensure_pass(): GPURenderPassEncoder {
|
|||||||
depthLoadOp: pending_depth_clear ? "clear" : "load",
|
depthLoadOp: pending_depth_clear ? "clear" : "load",
|
||||||
depthStoreOp: "store",
|
depthStoreOp: "store",
|
||||||
},
|
},
|
||||||
|
timestampWrites: gpu_timer?.pass_writes(gpu_label),
|
||||||
});
|
});
|
||||||
|
frame_stats.passes += 1;
|
||||||
pending_color_clear = false;
|
pending_color_clear = false;
|
||||||
pending_depth_clear = false;
|
pending_depth_clear = false;
|
||||||
current_pipeline = undefined;
|
current_pipeline = undefined;
|
||||||
@@ -642,8 +908,8 @@ function ensure_pass(): GPURenderPassEncoder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function apply_scissor(render_pass: GPURenderPassEncoder) {
|
function apply_scissor(render_pass: GPURenderPassEncoder) {
|
||||||
const target_width = msaa_texture!.width;
|
const target_width = depth_texture!.width;
|
||||||
const target_height = msaa_texture!.height;
|
const target_height = depth_texture!.height;
|
||||||
|
|
||||||
if (!scissor) {
|
if (!scissor) {
|
||||||
render_pass.setScissorRect(0, 0, target_width, target_height);
|
render_pass.setScissorRect(0, 0, target_width, target_height);
|
||||||
@@ -663,23 +929,29 @@ function ensure_render_targets() {
|
|||||||
const width = canvas.width;
|
const width = canvas.width;
|
||||||
const height = canvas.height;
|
const height = canvas.height;
|
||||||
|
|
||||||
if (msaa_texture && msaa_texture.width === width && msaa_texture.height === height) {
|
if (
|
||||||
|
depth_texture && depth_texture.width === width && depth_texture.height === height &&
|
||||||
|
depth_texture.sampleCount === sample_count
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
msaa_texture?.destroy();
|
msaa_texture?.destroy();
|
||||||
depth_texture?.destroy();
|
depth_texture?.destroy();
|
||||||
|
|
||||||
msaa_texture = device.createTexture({
|
// without msaa the frame is drawn straight into the canvas
|
||||||
size: [width, height],
|
msaa_texture = sample_count > 1
|
||||||
format: canvas_format,
|
? device.createTexture({
|
||||||
sampleCount: SAMPLE_COUNT,
|
size: [width, height],
|
||||||
usage: GPUTextureUsage.RENDER_ATTACHMENT,
|
format: canvas_format,
|
||||||
});
|
sampleCount: sample_count,
|
||||||
|
usage: GPUTextureUsage.RENDER_ATTACHMENT,
|
||||||
|
})
|
||||||
|
: undefined;
|
||||||
depth_texture = device.createTexture({
|
depth_texture = device.createTexture({
|
||||||
size: [width, height],
|
size: [width, height],
|
||||||
format: DEPTH_FORMAT,
|
format: DEPTH_FORMAT,
|
||||||
sampleCount: SAMPLE_COUNT,
|
sampleCount: sample_count,
|
||||||
usage: GPUTextureUsage.RENDER_ATTACHMENT,
|
usage: GPUTextureUsage.RENDER_ATTACHMENT,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -693,8 +965,9 @@ function write_mvp() {
|
|||||||
uniform_slot = 0;
|
uniform_slot = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
const matrix = mode3d ? mvp : ortho;
|
uniform_data.set(mode3d ? mvp : ortho);
|
||||||
device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, matrix as Float32Array);
|
uniform_data[16] = render_time;
|
||||||
|
device.queue.writeBuffer(uniform_buffer, uniform_slot * UNIFORM_SLOT_SIZE, uniform_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
function update_camera() {
|
function update_camera() {
|
||||||
@@ -724,14 +997,15 @@ function update_camera() {
|
|||||||
function create_pipelines() {
|
function create_pipelines() {
|
||||||
const module = device.createShaderModule({ code: shader_src });
|
const module = device.createShaderModule({ code: shader_src });
|
||||||
|
|
||||||
uniform_layout = device.createBindGroupLayout({
|
// made once, the bind groups made with them outlive pipelines made again for a new sample count
|
||||||
|
uniform_layout ??= device.createBindGroupLayout({
|
||||||
entries: [{
|
entries: [{
|
||||||
binding: 0,
|
binding: 0,
|
||||||
visibility: GPUShaderStage.VERTEX,
|
visibility: GPUShaderStage.VERTEX,
|
||||||
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: 64 },
|
buffer: { type: "uniform", hasDynamicOffset: true, minBindingSize: UNIFORM_FLOATS * 4 },
|
||||||
}],
|
}],
|
||||||
});
|
});
|
||||||
texture_layout = device.createBindGroupLayout({
|
texture_layout ??= device.createBindGroupLayout({
|
||||||
entries: [
|
entries: [
|
||||||
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: {} },
|
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: {} },
|
||||||
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
|
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
|
||||||
@@ -762,7 +1036,7 @@ function create_pipelines() {
|
|||||||
},
|
},
|
||||||
}],
|
}],
|
||||||
};
|
};
|
||||||
const multisample: GPUMultisampleState = { count: SAMPLE_COUNT };
|
const multisample: GPUMultisampleState = { count: sample_count };
|
||||||
|
|
||||||
pipeline_2d = device.createRenderPipeline({
|
pipeline_2d = device.createRenderPipeline({
|
||||||
layout,
|
layout,
|
||||||
@@ -791,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({
|
||||||
@@ -811,25 +1093,67 @@ function create_pipelines() {
|
|||||||
};
|
};
|
||||||
// like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth
|
// like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth
|
||||||
// since it's drawn sorted back to front
|
// since it's drawn sorted back to front
|
||||||
const terrain_pipeline = (entryPoint: string, blend?: GPUBlendState) =>
|
const terrain_pipeline = (
|
||||||
device.createRenderPipeline({
|
entryPoint: string,
|
||||||
layout: terrain_layout,
|
blend?: GPUBlendState,
|
||||||
vertex: terrain_vertex,
|
alphaToCoverageEnabled = false,
|
||||||
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
|
vertex = terrain_vertex,
|
||||||
multisample,
|
) => device.createRenderPipeline({
|
||||||
primitive: primitive_3d,
|
layout: terrain_layout,
|
||||||
depthStencil: depth_3d,
|
vertex,
|
||||||
});
|
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
|
||||||
|
multisample: { ...multisample, alphaToCoverageEnabled },
|
||||||
|
primitive: primitive_3d,
|
||||||
|
depthStencil: depth_3d,
|
||||||
|
});
|
||||||
|
const blend: GPUBlendState = {
|
||||||
|
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||||
|
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
||||||
|
};
|
||||||
terrain_pipelines = {
|
terrain_pipelines = {
|
||||||
solid: terrain_pipeline("fs_solid"),
|
solid: terrain_pipeline("fs_solid"),
|
||||||
cutout: terrain_pipeline("fs_cutout"),
|
// alpha to coverage needs msaa
|
||||||
translucent: terrain_pipeline("fs_translucent", {
|
cutout: sample_count > 1
|
||||||
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
? terrain_pipeline("fs_cutout", undefined, true)
|
||||||
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
|
: terrain_pipeline("fs_cutout_discard"),
|
||||||
}),
|
translucent: terrain_pipeline("fs_translucent", blend),
|
||||||
|
};
|
||||||
|
// instances are cut out like cutout terrain, or blended like translucent terrain, like a fluid's box
|
||||||
|
const instance_vertex: GPUVertexState = {
|
||||||
|
module: terrain_module,
|
||||||
|
entryPoint: "vs_instance",
|
||||||
|
buffers: INSTANCED_BUFFERS,
|
||||||
|
};
|
||||||
|
instance_pipelines = {
|
||||||
|
cutout: sample_count > 1
|
||||||
|
? terrain_pipeline("fs_cutout", undefined, true, instance_vertex)
|
||||||
|
: terrain_pipeline("fs_cutout_discard", undefined, false, instance_vertex),
|
||||||
|
translucent: terrain_pipeline("fs_translucent", blend, false, instance_vertex),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// how vs_instance reads a model's vertices and its instances
|
||||||
|
export const INSTANCED_BUFFERS: GPUVertexBufferLayout[] = [
|
||||||
|
{
|
||||||
|
arrayStride: MODEL_VERTEX_BYTES,
|
||||||
|
attributes: [
|
||||||
|
{ shaderLocation: 0, offset: 0, format: "float32x3" },
|
||||||
|
{ shaderLocation: 1, offset: 12, format: "unorm16x2" },
|
||||||
|
{ shaderLocation: 2, offset: 16, format: "unorm8x4" },
|
||||||
|
{ shaderLocation: 3, offset: 20, format: "snorm8x4" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
arrayStride: INSTANCE_FLOATS * 4,
|
||||||
|
stepMode: "instance",
|
||||||
|
attributes: [4, 5, 6, 7, 8, 9].map((location, i) => ({
|
||||||
|
shaderLocation: location,
|
||||||
|
offset: i * 16,
|
||||||
|
format: "float32x4" as const,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
function create_stream_buffer(size: number) {
|
function create_stream_buffer(size: number) {
|
||||||
return device.createBuffer({ size, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
return device.createBuffer({ size, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
|
||||||
}
|
}
|
||||||
@@ -841,7 +1165,7 @@ function create_uniform_buffer(slots: number) {
|
|||||||
});
|
});
|
||||||
uniform_bind_group = device.createBindGroup({
|
uniform_bind_group = device.createBindGroup({
|
||||||
layout: uniform_layout,
|
layout: uniform_layout,
|
||||||
entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: 64 } }],
|
entries: [{ binding: 0, resource: { buffer: uniform_buffer, size: UNIFORM_FLOATS * 4 } }],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// how long the gpu spends on each render pass, with timestamp queries, for the f3 performance window. passes are
|
||||||
|
// labeled with the section they started in (see gpu_section in core.ts), and the results come back a few frames
|
||||||
|
// later, when the gpu is done. chrome rounds timestamps to 0.1 ms unless it's started with
|
||||||
|
// --enable-webgpu-developer-features
|
||||||
|
|
||||||
|
// passes timed per frame, the rest of a frame's aren't
|
||||||
|
const MAX_PASSES = 32;
|
||||||
|
// frames whose results can be on their way back at once. when they all are, the next frame isn't timed
|
||||||
|
const READBACK_BUFFERS = 3;
|
||||||
|
const WINDOW_MS = 1000;
|
||||||
|
|
||||||
|
export class GpuTimer {
|
||||||
|
readonly supported: boolean;
|
||||||
|
// ms per frame by label, averaged over the last window
|
||||||
|
results = new Map<string, number>();
|
||||||
|
total = 0;
|
||||||
|
// every timed frame's total, while something reads them, like the benchmark. a frame goes to the array that was
|
||||||
|
// here when it was submitted, however late its time comes back
|
||||||
|
samples: number[] | undefined;
|
||||||
|
|
||||||
|
#device: GPUDevice;
|
||||||
|
#query_set: GPUQuerySet | undefined;
|
||||||
|
#resolve_buffer: GPUBuffer | undefined;
|
||||||
|
#free: GPUBuffer[] = [];
|
||||||
|
#created = 0;
|
||||||
|
// this frame's
|
||||||
|
#labels: string[] = [];
|
||||||
|
#readback: GPUBuffer | undefined;
|
||||||
|
|
||||||
|
#sums = new Map<string, number>();
|
||||||
|
#frames = 0;
|
||||||
|
#window_start = performance.now();
|
||||||
|
|
||||||
|
constructor(device: GPUDevice) {
|
||||||
|
this.#device = device;
|
||||||
|
this.supported = device.features.has("timestamp-query");
|
||||||
|
if (this.supported) {
|
||||||
|
this.#query_set = device.createQuerySet({ type: "timestamp", count: MAX_PASSES * 2 });
|
||||||
|
this.#resolve_buffer = device.createBuffer({
|
||||||
|
size: MAX_PASSES * 16,
|
||||||
|
usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
begin_frame() {
|
||||||
|
this.#labels = [];
|
||||||
|
this.#readback = undefined;
|
||||||
|
if (!this.supported) return;
|
||||||
|
this.#readback = this.#free.pop();
|
||||||
|
if (!this.#readback && this.#created < READBACK_BUFFERS) {
|
||||||
|
this.#created += 1;
|
||||||
|
this.#readback = this.#device.createBuffer({
|
||||||
|
size: MAX_PASSES * 16,
|
||||||
|
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// for a pass about to begin
|
||||||
|
pass_writes(label: string): GPURenderPassTimestampWrites | undefined {
|
||||||
|
if (!this.#readback || this.#labels.length >= MAX_PASSES) return undefined;
|
||||||
|
const i = this.#labels.length;
|
||||||
|
this.#labels.push(label);
|
||||||
|
return { querySet: this.#query_set!, beginningOfPassWriteIndex: i * 2, endOfPassWriteIndex: i * 2 + 1 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// after the last pass ends, before the encoder finishes
|
||||||
|
resolve(encoder: GPUCommandEncoder) {
|
||||||
|
if (!this.#readback || this.#labels.length === 0) return;
|
||||||
|
const count = this.#labels.length * 2;
|
||||||
|
encoder.resolveQuerySet(this.#query_set!, 0, count, this.#resolve_buffer!, 0);
|
||||||
|
encoder.copyBufferToBuffer(this.#resolve_buffer!, 0, this.#readback, 0, count * 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
// after the submit
|
||||||
|
read() {
|
||||||
|
const buffer = this.#readback;
|
||||||
|
if (!buffer) return;
|
||||||
|
const labels = this.#labels;
|
||||||
|
if (labels.length === 0) {
|
||||||
|
this.#free.push(buffer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const samples = this.samples;
|
||||||
|
buffer.mapAsync(GPUMapMode.READ, 0, labels.length * 16).then(() => {
|
||||||
|
const times = new BigUint64Array(buffer.getMappedRange(0, labels.length * 16));
|
||||||
|
const frame = new Map<string, number>();
|
||||||
|
let total = 0;
|
||||||
|
labels.forEach((label, i) => {
|
||||||
|
const ms = Math.max(0, Number(times[i * 2 + 1] - times[i * 2])) / 1e6;
|
||||||
|
frame.set(label, (frame.get(label) ?? 0) + ms);
|
||||||
|
total += ms;
|
||||||
|
});
|
||||||
|
buffer.unmap();
|
||||||
|
this.#free.push(buffer);
|
||||||
|
this.#add_frame(frame);
|
||||||
|
samples?.push(total);
|
||||||
|
}).catch(() => {
|
||||||
|
// the device was lost, nothing to time anymore
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#add_frame(frame: Map<string, number>) {
|
||||||
|
for (const [label, ms] of frame) this.#sums.set(label, (this.#sums.get(label) ?? 0) + ms);
|
||||||
|
this.#frames += 1;
|
||||||
|
const now = performance.now();
|
||||||
|
if (now - this.#window_start < WINDOW_MS) return;
|
||||||
|
this.results = new Map([...this.#sums].map(([label, ms]) => [label, ms / this.#frames]));
|
||||||
|
this.total = [...this.results.values()].reduce((sum, ms) => sum + ms, 0);
|
||||||
|
this.#sums.clear();
|
||||||
|
this.#frames = 0;
|
||||||
|
this.#window_start = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
export * from "./core.ts";
|
export * from "./core.ts";
|
||||||
export * from "./shapes.ts";
|
export * from "./shapes.ts";
|
||||||
export * from "./textures.ts";
|
export * from "./textures.ts";
|
||||||
export * from "./text.ts";
|
export * from "./text.ts";
|
||||||
export * from "./models.ts";
|
|
||||||
export * from "./types.ts";
|
export * from "./types.ts";
|
||||||
|
|||||||
@@ -1,259 +0,0 @@
|
|||||||
import { push_vertex } from "./core.ts";
|
|
||||||
import type { Texture } from "./types.ts";
|
|
||||||
|
|
||||||
const pad = 0.5;
|
|
||||||
|
|
||||||
export function push_front_face(
|
|
||||||
texture: Texture,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
z: number,
|
|
||||||
sx: number,
|
|
||||||
sy: number,
|
|
||||||
sw: number,
|
|
||||||
sh: number,
|
|
||||||
r = 1,
|
|
||||||
g = 1,
|
|
||||||
b = 1,
|
|
||||||
a = 1,
|
|
||||||
) {
|
|
||||||
const x2 = x + 1;
|
|
||||||
const y2 = y + 1;
|
|
||||||
const z2 = z + 1;
|
|
||||||
|
|
||||||
const u0 = (sx + pad) / texture.width;
|
|
||||||
const v0 = (sy + pad) / texture.height;
|
|
||||||
const u1 = (sx + sw - pad) / texture.width;
|
|
||||||
const v1 = (sy + sh - pad) / texture.height;
|
|
||||||
|
|
||||||
push_vertex(x, y, z2, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y, z2, u1, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z2, u1, v0, r, g, b, a);
|
|
||||||
|
|
||||||
push_vertex(x, y, z2, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z2, u1, v0, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z2, u0, v0, r, g, b, a);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function push_back_face(
|
|
||||||
texture: Texture,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
z: number,
|
|
||||||
sx: number,
|
|
||||||
sy: number,
|
|
||||||
sw: number,
|
|
||||||
sh: number,
|
|
||||||
r = 1,
|
|
||||||
g = 1,
|
|
||||||
b = 1,
|
|
||||||
a = 1,
|
|
||||||
) {
|
|
||||||
const x2 = x + 1;
|
|
||||||
const y2 = y + 1;
|
|
||||||
|
|
||||||
const u0 = (sx + pad) / texture.width;
|
|
||||||
const v0 = (sy + pad) / texture.height;
|
|
||||||
const u1 = (sx + sw - pad) / texture.width;
|
|
||||||
const v1 = (sy + sh - pad) / texture.height;
|
|
||||||
|
|
||||||
push_vertex(x2, y, z, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x, y, z, u1, v1, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z, u1, v0, r, g, b, a);
|
|
||||||
|
|
||||||
push_vertex(x2, y, z, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z, u1, v0, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z, u0, v0, r, g, b, a);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function push_left_face(
|
|
||||||
texture: Texture,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
z: number,
|
|
||||||
sx: number,
|
|
||||||
sy: number,
|
|
||||||
sw: number,
|
|
||||||
sh: number,
|
|
||||||
r = 1,
|
|
||||||
g = 1,
|
|
||||||
b = 1,
|
|
||||||
a = 1,
|
|
||||||
) {
|
|
||||||
const y2 = y + 1;
|
|
||||||
const z2 = z + 1;
|
|
||||||
|
|
||||||
const u0 = (sx + pad) / texture.width;
|
|
||||||
const v0 = (sy + pad) / texture.height;
|
|
||||||
const u1 = (sx + sw - pad) / texture.width;
|
|
||||||
const v1 = (sy + sh - pad) / texture.height;
|
|
||||||
|
|
||||||
push_vertex(x, y, z, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x, y, z2, u1, v1, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z2, u1, v0, r, g, b, a);
|
|
||||||
|
|
||||||
push_vertex(x, y, z, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z2, u1, v0, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z, u0, v0, r, g, b, a);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function push_right_face(
|
|
||||||
texture: Texture,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
z: number,
|
|
||||||
sx: number,
|
|
||||||
sy: number,
|
|
||||||
sw: number,
|
|
||||||
sh: number,
|
|
||||||
r = 1,
|
|
||||||
g = 1,
|
|
||||||
b = 1,
|
|
||||||
a = 1,
|
|
||||||
) {
|
|
||||||
const x2 = x + 1;
|
|
||||||
const y2 = y + 1;
|
|
||||||
const z2 = z + 1;
|
|
||||||
|
|
||||||
const u0 = (sx + pad) / texture.width;
|
|
||||||
const v0 = (sy + pad) / texture.height;
|
|
||||||
const u1 = (sx + sw - pad) / texture.width;
|
|
||||||
const v1 = (sy + sh - pad) / texture.height;
|
|
||||||
|
|
||||||
push_vertex(x2, y, z2, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y, z, u1, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z, u1, v0, r, g, b, a);
|
|
||||||
|
|
||||||
push_vertex(x2, y, z2, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z, u1, v0, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z2, u0, v0, r, g, b, a);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function push_top_face(
|
|
||||||
texture: Texture,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
z: number,
|
|
||||||
sx: number,
|
|
||||||
sy: number,
|
|
||||||
sw: number,
|
|
||||||
sh: number,
|
|
||||||
r = 1,
|
|
||||||
g = 1,
|
|
||||||
b = 1,
|
|
||||||
a = 1,
|
|
||||||
) {
|
|
||||||
const x2 = x + 1;
|
|
||||||
const z2 = z + 1;
|
|
||||||
const y2 = y + 1;
|
|
||||||
|
|
||||||
const u0 = (sx + pad) / texture.width;
|
|
||||||
const v0 = (sy + pad) / texture.height;
|
|
||||||
const u1 = (sx + sw - pad) / texture.width;
|
|
||||||
const v1 = (sy + sh - pad) / texture.height;
|
|
||||||
|
|
||||||
push_vertex(x, y2, z2, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z2, u1, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z, u1, v0, r, g, b, a);
|
|
||||||
|
|
||||||
push_vertex(x, y2, z2, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z, u1, v0, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z, u0, v0, r, g, b, a);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function push_bottom_face(
|
|
||||||
texture: Texture,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
z: number,
|
|
||||||
sx: number,
|
|
||||||
sy: number,
|
|
||||||
sw: number,
|
|
||||||
sh: number,
|
|
||||||
r = 1,
|
|
||||||
g = 1,
|
|
||||||
b = 1,
|
|
||||||
a = 1,
|
|
||||||
) {
|
|
||||||
const x2 = x + 1;
|
|
||||||
const z2 = z + 1;
|
|
||||||
|
|
||||||
const u0 = (sx + pad) / texture.width;
|
|
||||||
const v0 = (sy + pad) / texture.height;
|
|
||||||
const u1 = (sx + sw - pad) / texture.width;
|
|
||||||
const v1 = (sy + sh - pad) / texture.height;
|
|
||||||
|
|
||||||
push_vertex(x, y, z, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y, z, u1, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y, z2, u1, v0, r, g, b, a);
|
|
||||||
|
|
||||||
push_vertex(x, y, z, u0, v1, r, g, b, a);
|
|
||||||
push_vertex(x2, y, z2, u1, v0, r, g, b, a);
|
|
||||||
push_vertex(x, y, z2, u0, v0, r, g, b, a);
|
|
||||||
}
|
|
||||||
|
|
||||||
// solid colored box, draw it with white_tex as the current texture
|
|
||||||
export function push_box(
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
z: number,
|
|
||||||
width: number,
|
|
||||||
height: number,
|
|
||||||
depth: number,
|
|
||||||
r = 1,
|
|
||||||
g = 1,
|
|
||||||
b = 1,
|
|
||||||
a = 1,
|
|
||||||
) {
|
|
||||||
const x2 = x + width;
|
|
||||||
const y2 = y + height;
|
|
||||||
const z2 = z + depth;
|
|
||||||
|
|
||||||
// front
|
|
||||||
push_vertex(x, y, z2, 0, 1, r, g, b, a);
|
|
||||||
push_vertex(x2, y, z2, 1, 1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z2, 1, 0, r, g, b, a);
|
|
||||||
push_vertex(x, y, z2, 0, 1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z2, 1, 0, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z2, 0, 0, r, g, b, a);
|
|
||||||
|
|
||||||
// back
|
|
||||||
push_vertex(x2, y, z, 0, 1, r * 0.8, g * 0.8, b * 0.8, a);
|
|
||||||
push_vertex(x, y, z, 1, 1, r * 0.8, g * 0.8, b * 0.8, a);
|
|
||||||
push_vertex(x, y2, z, 1, 0, r * 0.8, g * 0.8, b * 0.8, a);
|
|
||||||
push_vertex(x2, y, z, 0, 1, r * 0.8, g * 0.8, b * 0.8, a);
|
|
||||||
push_vertex(x, y2, z, 1, 0, r * 0.8, g * 0.8, b * 0.8, a);
|
|
||||||
push_vertex(x2, y2, z, 0, 0, r * 0.8, g * 0.8, b * 0.8, a);
|
|
||||||
|
|
||||||
// left
|
|
||||||
push_vertex(x, y, z, 0, 1, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x, y, z2, 1, 1, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x, y2, z2, 1, 0, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x, y, z, 0, 1, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x, y2, z2, 1, 0, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x, y2, z, 0, 0, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
|
|
||||||
// right
|
|
||||||
push_vertex(x2, y, z2, 0, 1, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x2, y, z, 1, 1, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x2, y2, z, 1, 0, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x2, y, z2, 0, 1, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x2, y2, z, 1, 0, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
push_vertex(x2, y2, z2, 0, 0, r * 0.9, g * 0.9, b * 0.9, a);
|
|
||||||
|
|
||||||
// top
|
|
||||||
push_vertex(x, y2, z2, 0, 1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z2, 1, 1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z, 1, 0, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z2, 0, 1, r, g, b, a);
|
|
||||||
push_vertex(x2, y2, z, 1, 0, r, g, b, a);
|
|
||||||
push_vertex(x, y2, z, 0, 0, r, g, b, a);
|
|
||||||
|
|
||||||
// bottom
|
|
||||||
push_vertex(x, y, z, 0, 1, r * 0.6, g * 0.6, b * 0.6, a);
|
|
||||||
push_vertex(x2, y, z, 1, 1, r * 0.6, g * 0.6, b * 0.6, a);
|
|
||||||
push_vertex(x2, y, z2, 1, 0, r * 0.6, g * 0.6, b * 0.6, a);
|
|
||||||
push_vertex(x, y, z, 0, 1, r * 0.6, g * 0.6, b * 0.6, a);
|
|
||||||
push_vertex(x2, y, z2, 1, 0, r * 0.6, g * 0.6, b * 0.6, a);
|
|
||||||
push_vertex(x, y, z2, 0, 0, r * 0.6, g * 0.6, b * 0.6, a);
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
import { flush_batch, get_current_texture, push_quad, set_current_texture, white_tex } from "./core.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import { push_quad, push_vertex, use_texture, white_tex } from "./core.ts";
|
||||||
|
|
||||||
export function draw_rect(
|
export function draw_rect(
|
||||||
x: number,
|
x: number,
|
||||||
@@ -7,10 +10,7 @@ export function draw_rect(
|
|||||||
h: number,
|
h: number,
|
||||||
color: [number, number, number, number] = [1, 1, 1, 1],
|
color: [number, number, number, number] = [1, 1, 1, 1],
|
||||||
) {
|
) {
|
||||||
if (get_current_texture() !== white_tex) {
|
use_texture(white_tex!);
|
||||||
flush_batch();
|
|
||||||
set_current_texture(white_tex!);
|
|
||||||
}
|
|
||||||
|
|
||||||
push_quad(x, y, w, h, 0, 0, 1, 1, color[0], color[1], color[2], color[3]);
|
push_quad(x, y, w, h, 0, 0, 1, 1, color[0], color[1], color[2], color[3]);
|
||||||
}
|
}
|
||||||
@@ -32,3 +32,60 @@ export function draw_rect_stroke(
|
|||||||
// right
|
// right
|
||||||
draw_rect(x + w - thickness, y, thickness, h, color);
|
draw_rect(x + w - thickness, y, thickness, h, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// a plane in the world to lay 2d drawing on: origin is its top left, x goes along right and y along -up, like the
|
||||||
|
// screen. for text and rects facing a direction, like nameplates facing the camera
|
||||||
|
export type Plane3d = {
|
||||||
|
origin: [number, number, number];
|
||||||
|
right: [number, number, number];
|
||||||
|
up: [number, number, number];
|
||||||
|
};
|
||||||
|
|
||||||
|
// a quad at x, y on the plane, in its units. wound counter clockwise seen from where right and up point the usual way,
|
||||||
|
// so it's culled from behind
|
||||||
|
export function push_plane_quad(
|
||||||
|
plane: Plane3d,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
w: number,
|
||||||
|
h: number,
|
||||||
|
u0: number,
|
||||||
|
v0: number,
|
||||||
|
u1: number,
|
||||||
|
v1: number,
|
||||||
|
color: readonly number[],
|
||||||
|
) {
|
||||||
|
const { origin: o, right: rt, up } = plane;
|
||||||
|
const corner = (cx: number, cy: number, u: number, v: number) =>
|
||||||
|
push_vertex(
|
||||||
|
o[0] + rt[0] * cx - up[0] * cy,
|
||||||
|
o[1] + rt[1] * cx - up[1] * cy,
|
||||||
|
o[2] + rt[2] * cx - up[2] * cy,
|
||||||
|
u,
|
||||||
|
v,
|
||||||
|
color[0],
|
||||||
|
color[1],
|
||||||
|
color[2],
|
||||||
|
color[3],
|
||||||
|
);
|
||||||
|
const x2 = x + w;
|
||||||
|
const y2 = y + h;
|
||||||
|
corner(x, y, u0, v0);
|
||||||
|
corner(x, y2, u0, v1);
|
||||||
|
corner(x2, y2, u1, v1);
|
||||||
|
corner(x, y, u0, v0);
|
||||||
|
corner(x2, y2, u1, v1);
|
||||||
|
corner(x2, y, u1, v0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function draw_rect_3d(
|
||||||
|
plane: Plane3d,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
w: number,
|
||||||
|
h: number,
|
||||||
|
color: readonly number[] = [1, 1, 1, 1],
|
||||||
|
) {
|
||||||
|
use_texture(white_tex!);
|
||||||
|
push_plane_quad(plane, x, y, w, h, 0, 0, 1, 1, color);
|
||||||
|
}
|
||||||
|
|||||||
+51
-7
@@ -1,14 +1,18 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
import { AssetManager } from "../assets.ts";
|
import { AssetManager } from "../assets.ts";
|
||||||
import { flush_batch, get_current_texture, push_quad, set_current_texture } from "./core.ts";
|
import { push_quad, use_texture } from "./core.ts";
|
||||||
|
import { type Plane3d, push_plane_quad } from "./shapes.ts";
|
||||||
import { FntChar, FntFont, Texture } from "./types.ts";
|
import { FntChar, FntFont, Texture } from "./types.ts";
|
||||||
|
|
||||||
let font_texture: Texture;
|
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
|
||||||
@@ -75,10 +79,7 @@ export function draw_text(str: string, x: number, y: number, scale: number = 1,
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (get_current_texture() !== font_texture.tex) {
|
use_texture(font_texture.tex);
|
||||||
flush_batch();
|
|
||||||
set_current_texture(font_texture.tex);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const ch of str) {
|
for (const ch of str) {
|
||||||
const glyph = font_fnt.chars[ch.charCodeAt(0)];
|
const glyph = font_fnt.chars[ch.charCodeAt(0)];
|
||||||
@@ -102,6 +103,49 @@ export function draw_text(str: string, x: number, y: number, scale: number = 1,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// text on a plane in the world (see Plane3d), x and y in the plane's units like draw_text's are in pixels. scale is
|
||||||
|
// how big a font pixel is in them
|
||||||
|
export function draw_text_3d(
|
||||||
|
plane: Plane3d,
|
||||||
|
str: string,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
scale: number,
|
||||||
|
color: readonly number[] = [1, 1, 1, 1],
|
||||||
|
) {
|
||||||
|
if (!font_texture) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
use_texture(font_texture.tex);
|
||||||
|
|
||||||
|
for (const ch of str) {
|
||||||
|
const glyph = font_fnt.chars[ch.charCodeAt(0)];
|
||||||
|
if (!glyph) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
push_plane_quad(
|
||||||
|
plane,
|
||||||
|
x + glyph.xoffset * scale,
|
||||||
|
y + glyph.yoffset * scale,
|
||||||
|
glyph.width * scale,
|
||||||
|
glyph.height * scale,
|
||||||
|
glyph.x / font_texture.width,
|
||||||
|
glyph.y / font_texture.height,
|
||||||
|
(glyph.x + glyph.width) / font_texture.width,
|
||||||
|
(glyph.y + glyph.height) / font_texture.height,
|
||||||
|
color,
|
||||||
|
);
|
||||||
|
|
||||||
|
x += glyph.xadvance * scale;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function font_line_height() {
|
||||||
|
return font_fnt?.line_height ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
export function measure_text(str: string, scale: number = 1) {
|
export function measure_text(str: string, scale: number = 1) {
|
||||||
let x = 0;
|
let x = 0;
|
||||||
for (const ch of str) {
|
for (const ch of str) {
|
||||||
|
|||||||
+30
-60
@@ -1,17 +1,13 @@
|
|||||||
import {
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
create_texture,
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
device,
|
|
||||||
flush_batch,
|
|
||||||
get_current_texture,
|
|
||||||
push_quad,
|
|
||||||
push_quad_vertices,
|
|
||||||
set_current_texture,
|
|
||||||
} from "./core.ts";
|
|
||||||
import { Texture } from "./types.ts";
|
|
||||||
|
|
||||||
export function load_texture(image: HTMLImageElement | ImageBitmap): Texture {
|
import { create_texture, device, push_quad, push_quad_vertices, use_texture } from "./core.ts";
|
||||||
|
import { Texture } from "./types.ts";
|
||||||
|
import type { Pixels } from "../png.ts";
|
||||||
|
|
||||||
|
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,
|
||||||
@@ -29,21 +25,7 @@ export function draw_texture(
|
|||||||
flip_x = false,
|
flip_x = false,
|
||||||
flip_y = false,
|
flip_y = false,
|
||||||
) {
|
) {
|
||||||
if (get_current_texture() !== texture.tex) {
|
draw_texture_region(texture, 0, 0, texture.width, texture.height, x, y, w, h, flip_x, flip_y);
|
||||||
flush_batch();
|
|
||||||
set_current_texture(texture.tex);
|
|
||||||
}
|
|
||||||
|
|
||||||
let u0 = 0, v0 = 0, u1 = 1, v1 = 1;
|
|
||||||
|
|
||||||
if (flip_x) {
|
|
||||||
[u0, u1] = [u1, u0];
|
|
||||||
}
|
|
||||||
if (flip_y) {
|
|
||||||
[v0, v1] = [v1, v0];
|
|
||||||
}
|
|
||||||
|
|
||||||
push_quad(x, y, w, h, u0, v0, u1, v1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function draw_texture_region(
|
export function draw_texture_region(
|
||||||
@@ -63,23 +45,8 @@ export function draw_texture_region(
|
|||||||
b = 1,
|
b = 1,
|
||||||
a = 1,
|
a = 1,
|
||||||
) {
|
) {
|
||||||
if (get_current_texture() !== texture.tex) {
|
use_texture(texture.tex);
|
||||||
flush_batch();
|
const [u0, v0, u1, v1] = region_uvs(texture, sx, sy, sw, sh, flip_x, flip_y);
|
||||||
set_current_texture(texture.tex);
|
|
||||||
}
|
|
||||||
|
|
||||||
let u0 = sx / texture.width;
|
|
||||||
let v0 = sy / texture.height;
|
|
||||||
let u1 = (sx + sw) / texture.width;
|
|
||||||
let v1 = (sy + sh) / texture.height;
|
|
||||||
|
|
||||||
if (flip_x) {
|
|
||||||
[u0, u1] = [u1, u0];
|
|
||||||
}
|
|
||||||
if (flip_y) {
|
|
||||||
[v0, v1] = [v1, v0];
|
|
||||||
}
|
|
||||||
|
|
||||||
push_quad(dx, dy, dw, dh, u0, v0, u1, v1, r, g, b, a);
|
push_quad(dx, dy, dw, dh, u0, v0, u1, v1, r, g, b, a);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,22 +69,8 @@ export function draw_texture_region_skewed(
|
|||||||
flip_x = false,
|
flip_x = false,
|
||||||
flip_y = false,
|
flip_y = false,
|
||||||
) {
|
) {
|
||||||
if (get_current_texture() !== texture.tex) {
|
use_texture(texture.tex);
|
||||||
flush_batch();
|
const [u0, v0, u1, v1] = region_uvs(texture, sx, sy, sw, sh, flip_x, flip_y);
|
||||||
set_current_texture(texture.tex);
|
|
||||||
}
|
|
||||||
|
|
||||||
let u0 = sx / texture.width;
|
|
||||||
let v0 = sy / texture.height;
|
|
||||||
let u1 = (sx + sw) / texture.width;
|
|
||||||
let v1 = (sy + sh) / texture.height;
|
|
||||||
|
|
||||||
if (flip_x) {
|
|
||||||
[u0, u1] = [u1, u0];
|
|
||||||
}
|
|
||||||
if (flip_y) {
|
|
||||||
[v0, v1] = [v1, v0];
|
|
||||||
}
|
|
||||||
|
|
||||||
const p0 = points[0];
|
const p0 = points[0];
|
||||||
const p1 = points[1];
|
const p1 = points[1];
|
||||||
@@ -143,3 +96,20 @@ export function draw_texture_region_skewed(
|
|||||||
a,
|
a,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the uvs of a region of texture given in pixels, swapped to flip it
|
||||||
|
function region_uvs(
|
||||||
|
texture: Texture,
|
||||||
|
sx: number,
|
||||||
|
sy: number,
|
||||||
|
sw: number,
|
||||||
|
sh: number,
|
||||||
|
flip_x: boolean,
|
||||||
|
flip_y: boolean,
|
||||||
|
) {
|
||||||
|
const u = [sx / texture.width, (sx + sw) / texture.width];
|
||||||
|
const v = [sy / texture.height, (sy + sh) / texture.height];
|
||||||
|
if (flip_x) u.reverse();
|
||||||
|
if (flip_y) v.reverse();
|
||||||
|
return [u[0], v[0], u[1], v[1]];
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
export interface Texture {
|
export interface Texture {
|
||||||
tex: GPUTexture;
|
tex: GPUTexture;
|
||||||
width: number;
|
width: number;
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// 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
|
||||||
|
import type { Entity } from "@/client/entity/entity.ts";
|
||||||
|
import type { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
|
import { light_color } from "@/client/renderer/mod.ts";
|
||||||
|
import type { Vec3 } from "./player_renderer.ts";
|
||||||
|
|
||||||
|
// the color for the light at a point, times tint (like the hurt flash)
|
||||||
|
export function light_tint(level: ClientLevel, x: number, y: number, z: number, tint?: Vec3, on_fire = false): Vec3 {
|
||||||
|
let packed = level.get_light(x, y, z);
|
||||||
|
if (on_fire) packed |= 15 << 4;
|
||||||
|
const [r, g, b] = light_color(packed);
|
||||||
|
return tint ? [r * tint[0], g * tint[1], b * tint[2]] : [r, g, b];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function entity_tint(entity: Entity, partial_tick: number, tint?: Vec3, on_fire = false): Vec3 {
|
||||||
|
const { x, y, z } = entity.render_position(partial_tick);
|
||||||
|
return light_tint(entity.level, x, y + entity.render_eye_height(partial_tick), z, tint, on_fire);
|
||||||
|
}
|
||||||
@@ -1,68 +1,98 @@
|
|||||||
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. there are no
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
// animations yet: the model turns to the entity's yaw, and a bone named "head" to where it looks. entities without a
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
// model are their texture facing the camera, like minecraft's fishing hook
|
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
// entities mods define (entities/<name>.json), drawn with their entity model and a texture from the atlas. the model
|
||||||
import type { Camera } from "$/client/camera.ts";
|
// turns to the entity's yaw, and its bones are posed by its type's animator from a mod (see entity_animators.ts). without
|
||||||
import type { RemoteEntity } from "$/client/entity/remote_entity.ts";
|
// one, a bone named "head" turns to where it looks, and bones named like minecraft's humanoid ones (right_arm, left_arm,
|
||||||
import { push_vertex, type Texture } from "$/client/renderer/mod.ts";
|
// right_leg, left_leg) swing as it walks, the right arm when it attacks too. entities without a model are their texture
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
// facing the camera, like minecraft's fishing hook, and objects without one are the item they hold
|
||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
import type { Camera } from "@/client/camera.ts";
|
||||||
import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts";
|
import type { RemoteEntity } from "@/client/entity/remote_entity.ts";
|
||||||
import { push_box, type Vec3 } from "./player_renderer.ts";
|
import { push_vertex, type Texture } from "@/client/renderer/mod.ts";
|
||||||
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
|
import type { SpriteRegion } from "@/common/constants.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 { bone_matrices, IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
||||||
|
import { push_model } from "./model_renderer.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;
|
||||||
// how much of each color is left while it flashes red after being hurt, like minecraft's
|
|
||||||
const HURT_TINT: Vec3 = [1, 0.6, 0.6];
|
|
||||||
|
|
||||||
// the atlas has to be the current texture
|
// the atlas has to be the current texture
|
||||||
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 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);
|
// 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 to_uv = (u: number, v: number): [number, number] => [
|
const placed = turned_with(entity, partial_tick, scale);
|
||||||
(region.x + u * region.width / model.texture_width) / atlas.width,
|
const to_world = (px: number, py: number, pz: number) => placed(px * PIXEL, py * PIXEL, pz * PIXEL);
|
||||||
(region.y + v * region.height / model.texture_height) / atlas.height,
|
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 tint = entity.hurt_time > 0 || entity.dead ? HURT_TINT : undefined;
|
return (bx: number, by: number, bz: number): Vec3 => [
|
||||||
|
x + bx * yaw_cos + bz * yaw_sin,
|
||||||
|
y + by * scale,
|
||||||
|
z - bx * yaw_sin + bz * yaw_cos,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
const bones = new Map<string, Matrix>();
|
// the head looking and the humanoid swing, for an entity without an animator
|
||||||
for (const bone of model.bones) {
|
function default_pose(entity: RemoteEntity, partial_tick: number) {
|
||||||
let matrix = bone_matrix(bone);
|
const limbs = limb_angles(entity, partial_tick);
|
||||||
|
return (bone: EntityBoneJson) => {
|
||||||
|
let matrix = IDENTITY;
|
||||||
if (bone.name === "head") {
|
if (bone.name === "head") {
|
||||||
const look = 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);
|
||||||
matrix = multiply(look, matrix);
|
|
||||||
}
|
}
|
||||||
if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix);
|
const limb = limbs[bone.name];
|
||||||
bones.set(bone.name, matrix);
|
if (limb) matrix = multiply(rotation_around(model_pivot(bone), limb, 0, 0), matrix);
|
||||||
|
return matrix;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const transform = (px: number, py: number, pz: number): Vec3 => {
|
// how far each humanoid limb turns forward (radians), like minecraft's HumanoidModel.setupAnim: arms and legs swing
|
||||||
const [mx, my, mz] = apply(matrix, px, py, pz).map((n) => n * PIXEL);
|
// opposite each other as it walks, and the right arm comes down in an attack like undergarden's rotwalker's
|
||||||
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
|
function limb_angles(entity: RemoteEntity, partial_tick: number): Record<string, number> {
|
||||||
};
|
const walk = entity.walk_animation(partial_tick);
|
||||||
for (const cube of bone.cubes) {
|
const swing = Math.cos(walk.position * 0.6662) * 1.4 * walk.speed;
|
||||||
const inflate = cube.inflate ?? 0;
|
const attack = entity.attack_animation(partial_tick);
|
||||||
const [ox, oy, oz] = cube.origin;
|
// ease out quart, so it comes down fast
|
||||||
const [w, h, d] = cube.size;
|
const eased = 1 - (1 - attack) ** 4;
|
||||||
// bedrock models are mirrored on x from the engine's, like blockbench shows them: +x is the model's right
|
return {
|
||||||
const low: Vec3 = [-(ox + w) - inflate, oy - inflate, oz - inflate];
|
right_arm: -swing + Math.sin(eased * Math.PI) * 1.2,
|
||||||
const high: Vec3 = [-ox + inflate, oy + h + inflate, oz + d + inflate];
|
left_arm: swing,
|
||||||
push_box(cube.size, low, high, cube.uv, to_uv, transform, tint);
|
right_leg: swing,
|
||||||
}
|
left_leg: -swing,
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// the whole texture, 16 pixels to a block, facing the camera around the middle of the entity's box
|
// the whole texture, 16 pixels to a block, facing the camera around the middle of the entity's box
|
||||||
@@ -71,18 +101,19 @@ 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,
|
||||||
) {
|
) {
|
||||||
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];
|
||||||
const up: Vec3 = [yaw_sin * pitch_sin * half_height, pitch_cos * half_height, yaw_cos * pitch_sin * half_height];
|
const up: Vec3 = [yaw_sin * pitch_sin * half_height, pitch_cos * half_height, yaw_cos * pitch_sin * half_height];
|
||||||
const [r, g, b] = entity.hurt_time > 0 || entity.dead ? HURT_TINT : [1, 1, 1];
|
|
||||||
|
|
||||||
const u0 = region.x / atlas.width;
|
const u0 = region.x / atlas.width;
|
||||||
const v0 = region.y / atlas.height;
|
const v0 = region.y / atlas.height;
|
||||||
@@ -105,57 +136,3 @@ function render_sprite(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's
|
|
||||||
type Matrix = number[];
|
|
||||||
|
|
||||||
const IDENTITY: Matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
|
||||||
|
|
||||||
function model_pivot(bone: EntityBoneJson): Vec3 {
|
|
||||||
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
|
|
||||||
function bone_matrix(bone: EntityBoneJson): Matrix {
|
|
||||||
if (!bone.rotation) return IDENTITY;
|
|
||||||
const [rx, ry, rz] = bone.rotation.map((degrees) => degrees * Math.PI / 180);
|
|
||||||
return rotation_around(model_pivot(bone), -rx, -ry, rz);
|
|
||||||
}
|
|
||||||
|
|
||||||
// turns around pivot by x, then y, then z (radians). y turns like the whole model does (see render_mod_entity) and x
|
|
||||||
// like the player's head pitch
|
|
||||||
function rotation_around(pivot: Vec3, rx: number, ry: number, rz: number): Matrix {
|
|
||||||
const [sx, cx] = [Math.sin(rx), Math.cos(rx)];
|
|
||||||
const [sy, cy] = [Math.sin(ry), Math.cos(ry)];
|
|
||||||
const [sz, cz] = [Math.sin(rz), Math.cos(rz)];
|
|
||||||
const rot_x = [1, 0, 0, 0, 0, cx, -sx, 0, 0, sx, cx, 0];
|
|
||||||
const rot_y = [cy, 0, sy, 0, 0, 1, 0, 0, -sy, 0, cy, 0];
|
|
||||||
const rot_z = [cz, -sz, 0, 0, sz, cz, 0, 0, 0, 0, 1, 0];
|
|
||||||
const [px, py, pz] = pivot;
|
|
||||||
const rotation = multiply(rot_z, multiply(rot_y, rot_x));
|
|
||||||
return multiply(
|
|
||||||
[1, 0, 0, px, 0, 1, 0, py, 0, 0, 1, pz],
|
|
||||||
multiply(rotation, [1, 0, 0, -px, 0, 1, 0, -py, 0, 0, 1, -pz]),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// a after b
|
|
||||||
function multiply(a: Matrix, b: Matrix): Matrix {
|
|
||||||
const out: Matrix = [];
|
|
||||||
for (let row = 0; row < 3; row++) {
|
|
||||||
for (let col = 0; col < 4; col++) {
|
|
||||||
let sum = col === 3 ? a[row * 4 + 3] : 0;
|
|
||||||
for (let k = 0; k < 3; k++) sum += a[row * 4 + k] * b[k * 4 + col];
|
|
||||||
out.push(sum);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function apply(m: Matrix, x: number, y: number, z: number): Vec3 {
|
|
||||||
return [
|
|
||||||
m[0] * x + m[1] * y + m[2] * z + m[3],
|
|
||||||
m[4] * x + m[5] * y + m[6] * z + m[7],
|
|
||||||
m[8] * x + m[9] * y + m[10] * z + m[11],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// what the camera can see: the six planes around it, taken from its view projection matrix (gl-matrix's column major
|
// what the camera can see: the six planes around it, taken from its view projection matrix (gl-matrix's column major
|
||||||
// order, with webgpu's 0 to 1 depth). a box is out of view when it's entirely behind one of them
|
// order, with webgpu's 0 to 1 depth). a box is out of view when it's entirely behind one of them
|
||||||
export class Frustum {
|
export class Frustum {
|
||||||
|
|||||||
@@ -1,16 +1,33 @@
|
|||||||
import type { Client } from "$/client/client.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { begin_mode_3d, clear_background, end_mode_3d, update_lightmap } from "$/client/renderer/mod.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { daylight } from "$/common/time.ts";
|
|
||||||
import { Hud } from "$/client/gui/hud.ts";
|
import type { Client } from "@/client/client.ts";
|
||||||
import { DebugOverlay } from "$/client/gui/debug_overlay.ts";
|
import type { Camera } from "@/client/camera.ts";
|
||||||
|
import type { ClientLevel } from "@/client/level/client_level.ts";
|
||||||
|
import {
|
||||||
|
begin_mode_3d,
|
||||||
|
canvas,
|
||||||
|
clear_background,
|
||||||
|
draw_rect,
|
||||||
|
end_mode_3d,
|
||||||
|
set_render_time,
|
||||||
|
update_lightmap,
|
||||||
|
} from "@/client/renderer/mod.ts";
|
||||||
|
import { daylight } from "@/common/time.ts";
|
||||||
|
import { Hud } from "@/client/gui/hud.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 { 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];
|
||||||
const NIGHT_SKY = [0.02, 0.03, 0.08];
|
const NIGHT_SKY = [0.02, 0.03, 0.08];
|
||||||
// minecraft's darkest sky: moonlight still lights things a little
|
// minecraft's darkest sky: moonlight still lights things a little
|
||||||
const NIGHT_SKY_LIGHT = 0.2;
|
const NIGHT_SKY_LIGHT = 0.2;
|
||||||
|
// how much of the screen is the water's color with the camera under water
|
||||||
|
const UNDERWATER_ALPHA = 0.4;
|
||||||
|
|
||||||
// draws a frame, like minecraft's GameRenderer: the level from the camera, then the hud and screens on top
|
// draws a frame, like minecraft's GameRenderer: the level from the camera, then the hud and screens on top
|
||||||
export class GameRenderer {
|
export class GameRenderer {
|
||||||
@@ -22,8 +39,8 @@ export class GameRenderer {
|
|||||||
#lightmap_daylight = -1;
|
#lightmap_daylight = -1;
|
||||||
|
|
||||||
// sky color and sky light for the time of day
|
// sky color and sky light for the time of day
|
||||||
#setup_sky(client: Client, partial_tick: number) {
|
#setup_sky(level: ClientLevel, partial_tick: number) {
|
||||||
const light = daylight(client.level.time + partial_tick);
|
const light = daylight(level.time + partial_tick);
|
||||||
const [r, g, b] = DAY_SKY.map((day, i) => NIGHT_SKY[i] + (day - NIGHT_SKY[i]) * light);
|
const [r, g, b] = DAY_SKY.map((day, i) => NIGHT_SKY[i] + (day - NIGHT_SKY[i]) * light);
|
||||||
clear_background(r, g, b, 1);
|
clear_background(r, g, b, 1);
|
||||||
|
|
||||||
@@ -33,24 +50,58 @@ export class GameRenderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// with the camera in water, the screen and the hand are washed in the biome's water color, like minecraft's
|
||||||
|
// underwater overlay
|
||||||
|
#render_underwater(client: Client) {
|
||||||
|
const { x, y, z } = client.camera;
|
||||||
|
const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
|
||||||
|
if (!client.level.is_fluid(bx, by, bz)) return;
|
||||||
|
const color = client.level.water_color(bx, by, bz);
|
||||||
|
draw_rect(0, 0, canvas.width, canvas.height, [
|
||||||
|
(color >> 16) / 255,
|
||||||
|
((color >> 8) & 0xff) / 255,
|
||||||
|
(color & 0xff) / 255,
|
||||||
|
UNDERWATER_ALPHA,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
// partial_tick is how far this frame is between the last tick and the next, entities are drawn in between
|
// partial_tick is how far this frame is between the last tick and the next, entities are drawn in between
|
||||||
render(client: Client, partial_tick: number) {
|
render(client: Client, partial_tick: number) {
|
||||||
const camera = client.camera;
|
client.camera.setup(client.player, partial_tick);
|
||||||
camera.setup(client.player, partial_tick);
|
this.render_level(client.level, client.camera, partial_tick, client);
|
||||||
this.#setup_sky(client, partial_tick);
|
profiler.section("hand", () => this.hand.render(client.player, partial_tick));
|
||||||
|
this.#render_underwater(client);
|
||||||
|
|
||||||
begin_mode_3d(camera);
|
profiler.section("hud", () => {
|
||||||
this.level_renderer.render_opaque(client.level, camera);
|
this.hud.render(client);
|
||||||
this.level_renderer.render_destroy_progress(client.game_mode);
|
client.screen?.on_render();
|
||||||
this.level_renderer.render_entities(client.level, camera, client.player, partial_tick);
|
});
|
||||||
this.level_renderer.render_translucent(client.level, camera);
|
|
||||||
end_mode_3d();
|
|
||||||
this.hand.render(client.player.inventories);
|
|
||||||
|
|
||||||
this.hud.render(client);
|
|
||||||
client.screen?.on_render();
|
|
||||||
if (client.debugging) {
|
if (client.debugging) {
|
||||||
this.debug_overlay.render(client);
|
profiler.section("debug overlay", () => this.debug_overlay.render(client));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the sky and the level from the camera. with a viewer, the camera is in their player, who isn't drawn, and what
|
||||||
|
// they're breaking and looking at shows. the benchmark draws its level without one
|
||||||
|
render_level(
|
||||||
|
level: ClientLevel,
|
||||||
|
camera: Camera,
|
||||||
|
partial_tick: number,
|
||||||
|
viewer?: Pick<Client, "player" | "game_mode" | "hit_result">,
|
||||||
|
) {
|
||||||
|
this.#setup_sky(level, partial_tick);
|
||||||
|
set_render_time(level.ticks + partial_tick);
|
||||||
|
begin_mode_3d(camera);
|
||||||
|
const renderer = this.level_renderer;
|
||||||
|
renderer.render_opaque(level, camera);
|
||||||
|
profiler.section("entities", () => {
|
||||||
|
renderer.render_destroy_progress(level, viewer?.game_mode);
|
||||||
|
renderer.render_block_outline(level, viewer?.hit_result, camera);
|
||||||
|
renderer.render_entities(level, camera, viewer?.player, partial_tick);
|
||||||
|
});
|
||||||
|
profiler.section("visuals", () => renderer.render_visuals(level, camera, partial_tick));
|
||||||
|
profiler.section("translucent", () => renderer.render_translucent(level, camera));
|
||||||
|
profiler.section("nameplates", () => render_nameplates(level, camera, viewer?.player, partial_tick));
|
||||||
|
end_mode_3d();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// the player drawn in their inventory, like minecraft's InventoryScreen.renderEntityInInventoryFollowsMouse: standing,
|
||||||
|
// facing out of the screen, the body turned a little toward the mouse and the head turned and tilted more, with what
|
||||||
|
// 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
|
||||||
|
import { push_vertex, type Texture, use_texture } from "../renderer/mod.ts";
|
||||||
|
import type { ItemStack } from "@/common/inventory.ts";
|
||||||
|
import { AssetManager } from "../assets.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 { push_cube, type VertexSink } from "./player_renderer.ts";
|
||||||
|
import { push_worn } from "./worn_renderer.ts";
|
||||||
|
|
||||||
|
// how far away the mouse is, in gui pixels, for the player to turn about 45 degrees toward it, like minecraft's 40
|
||||||
|
const LOOK_DISTANCE = 40;
|
||||||
|
// how far they turn for that, like minecraft's 20 degrees for the body, and 40 for the head
|
||||||
|
const BODY_TURN = 20 * Math.PI / 180;
|
||||||
|
const HEAD_TURN = 40 * Math.PI / 180;
|
||||||
|
const HEAD_TILT = 20 * Math.PI / 180;
|
||||||
|
// the eyes, in skin pixels above the feet: what the mouse is measured from
|
||||||
|
export const EYES = 28;
|
||||||
|
|
||||||
|
// a face: its 6 vertices as [x, y, z, u, v, r, g, b], in blocks around the feet, the viewer at +z, and the texture
|
||||||
|
// they're in, the skin or the atlas for what's worn
|
||||||
|
export interface Face {
|
||||||
|
vertices: number[][];
|
||||||
|
texture: Texture;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the player facing +z, out of the screen, turned toward a mouse dx right of and dy below their eyes, in gui pixels
|
||||||
|
export function gui_player_pose(slim: boolean, dx: number, dy: number): PlayerPose {
|
||||||
|
const look_x = Math.atan(dx / LOOK_DISTANCE);
|
||||||
|
const look_y = Math.atan(dy / LOOK_DISTANCE);
|
||||||
|
const pose = pose_at({
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
z: 0,
|
||||||
|
yaw: Math.PI + look_x * BODY_TURN,
|
||||||
|
pitch: 0,
|
||||||
|
slim,
|
||||||
|
walk: { position: 0, speed: 0 },
|
||||||
|
});
|
||||||
|
// the head turns the rest of the way on top of the body, and tilts down for a mouse below
|
||||||
|
pose.parts.head = rotation_around(PARTS[0].pivot, -look_y * HEAD_TILT, look_x * (HEAD_TURN - BODY_TURN), 0);
|
||||||
|
return pose;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the player's faces turned toward the mouse (see gui_player_pose), with what they wear, back to front, without the
|
||||||
|
// ones facing away
|
||||||
|
export function gui_player_faces(skin: Texture, slim: boolean, dx: number, dy: number, worn: ItemStack[] = []): Face[] {
|
||||||
|
const pose = gui_player_pose(slim, dx, dy);
|
||||||
|
const faces: Face[] = [];
|
||||||
|
// every 6 vertices are a face, in the texture they're collected for
|
||||||
|
let vertices: number[][] = [];
|
||||||
|
const collect = (texture: Texture): VertexSink => (x, y, z, u, v, r = 1, g = 1, b = 1) => {
|
||||||
|
vertices.push([x, y, z, u, v, r, g, b]);
|
||||||
|
if (vertices.length === 6) {
|
||||||
|
faces.push({ vertices, texture });
|
||||||
|
vertices = [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const to_world = pose_to_world(pose);
|
||||||
|
const emit_skin = collect(skin);
|
||||||
|
for (const part of slim ? SLIM_PARTS : PARTS) {
|
||||||
|
const transform = (x: number, y: number, z: number) => to_world(...part_point(pose, part, x, y, z));
|
||||||
|
push_cube(skin, part, part.texture, 0, transform, undefined, emit_skin);
|
||||||
|
push_cube(skin, part, part.overlay, part.inflate, transform, undefined, emit_skin);
|
||||||
|
}
|
||||||
|
if (worn.length > 0) {
|
||||||
|
push_worn(worn, pose, undefined, collect(AssetManager.instance.get<Texture>("cubi:textures")));
|
||||||
|
}
|
||||||
|
|
||||||
|
return faces
|
||||||
|
.filter(({ vertices: [a, b, c] }) => {
|
||||||
|
// toward +z, the viewer
|
||||||
|
const normal_z = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
||||||
|
return normal_z > 1e-9;
|
||||||
|
})
|
||||||
|
.map((face) => ({ face, depth: face.vertices.reduce((sum, v) => sum + v[2], 0) }))
|
||||||
|
.sort((a, b) => a.depth - b.depth)
|
||||||
|
.map(({ face }) => face);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the player standing with their feet's middle at x, feet_y on the screen, pixel screen pixels to a skin pixel,
|
||||||
|
// looking at the mouse at mouse_x, mouse_y, wearing worn. gui_scale is the screen pixels to a gui pixel
|
||||||
|
export function draw_gui_player(
|
||||||
|
skin: Texture,
|
||||||
|
slim: boolean,
|
||||||
|
x: number,
|
||||||
|
feet_y: number,
|
||||||
|
pixel: number,
|
||||||
|
gui_scale: number,
|
||||||
|
mouse_x: number,
|
||||||
|
mouse_y: number,
|
||||||
|
worn: ItemStack[] = [],
|
||||||
|
) {
|
||||||
|
const eyes_y = feet_y - EYES * pixel;
|
||||||
|
const faces = gui_player_faces(skin, slim, (mouse_x - x) / gui_scale, (mouse_y - eyes_y) / gui_scale, worn);
|
||||||
|
// blocks to skin pixels to the screen, y down
|
||||||
|
const scale = 16 * pixel;
|
||||||
|
for (const { vertices, texture } of faces) {
|
||||||
|
use_texture(texture.tex);
|
||||||
|
for (const [vx, vy, , u, v, r, g, b] of vertices) {
|
||||||
|
push_vertex(x + vx * scale, feet_y - vy * scale, 0, u, v, r, g, b, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,26 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// the item the player is holding, drawn in the lower right in front of the camera like minecraft's
|
// the item the player is holding, drawn in the lower right in front of the camera like minecraft's
|
||||||
// ItemInHandRenderer. empty hands show nothing
|
// ItemInHandRenderer. with empty hands it's their right arm, in their skin, like minecraft's
|
||||||
|
// 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 { ClientInventories } from "$/client/inventory.ts";
|
import type { LocalPlayer } from "@/client/entity/local_player.ts";
|
||||||
import { begin_view_model, end_mode_3d, flush_batch, set_current_texture, Texture } from "$/client/renderer/mod.ts";
|
import {
|
||||||
import { item_block, push_item } from "./item_renderer.ts";
|
begin_view_model,
|
||||||
|
end_mode_3d,
|
||||||
|
flush_batch,
|
||||||
|
set_current_texture,
|
||||||
|
Texture,
|
||||||
|
use_texture,
|
||||||
|
} from "@/client/renderer/mod.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 { right_arm } from "./player_model.ts";
|
||||||
|
import { render_worn_arm } from "./worn_renderer.ts";
|
||||||
|
import { entity_tint } from "./entity_light.ts";
|
||||||
|
|
||||||
// wider than the world's field of view, like minecraft's fixed 70 degrees for the hand
|
// wider than the world's field of view, like minecraft's fixed 70 degrees for the hand
|
||||||
const FOV = 70 * Math.PI / 180;
|
const FOV = 70 * Math.PI / 180;
|
||||||
@@ -32,7 +47,8 @@ export class HandRenderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
render(inventories: ClientInventories) {
|
render(player: LocalPlayer, partial_tick: number) {
|
||||||
|
const inventories = player.inventories;
|
||||||
const item = inventories.inventory.get_item(inventories.hotbar_selected);
|
const item = inventories.inventory.get_item(inventories.hotbar_selected);
|
||||||
const held = item ? `${inventories.hotbar_selected} ${item.type_id}` : "";
|
const held = item ? `${inventories.hotbar_selected} ${item.type_id}` : "";
|
||||||
const now = performance.now();
|
const now = performance.now();
|
||||||
@@ -40,26 +56,97 @@ export class HandRenderer {
|
|||||||
this.#held = held;
|
this.#held = held;
|
||||||
this.#equipped_at = now;
|
this.#equipped_at = now;
|
||||||
}
|
}
|
||||||
if (!item) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const equip = Math.min(1, (now - this.#equipped_at) / EQUIP_MS);
|
const equip = Math.min(1, (now - this.#equipped_at) / EQUIP_MS);
|
||||||
const swing_progress = Math.min(1, (now - this.#swung_at) / SWING_MS);
|
const swing_progress = Math.min(1, (now - this.#swung_at) / SWING_MS);
|
||||||
const swing = Math.sin(swing_progress * Math.PI);
|
|
||||||
|
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
// the light where the player's eyes are, like every other entity
|
||||||
|
const tint = entity_tint(player, partial_tick);
|
||||||
begin_view_model(FOV);
|
begin_view_model(FOV);
|
||||||
set_current_texture(atlas.tex);
|
if (item) {
|
||||||
push_item(atlas, item, pose(item, (1 - equip) * 0.6, swing));
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
|
set_current_texture(atlas.tex);
|
||||||
|
const display = item_model_of(item)?.display.firstperson_righthand;
|
||||||
|
const transform = display
|
||||||
|
? display_transform(held_pose(1 - equip, swing_progress), display)
|
||||||
|
: pose(item, (1 - equip) * 0.6, Math.sin(swing_progress * Math.PI));
|
||||||
|
push_item(atlas, item, transform, tint);
|
||||||
|
} else {
|
||||||
|
const skin = player.skin ?? AssetManager.instance.get<Texture>("cubi:skin");
|
||||||
|
const arm = right_arm(player.slim);
|
||||||
|
const transform = arm_pose(arm.pivot, 1 - equip, swing_progress);
|
||||||
|
set_current_texture(skin.tex);
|
||||||
|
push_cube(skin, arm, arm.texture, 0, transform, tint);
|
||||||
|
push_cube(skin, arm, arm.overlay, arm.inflate, transform, tint);
|
||||||
|
// what's worn on it goes over it, from the atlas
|
||||||
|
if (player.worn.length > 0) {
|
||||||
|
use_texture(AssetManager.instance.get<Texture>("cubi:textures").tex);
|
||||||
|
render_worn_arm(player, transform, tint);
|
||||||
|
}
|
||||||
|
}
|
||||||
flush_batch();
|
flush_batch();
|
||||||
end_mode_3d();
|
end_mode_3d();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// from the item's model to in front of the camera. lower drops it out of sight, swing tips it forward and in
|
// minecraft's renderPlayerArm for the right arm, from the arm's own points (around its pivot, in skin pixels) to in
|
||||||
|
// front of the camera. lower is how far it's dropped out of sight (its inverseArmHeight), attack how far through the
|
||||||
|
// swing it is, both 0 to 1. the numbers are minecraft's, in its model's axes: y down and x mirrored from ours
|
||||||
|
export function arm_pose(pivot: Vec3, lower: number, attack: number) {
|
||||||
|
const degrees = Math.PI / 180;
|
||||||
|
const sqrt_attack = Math.sqrt(attack);
|
||||||
|
const matrix = mat4.create();
|
||||||
|
mat4.translate(matrix, matrix, [
|
||||||
|
-0.3 * Math.sin(sqrt_attack * Math.PI) + 0.64,
|
||||||
|
0.4 * Math.sin(sqrt_attack * Math.PI * 2) - 0.6 - lower * 0.6,
|
||||||
|
-0.4 * Math.sin(attack * Math.PI) - 0.72,
|
||||||
|
]);
|
||||||
|
mat4.rotateY(matrix, matrix, 45 * degrees);
|
||||||
|
mat4.rotateY(matrix, matrix, Math.sin(sqrt_attack * Math.PI) * 70 * degrees);
|
||||||
|
mat4.rotateZ(matrix, matrix, Math.sin(attack * attack * Math.PI) * -20 * degrees);
|
||||||
|
mat4.translate(matrix, matrix, [-1, 3.6, 3.5]);
|
||||||
|
mat4.rotateZ(matrix, matrix, 120 * degrees);
|
||||||
|
mat4.rotateX(matrix, matrix, 200 * degrees);
|
||||||
|
mat4.rotateY(matrix, matrix, -135 * degrees);
|
||||||
|
mat4.translate(matrix, matrix, [5.6, 0, 0]);
|
||||||
|
// the arm's ModelPart: to its pivot, tipped out a little like the player renderer's renderHand does, in pixels
|
||||||
|
const [px, py, pz] = pivot;
|
||||||
|
mat4.translate(matrix, matrix, [-px / 16, (24 - py) / 16, pz / 16]);
|
||||||
|
mat4.rotateZ(matrix, matrix, 0.1);
|
||||||
|
mat4.scale(matrix, matrix, [1 / 16, 1 / 16, 1 / 16]);
|
||||||
|
|
||||||
|
const point = vec3.create();
|
||||||
|
return (x: number, y: number, z: number): Vec3 => {
|
||||||
|
// from our model's axes to minecraft's
|
||||||
|
vec3.transformMat4(point, [-x, -y, z], matrix);
|
||||||
|
return [point[0], point[1], point[2]];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// where a held model's firstperson_righthand transform starts from: low on the right in front of the camera, dropped
|
||||||
|
// out of sight by lower and swung by attack like arm_pose. it's where the display format's transforms are made from, so
|
||||||
|
// ones made for it elsewhere look the same here
|
||||||
|
export function held_pose(lower: number, attack: number) {
|
||||||
|
const degrees = Math.PI / 180;
|
||||||
|
const sqrt_attack = Math.sqrt(attack);
|
||||||
|
const matrix = mat4.create();
|
||||||
|
mat4.translate(matrix, matrix, [
|
||||||
|
-0.4 * Math.sin(sqrt_attack * Math.PI) + 0.56,
|
||||||
|
0.2 * Math.sin(sqrt_attack * Math.PI * 2) - 0.52 - lower * 0.6,
|
||||||
|
-0.2 * Math.sin(attack * Math.PI) - 0.72,
|
||||||
|
]);
|
||||||
|
const swing = Math.sin(sqrt_attack * Math.PI);
|
||||||
|
mat4.rotateY(matrix, matrix, (45 - Math.sin(attack * attack * Math.PI) * 20) * degrees);
|
||||||
|
mat4.rotateZ(matrix, matrix, swing * -20 * degrees);
|
||||||
|
mat4.rotateX(matrix, matrix, swing * -80 * degrees);
|
||||||
|
mat4.rotateY(matrix, matrix, -45 * degrees);
|
||||||
|
return matrix;
|
||||||
|
}
|
||||||
|
|
||||||
|
// from the item's model to in front of the camera, for one without a display transform for it. lower drops it out of
|
||||||
|
// sight, swing tips it forward and in
|
||||||
function pose(item: ItemStack, lower: number, swing: number) {
|
function pose(item: ItemStack, lower: number, swing: number) {
|
||||||
const p = item_block(item) ? BLOCK_POSE : ITEM_POSE;
|
const p = drawn_as_model(item) ? BLOCK_POSE : ITEM_POSE;
|
||||||
const matrix = mat4.create();
|
const matrix = mat4.create();
|
||||||
mat4.translate(matrix, matrix, [p.x - swing * 0.25, p.y - lower + swing * 0.1, p.z - swing * 0.2]);
|
mat4.translate(matrix, matrix, [p.x - swing * 0.25, p.y - lower + swing * 0.1, p.z - swing * 0.2]);
|
||||||
mat4.rotateX(matrix, matrix, p.pitch - swing * SWING_ANGLE);
|
mat4.rotateX(matrix, matrix, p.pitch - swing * SWING_ANGLE);
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
// 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
|
||||||
|
|||||||
@@ -1,21 +1,45 @@
|
|||||||
import type { SpriteRegion } from "$/common/constants.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import { mat4, vec3 } from "gl-matrix";
|
||||||
import type { ItemEntity } from "$/client/entity/item_entity.ts";
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
import type { ItemStack } from "$/common/inventory.ts";
|
import { BlockRegistry, EverythingRegistry, type ItemLayer, ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
import { push_vertex, Texture } from "$/client/renderer/mod.ts";
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
import { block_item_texture, block_variant, cube_face_texture, cube_face_tint } from "$/common/block_models.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { item_model } from "./item_model.ts";
|
import type { ItemEntity } from "@/client/entity/item_entity.ts";
|
||||||
import { get_state_value, item_texture } from "$/common/utils.ts";
|
import { contained_fluid, type ItemData, ItemStack } from "@/common/inventory.ts";
|
||||||
import { ID_MASK, TEXTURE_SIZE } from "$/common/constants.ts";
|
import type { FluidVariant } from "@/common/mod_api/shared.ts";
|
||||||
import type { ClientLevel } from "$/client/level/client_level.ts";
|
import type { EntityModelJson, FluidJson } from "@/common/mod_data.ts";
|
||||||
|
import { light_color, push_vertex, Texture } from "@/client/renderer/mod.ts";
|
||||||
|
import {
|
||||||
|
bake_model,
|
||||||
|
type BakedQuad,
|
||||||
|
block_item_texture,
|
||||||
|
block_variant,
|
||||||
|
classify_quad,
|
||||||
|
cube_face_texture,
|
||||||
|
cube_face_tint,
|
||||||
|
type DisplayTransform,
|
||||||
|
find_model,
|
||||||
|
ITEM_FACE_SHADE,
|
||||||
|
item_tint,
|
||||||
|
type ModelDisplay,
|
||||||
|
type ModelJson,
|
||||||
|
} from "@/common/block_models.ts";
|
||||||
|
import { item_model, type ItemQuad } from "./item_model.ts";
|
||||||
|
import { get_state_value, item_texture } from "@/common/utils.ts";
|
||||||
|
import { ID_MASK, TEXTURE_SIZE } from "@/common/constants.ts";
|
||||||
|
import type { ClientLevel } from "@/client/level/client_level.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 { fluid_rules } from "@/client/fluid_rules.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;
|
||||||
const ITEM_SCALE = 0.5;
|
const ITEM_SCALE = 0.5;
|
||||||
// keeps texture lookups off the sprite's edge
|
|
||||||
const UV_PAD = 0.5;
|
|
||||||
|
|
||||||
// each face's corners in drawing order (counter clockwise from outside) on a unit cube, with its shade.
|
// each face's corners in drawing order (counter clockwise from outside) on a unit cube, with its shade.
|
||||||
// top, bottom, front, back, left, right, like the chunk mesher
|
// top, bottom, front, back, left, right, like the chunk mesher
|
||||||
@@ -33,6 +57,9 @@ const CORNER_UVS = [[0, 1], [1, 1], [1, 0], [0, 0]] as const;
|
|||||||
// where the extra copies of a bigger stack sit, as fractions of the model's size
|
// where the extra copies of a bigger stack sit, as fractions of the model's size
|
||||||
const COPY_OFFSETS = [[0, 0, 0], [0.35, 0.2, -0.25], [-0.3, 0.4, 0.2], [0.15, 0.6, 0.35], [-0.2, 0.8, -0.3]];
|
const COPY_OFFSETS = [[0, 0, 0], [0.35, 0.2, -0.25], [-0.3, 0.4, 0.2], [0.15, 0.6, 0.35], [-0.2, 0.8, -0.3]];
|
||||||
|
|
||||||
|
// how far each of a flat item's layers sits out from the one under it, so it's drawn over it
|
||||||
|
const LAYER_GAP = 0.001;
|
||||||
|
|
||||||
// minecraft draws more copies of the model the bigger the stack is
|
// minecraft draws more copies of the model the bigger the stack is
|
||||||
function copies(amount: number) {
|
function copies(amount: number) {
|
||||||
if (amount > 48) return 5;
|
if (amount > 48) return 5;
|
||||||
@@ -46,15 +73,29 @@ function copies(amount: number) {
|
|||||||
// copies for bigger stacks are this far apart, and at most this far off the middle
|
// copies for bigger stacks are this far apart, and at most this far off the middle
|
||||||
const SHOWN_ITEM_SCALE = 0.6;
|
const SHOWN_ITEM_SCALE = 0.6;
|
||||||
const SHOWN_BLOCK_SCALE = 0.4;
|
const SHOWN_BLOCK_SCALE = 0.4;
|
||||||
|
// a model with its own fixed transform is sized by it on top of this. a block's usually halves it, to SHOWN_BLOCK_SCALE
|
||||||
|
const SHOWN_MODEL_SCALE = 0.8;
|
||||||
const SHOWN_COPY_GAP = 0.03;
|
const SHOWN_COPY_GAP = 0.03;
|
||||||
const SHOWN_COPY_SPREAD = 0.075;
|
const SHOWN_COPY_SPREAD = 0.075;
|
||||||
|
|
||||||
// a point of an item's model to where it's drawn. models are 1 across, from y 0 to 1, centered on x and z
|
// a point of an item's model to where it's drawn. models are 1 across, from y 0 to 1, centered on x and z
|
||||||
export type ItemTransform = (x: number, y: number, z: number) => [number, number, number];
|
export type ItemTransform = (x: number, y: number, z: number) => [number, number, number];
|
||||||
|
|
||||||
|
// where push_item's vertices go: the batch, or anything else that takes them the same way, like a visual's model
|
||||||
|
export type VertexSink = typeof push_vertex;
|
||||||
|
|
||||||
|
// an item the size it's drawn on the ground, with its middle at the middle of the block. for a visual's item, which
|
||||||
|
// is placed from there, like create's items in a basin
|
||||||
|
export function ground_transform(item: ItemStack): ItemTransform {
|
||||||
|
const ground = item_model_of(item)?.display.ground;
|
||||||
|
if (ground) return display_transform(mat4.fromTranslation(mat4.create(), [0.5, 0.5, 0.5]), ground);
|
||||||
|
const scale = drawn_as_model(item) ? BLOCK_SCALE : ITEM_SCALE;
|
||||||
|
return (x, y, z) => [0.5 + x * scale, 0.5 + (y - 0.5) * scale, 0.5 + z * scale];
|
||||||
|
}
|
||||||
|
|
||||||
// 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;
|
||||||
@@ -64,32 +105,59 @@ export function render_item_entity(entity: ItemEntity, partial_tick: number) {
|
|||||||
const sin = Math.sin(angle);
|
const sin = Math.sin(angle);
|
||||||
const cos = Math.cos(angle);
|
const cos = Math.cos(angle);
|
||||||
|
|
||||||
const scale = item_block(entity.item) ? BLOCK_SCALE : ITEM_SCALE;
|
const scale = drawn_as_model(entity.item) ? BLOCK_SCALE : ITEM_SCALE;
|
||||||
|
const ground = item_model_of(entity.item)?.display.ground;
|
||||||
|
const tint = entity_tint(entity, partial_tick);
|
||||||
for (let i = 0; i < copies(entity.item.amount); i++) {
|
for (let i = 0; i < copies(entity.item.amount); i++) {
|
||||||
const [ox, oy, oz] = COPY_OFFSETS[i];
|
const [ox, oy, oz] = COPY_OFFSETS[i];
|
||||||
const bx = x + ox * scale;
|
const bx = x + ox * scale;
|
||||||
const by = y + bob + oy * scale * 0.5;
|
const by = y + bob + oy * scale * 0.5;
|
||||||
const bz = z + oz * scale;
|
const bz = z + oz * scale;
|
||||||
|
if (ground) {
|
||||||
|
// lifted by a quarter of its height and spun, then its own transform
|
||||||
|
const base = mat4.fromTranslation(mat4.create(), [bx, by + 0.25 * (ground.scale?.[1] ?? 1), bz]);
|
||||||
|
push_item(atlas, entity.item, display_transform(mat4.rotateY(base, base, -angle), ground), tint);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
push_item(atlas, entity.item, (lx, ly, lz) => [
|
push_item(atlas, entity.item, (lx, ly, lz) => [
|
||||||
bx + (lx * cos - lz * sin) * scale,
|
bx + (lx * cos - lz * sin) * scale,
|
||||||
by + ly * scale,
|
by + ly * scale,
|
||||||
bz + (lx * sin + lz * cos) * scale,
|
bz + (lx * sin + lz * cos) * scale,
|
||||||
]);
|
], tint);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// every item blocks with item_display show on top of them, see BlockRegistry.item_display. the atlas has to be the
|
// the stack an item synced to clients is drawn as, like a shown item's "item" client data or an object's. made once
|
||||||
// current texture
|
// 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.
|
||||||
|
// 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 items of level.block_items.values()) {
|
for (const in_chunk of level.block_data.values()) {
|
||||||
for (const { x, y, z, item } of items.values()) {
|
for (const { x, y, z, data } of in_chunk.values()) {
|
||||||
|
const shown = data.item as ItemData | undefined;
|
||||||
|
if (!shown) continue;
|
||||||
// gone already when this client predicted breaking it
|
// gone already when this client predicted breaking it
|
||||||
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;
|
||||||
push_shown_item(atlas, block, value, item, x, y, z);
|
const item = synced_stack(shown);
|
||||||
|
// 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 above = level.get_light(x, y + 1, z);
|
||||||
|
const tint = light_color((Math.max(here >> 4, above >> 4) << 4) | Math.max(here & 15, above & 15));
|
||||||
|
push_shown_item(atlas, block, value, item, x, y, z, tint);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -102,6 +170,7 @@ function push_shown_item(
|
|||||||
x: number,
|
x: number,
|
||||||
y: number,
|
y: number,
|
||||||
z: number,
|
z: number,
|
||||||
|
tint: Vec3,
|
||||||
) {
|
) {
|
||||||
const states: Record<string, number> = {};
|
const states: Record<string, number> = {};
|
||||||
for (const state of block.states ?? []) states[state.name] = get_state_value(value, block, state.name)!;
|
for (const state of block.states ?? []) states[state.name] = get_state_value(value, block, state.name)!;
|
||||||
@@ -115,7 +184,8 @@ function push_shown_item(
|
|||||||
[bx, bz] = [-bz, bx];
|
[bx, bz] = [-bz, bx];
|
||||||
}
|
}
|
||||||
|
|
||||||
const is_block = item_block(item) !== undefined;
|
const is_block = drawn_as_model(item);
|
||||||
|
const fixed = item_model_of(item)?.display.fixed;
|
||||||
const scale = is_block ? SHOWN_BLOCK_SCALE : SHOWN_ITEM_SCALE;
|
const scale = is_block ? SHOWN_BLOCK_SCALE : SHOWN_ITEM_SCALE;
|
||||||
const surface = y + block.item_display!.surface / TEXTURE_SIZE;
|
const surface = y + block.item_display!.surface / TEXTURE_SIZE;
|
||||||
const random = seeded_random(item.type_id);
|
const random = seeded_random(item.type_id);
|
||||||
@@ -127,13 +197,19 @@ function push_shown_item(
|
|||||||
const cx = x + 0.5 + ox;
|
const cx = x + 0.5 + ox;
|
||||||
const cz = z + 0.5 + oz;
|
const cz = z + 0.5 + oz;
|
||||||
const bottom = surface + SHOWN_COPY_GAP * (i + 1);
|
const bottom = surface + SHOWN_COPY_GAP * (i + 1);
|
||||||
if (is_block) {
|
if (fixed) {
|
||||||
|
// standing like a block, its middle where a block's would be and its front towards whoever it faces
|
||||||
|
const base = mat4.fromTranslation(mat4.create(), [cx, bottom + scale / 2, cz]);
|
||||||
|
mat4.rotateY(base, base, Math.PI - turns * Math.PI / 2);
|
||||||
|
mat4.scale(base, base, [SHOWN_MODEL_SCALE, SHOWN_MODEL_SCALE, SHOWN_MODEL_SCALE]);
|
||||||
|
push_item(atlas, item, display_transform(base, fixed), tint);
|
||||||
|
} else if (is_block) {
|
||||||
// standing, its front towards whoever it faces
|
// standing, its front towards whoever it faces
|
||||||
push_item(atlas, item, (lx, ly, lz) => [
|
push_item(atlas, item, (lx, ly, lz) => [
|
||||||
cx + (rx * lx - bx * lz) * scale,
|
cx + (rx * lx - bx * lz) * scale,
|
||||||
bottom + ly * scale,
|
bottom + ly * scale,
|
||||||
cz + (rz * lx - bz * lz) * scale,
|
cz + (rz * lx - bz * lz) * scale,
|
||||||
]);
|
], tint);
|
||||||
} else {
|
} else {
|
||||||
// lying face up, its top away from whoever it faces so they read it the right way round
|
// lying face up, its top away from whoever it faces so they read it the right way round
|
||||||
const half = scale / TEXTURE_SIZE / 2;
|
const half = scale / TEXTURE_SIZE / 2;
|
||||||
@@ -141,7 +217,7 @@ function push_shown_item(
|
|||||||
cx + (rx * lx + bx * (ly - 0.5)) * scale,
|
cx + (rx * lx + bx * (ly - 0.5)) * scale,
|
||||||
bottom + half + lz * scale,
|
bottom + half + lz * scale,
|
||||||
cz + (rz * lx + bz * (ly - 0.5)) * scale,
|
cz + (rz * lx + bz * (ly - 0.5)) * scale,
|
||||||
]);
|
], tint);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -159,48 +235,268 @@ function seeded_random(seed: string) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the block a block's own item looks like. other items that place a block, like seeds or a water bucket, look like
|
||||||
|
// their own texture
|
||||||
|
export function placed_block(item: ItemStack): BlockRegistry | undefined {
|
||||||
|
const item_info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||||
|
if (!item_info?.block_id || item_info.block_id !== item.type_id) return undefined;
|
||||||
|
return EverythingRegistry.get<BlockRegistry>("blocks", item_info.block_id);
|
||||||
|
}
|
||||||
|
|
||||||
// the full block an item places, drawn as a cube. blocks that aren't cubes, like plants, are drawn as their sprite
|
// the full block an item places, drawn as a cube. blocks that aren't cubes, like plants, are drawn as their sprite
|
||||||
export function item_block(item: ItemStack): BlockRegistry | undefined {
|
export function item_block(item: ItemStack): BlockRegistry | undefined {
|
||||||
const item_info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
const block = placed_block(item);
|
||||||
const block = item_info?.block_id ? EverythingRegistry.get<BlockRegistry>("blocks", item_info.block_id) : undefined;
|
|
||||||
return block && block_item_texture(block) === undefined ? block : undefined;
|
return block && block_item_texture(block) === undefined ? block : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
// an item's model: a cube for blocks, its sprite made 3d for everything else (see item_model.ts)
|
// the model an item is drawn with, when it has one: its quads, its display transforms, and the block whose textures and
|
||||||
export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransform) {
|
// tint fill it in
|
||||||
|
export interface ItemModel {
|
||||||
|
quads: BakedQuad[];
|
||||||
|
display: ModelDisplay;
|
||||||
|
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. an item's
|
||||||
|
// 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 {
|
||||||
|
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||||
|
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);
|
||||||
|
if (block?.item_model !== undefined) return baked_item_model(block, block.item_model, block);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function baked_item_model(key: ItemRegistry | BlockRegistry, id: string, block?: BlockRegistry): ItemModel {
|
||||||
|
let model = baked_items.get(key);
|
||||||
|
if (!model) {
|
||||||
|
const json = find_model(id, Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")));
|
||||||
|
model = { quads: json ? bake_model(json, block?.textures) : [], display: json?.display ?? {}, block };
|
||||||
|
baked_items.set(key, model);
|
||||||
|
}
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
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
|
||||||
|
// held when its model has no display transform for that
|
||||||
|
export function drawn_as_model(item: ItemStack) {
|
||||||
|
return item_block(item) !== undefined || item_model_of(item) !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a display transform after base: from a model's points (0 to 1 across the block) to base's, with the model's middle at
|
||||||
|
// base's origin before it's moved, turned and scaled
|
||||||
|
export function display_matrix(base: mat4, display: DisplayTransform): mat4 {
|
||||||
|
const matrix = mat4.clone(base);
|
||||||
|
const [tx, ty, tz] = display.translation ?? [0, 0, 0];
|
||||||
|
mat4.translate(matrix, matrix, [tx / 16, ty / 16, tz / 16]);
|
||||||
|
const [rx, ry, rz] = (display.rotation ?? [0, 0, 0]).map((degrees) => degrees * Math.PI / 180);
|
||||||
|
mat4.rotateX(matrix, matrix, rx);
|
||||||
|
mat4.rotateY(matrix, matrix, ry);
|
||||||
|
mat4.rotateZ(matrix, matrix, rz);
|
||||||
|
mat4.scale(matrix, matrix, display.scale ?? [1, 1, 1]);
|
||||||
|
mat4.translate(matrix, matrix, [-0.5, -0.5, -0.5]);
|
||||||
|
return matrix;
|
||||||
|
}
|
||||||
|
|
||||||
|
// display_matrix as an ItemTransform, whose points are centered on x and z
|
||||||
|
export function display_transform(base: mat4, display: DisplayTransform): ItemTransform {
|
||||||
|
const matrix = display_matrix(base, display);
|
||||||
|
const point = vec3.create();
|
||||||
|
return (x, y, z) => {
|
||||||
|
vec3.transformMat4(point, [x + 0.5, y, z + 0.5], matrix);
|
||||||
|
return [point[0], point[1], point[2]];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// an item's model: its own model or its block's item_model, a cube for other blocks, its sprite made 3d for everything
|
||||||
|
// else (see item_model.ts). tint multiplies its colors, like the light it's in. two triangles a quad, its corners 0 1 2
|
||||||
|
// and 0 2 3
|
||||||
|
export function push_item(
|
||||||
|
atlas: Texture,
|
||||||
|
item: ItemStack,
|
||||||
|
transform: ItemTransform,
|
||||||
|
[tr, tg, tb]: Vec3 = [1, 1, 1],
|
||||||
|
vertex: VertexSink = push_vertex,
|
||||||
|
) {
|
||||||
|
const model = item_model_of(item);
|
||||||
|
if (model) {
|
||||||
|
for (const quad of model.quads) {
|
||||||
|
const region = get_sprite_region(quad.texture);
|
||||||
|
const [r, g, b] = model.block ? item_tint(model.block, quad.variables) : [1, 1, 1];
|
||||||
|
const shade = quad.shade ? ITEM_FACE_SHADE[quad.face] : 1;
|
||||||
|
for (const i of [0, 1, 2, 0, 2, 3]) {
|
||||||
|
const p = quad.positions;
|
||||||
|
const [px, py, pz] = transform(p[i * 3] - 0.5, p[i * 3 + 1], p[i * 3 + 2] - 0.5);
|
||||||
|
vertex(
|
||||||
|
px,
|
||||||
|
py,
|
||||||
|
pz,
|
||||||
|
sprite_u(atlas, region, quad.uvs[i * 2]),
|
||||||
|
sprite_v(atlas, region, quad.uvs[i * 2 + 1]),
|
||||||
|
shade * r * tr,
|
||||||
|
shade * g * tg,
|
||||||
|
shade * b * tb,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
const block = item_block(item);
|
const block = item_block(item);
|
||||||
if (block) {
|
if (block) {
|
||||||
for (const face of CUBE_FACES) {
|
for (const face of CUBE_FACES) {
|
||||||
const region = get_sprite_region(cube_face_texture(block, face.texture));
|
const region = get_sprite_region(cube_face_texture(block, face.texture));
|
||||||
const corners = face.corners.map(([cx, cy, cz]) => transform(cx - 0.5, cy, cz - 0.5));
|
const corners = face.corners.map(([cx, cy, cz]) => transform(cx - 0.5, cy, cz - 0.5));
|
||||||
const [r, g, b] = cube_face_tint(block, face.texture);
|
const [r, g, b] = cube_face_tint(block, face.texture);
|
||||||
push_textured_quad(atlas, region, corners, [face.shade * r, face.shade * g, face.shade * b]);
|
const color = [face.shade * r * tr, face.shade * g * tg, face.shade * b * tb];
|
||||||
|
push_textured_quad(atlas, region, corners, color, vertex);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// its sprite, then its layers over it: only their fronts and backs, the first two quads, each a little further out
|
||||||
const texture_id = item_texture(item);
|
const texture_id = item_texture(item);
|
||||||
|
push_sprite(atlas, texture_id, item_model(texture_id), [tr, tg, tb], 0, transform, vertex);
|
||||||
|
item_layers(item).forEach(({ texture, color: [r, g, b] }, i) => {
|
||||||
|
const color: Vec3 = [r * tr, g * tg, b * tb];
|
||||||
|
push_sprite(atlas, texture, item_model(texture).slice(0, 2), color, (i + 1) * LAYER_GAP, transform, vertex);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// a flat item's sprite made 3d (see item_model.ts), its front and back gap further out than the item's
|
||||||
|
function push_sprite(
|
||||||
|
atlas: Texture,
|
||||||
|
texture_id: string,
|
||||||
|
quads: ItemQuad[],
|
||||||
|
[r, g, b]: Vec3,
|
||||||
|
gap: number,
|
||||||
|
transform: ItemTransform,
|
||||||
|
vertex: VertexSink,
|
||||||
|
) {
|
||||||
const region = get_sprite_region(texture_id);
|
const region = get_sprite_region(texture_id);
|
||||||
const u = (pixels: number) => (region.x + pixels) / atlas.width;
|
for (const quad of quads) {
|
||||||
const v = (pixels: number) => (region.y + pixels) / atlas.height;
|
// each corner transformed once, though corners 0 and 2 are in both triangles
|
||||||
for (const quad of item_model(texture_id)) {
|
const points = quad.corners.map(([cx, cy, cz]) => transform(cx, cy, cz + Math.sign(cz) * gap));
|
||||||
for (const i of [0, 1, 2, 0, 2, 3]) {
|
for (const i of QUAD_CORNERS) {
|
||||||
const [px, py, pz] = transform(...quad.corners[i]);
|
const point = points[i];
|
||||||
const [pu, pv] = quad.uvs[i];
|
const uv = quad.uvs[i];
|
||||||
push_vertex(px, py, pz, u(pu), v(pv), quad.shade, quad.shade, quad.shade, 1);
|
const u = (region.x + uv[0]) / atlas.width;
|
||||||
|
const v = (region.y + uv[1]) / atlas.height;
|
||||||
|
vertex(point[0], point[1], point[2], u, v, quad.shade * r, quad.shade * g, quad.shade * b, 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function push_textured_quad(atlas: Texture, region: SpriteRegion, corners: number[][], color: number[]) {
|
// a quad's corners as two triangles
|
||||||
const u0 = (region.x + UV_PAD) / atlas.width;
|
const QUAD_CORNERS = [0, 1, 2, 0, 2, 3];
|
||||||
const v0 = (region.y + UV_PAD) / atlas.height;
|
|
||||||
const u1 = (region.x + region.width - UV_PAD) / atlas.width;
|
// the layers drawn over a flat item's texture (see ItemLayer), each in its tint's color, without the ones whose tint
|
||||||
const v1 = (region.y + region.height - UV_PAD) / atlas.height;
|
// has no color for this stack
|
||||||
|
export function item_layers(item: ItemStack): { texture: string; color: Vec3 }[] {
|
||||||
|
const layers = EverythingRegistry.get<ItemRegistry>("items", item.type_id)?.layers ?? [];
|
||||||
|
return layers.flatMap(({ texture, tint }) => {
|
||||||
|
const color = layer_color(item, tint);
|
||||||
|
return color ? [{ texture, color }] : [];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function layer_color(item: ItemStack, tint: ItemLayer["tint"]): Vec3 | undefined {
|
||||||
|
if (tint === undefined) return [1, 1, 1];
|
||||||
|
if (tint !== "fluid") return color_rgb(tint_without_biome(tint));
|
||||||
|
const fluid = contained_fluid(item.type_id, item.data);
|
||||||
|
return fluid && fluid_rgb(fluid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a fluid's color by its rules, as r g b from 0 to 1
|
||||||
|
export function fluid_rgb(fluid: FluidVariant): Vec3 {
|
||||||
|
return color_rgb(tint_without_biome(fluid_rules.color(fluid) as TintColor));
|
||||||
|
}
|
||||||
|
|
||||||
|
// a fluid's texture and its color by its rules, for drawing it in a box or a slot. throws for a fluid no mod defines
|
||||||
|
export function fluid_look(fluid: FluidVariant): { texture: string; tint: Vec3 } {
|
||||||
|
const json = EverythingRegistry.get<FluidJson>("fluids", fluid?.id);
|
||||||
|
if (!json) throw new Error(`there's no fluid ${fluid?.id}`);
|
||||||
|
return { texture: json.texture ?? "cubi:missing", tint: fluid_rgb(structuredClone(fluid)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// where a model's uv in pixels (0-16) is in the atlas. the atlas's border around each sprite (see ATLAS_BORDER) keeps
|
||||||
|
// lookups that round past its edge on its own pixels
|
||||||
|
export function sprite_u(atlas: Texture, region: SpriteRegion, pixels: number) {
|
||||||
|
return (region.x + pixels / TEXTURE_SIZE * region.width) / atlas.width;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sprite_v(atlas: Texture, region: SpriteRegion, pixels: number) {
|
||||||
|
return (region.y + pixels / TEXTURE_SIZE * region.height) / atlas.height;
|
||||||
|
}
|
||||||
|
|
||||||
|
function push_textured_quad(
|
||||||
|
atlas: Texture,
|
||||||
|
region: SpriteRegion,
|
||||||
|
corners: number[][],
|
||||||
|
color: number[],
|
||||||
|
vertex: VertexSink,
|
||||||
|
) {
|
||||||
|
const u0 = region.x / atlas.width;
|
||||||
|
const v0 = region.y / atlas.height;
|
||||||
|
const u1 = (region.x + region.width) / atlas.width;
|
||||||
|
const v1 = (region.y + region.height) / atlas.height;
|
||||||
|
|
||||||
for (const i of [0, 1, 2, 0, 2, 3]) {
|
for (const i of [0, 1, 2, 0, 2, 3]) {
|
||||||
const [px, py, pz] = corners[i];
|
const [px, py, pz] = corners[i];
|
||||||
const [cu, cv] = CORNER_UVS[i];
|
const [cu, cv] = CORNER_UVS[i];
|
||||||
push_vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, color[0], color[1], color[2], 1);
|
vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, color[0], color[1], color[2], 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+396
-100
@@ -1,164 +1,435 @@
|
|||||||
import { type Chunk, CHUNK_SIZE, type ChunkMesh, ClientLevel } from "$/client/level/client_level.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { Camera } from "$/client/camera.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
import {
|
||||||
import type { MultiPlayerGameMode } from "$/client/game_mode.ts";
|
type Chunk,
|
||||||
import type { Entity } from "$/client/entity/entity.ts";
|
CHUNK_SIZE,
|
||||||
import { RemotePlayer } from "$/client/entity/remote_player.ts";
|
type ChunkMesh,
|
||||||
import { ItemEntity } from "$/client/entity/item_entity.ts";
|
ClientLevel,
|
||||||
|
type RenderSection,
|
||||||
|
} from "@/client/level/client_level.ts";
|
||||||
|
import { profiler } from "@/client/profiler.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 { 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 type { PlayerPose } from "./player_model.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 { RemoteEntity } from "$/client/entity/remote_entity.ts";
|
import { entity_tint } from "./entity_light.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_back_face,
|
push_vertex,
|
||||||
push_bottom_face,
|
render_debug,
|
||||||
push_front_face,
|
|
||||||
push_left_face,
|
|
||||||
push_right_face,
|
|
||||||
push_top_face,
|
|
||||||
set_current_texture,
|
set_current_texture,
|
||||||
|
set_face_culling,
|
||||||
Texture,
|
Texture,
|
||||||
|
use_texture,
|
||||||
view_projection,
|
view_projection,
|
||||||
} from "$/client/renderer/mod.ts";
|
white_tex,
|
||||||
import type { RenderLayer } from "$/common/everything_registry.ts";
|
} from "@/client/renderer/mod.ts";
|
||||||
import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts";
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
import { FACE_AXIS, FACE_NORMALS } from "$/client/workers/translucent_sort.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 { type Shape, shape_at } from "@/common/block_shapes.ts";
|
||||||
|
import type { BlockHitResult } from "@/client/level/client_level.ts";
|
||||||
|
import { FACE_GROUPS, UNALIGNED_GROUP } from "@/client/workers/chunk_messages.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";
|
||||||
const BREAKING_FACES = [
|
import { reachable_sections } from "./occlusion.ts";
|
||||||
push_back_face,
|
import { REGION_LAYERS, type RegionLayer, type RenderRegion } from "@/client/level/render_region.ts";
|
||||||
push_bottom_face,
|
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||||
push_front_face,
|
|
||||||
push_left_face,
|
|
||||||
push_right_face,
|
|
||||||
push_top_face,
|
|
||||||
];
|
|
||||||
|
|
||||||
// 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
|
||||||
|
draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
|
||||||
|
|
||||||
|
// entities drawn this frame, for the f3 performance window
|
||||||
|
#drawn_entities = 0;
|
||||||
|
|
||||||
|
get visible_sections() {
|
||||||
|
return this.#visible.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
get drawn_entities() {
|
||||||
|
return this.#drawn_entities;
|
||||||
|
}
|
||||||
|
|
||||||
// solid and cutout terrain, drawn before entities
|
// solid and cutout terrain, drawn before entities
|
||||||
render_opaque(level: ClientLevel, camera: Camera) {
|
render_opaque(level: ClientLevel, camera: Camera) {
|
||||||
|
profiler.section("chunk upkeep", () => this.#find_visible(level, camera));
|
||||||
|
set_current_texture(level.image.tex);
|
||||||
|
for (const layer of REGION_LAYERS) {
|
||||||
|
if (!this.draw[layer]) continue;
|
||||||
|
profiler.section(layer, () => {
|
||||||
|
for (const section of this.#visible) {
|
||||||
|
const mesh = section.meshes[layer];
|
||||||
|
if (mesh?.vertex_buffer) draw_facing_camera(layer, mesh.vertex_buffer, 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 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) {
|
||||||
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();
|
||||||
if (Object.keys(chunk.meshes).length > 0 && this.#in_view(chunk)) {
|
const reachable = this.#reachable_sections(level, camera);
|
||||||
this.#visible.push(chunk);
|
if (reachable) {
|
||||||
}
|
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) {
|
||||||
set_current_texture(level.image.tex);
|
this.#visible_chunks.add(section.chunk);
|
||||||
|
const in_region = this.#visible_regions.get(section.region);
|
||||||
for (const layer of ["solid", "cutout"] as const) {
|
if (in_region) in_region.push(section);
|
||||||
for (const chunk of this.#visible) {
|
else this.#visible_regions.set(section.region, [section]);
|
||||||
const mesh = chunk.meshes[layer];
|
|
||||||
if (mesh) {
|
|
||||||
draw_facing_camera(layer, mesh, camera);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
const distance_sq = (x: number, z: number) => {
|
if (!this.draw.translucent) return;
|
||||||
const dx = (x + 0.5) * CHUNK_SIZE - camera.x;
|
const sections = this.#visible
|
||||||
const dz = (z + 0.5) * CHUNK_SIZE - camera.z;
|
.filter((section) => section.meshes.translucent)
|
||||||
return dx * dx + dz * dz;
|
.map((section) => ({ mesh: section.meshes.translucent!, distance: distance_sq(section, camera) }))
|
||||||
};
|
|
||||||
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 but the one the camera is in
|
// every entity in view but the one the camera is in
|
||||||
render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) {
|
render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity | undefined, partial_tick: number) {
|
||||||
|
this.#drawn_entities = 0;
|
||||||
|
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
|
||||||
|
const posed: { player: RemotePlayer; pose: PlayerPose; tint: Vec3 }[] = [];
|
||||||
for (const entity of level.entities.values()) {
|
for (const entity of level.entities.values()) {
|
||||||
if (entity !== camera_entity && entity instanceof RemotePlayer) {
|
if (
|
||||||
|
entity !== camera_entity && entity instanceof RemotePlayer && this.#entity_in_view(entity, partial_tick)
|
||||||
|
) {
|
||||||
const skin = entity.skin ?? default_skin;
|
const skin = entity.skin ?? default_skin;
|
||||||
if (get_current_texture() !== skin.tex) {
|
use_texture(skin.tex);
|
||||||
flush_batch();
|
const tint = entity_tint(entity, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined);
|
||||||
set_current_texture(skin.tex);
|
const pose = player_pose(entity, partial_tick);
|
||||||
}
|
render_player(skin, pose, tint);
|
||||||
render_player(entity, skin, partial_tick);
|
posed.push({ player: entity, pose, tint });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
flush_batch();
|
flush_batch();
|
||||||
|
|
||||||
set_current_texture(level.image.tex);
|
set_current_texture(level.image.tex);
|
||||||
|
for (const { player, pose, tint } of posed) render_worn(player, pose, tint);
|
||||||
for (const entity of level.entities.values()) {
|
for (const entity of level.entities.values()) {
|
||||||
if (entity instanceof ItemEntity) {
|
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) {
|
}
|
||||||
|
}
|
||||||
|
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
// the cracks on the block being broken
|
// whether an entity's box, grown by ENTITY_CULL_MARGIN, is in view. entities are drawn on the cpu every frame, so
|
||||||
render_destroy_progress(game_mode: MultiPlayerGameMode) {
|
// the ones out of view are skipped
|
||||||
const block = game_mode.destroy_pos;
|
#entity_in_view(entity: Entity, partial_tick: number) {
|
||||||
if (!block) {
|
const { x, y, z } = entity.render_position(partial_tick);
|
||||||
|
const half = entity.width / 2 + ENTITY_CULL_MARGIN;
|
||||||
|
const in_view = this.frustum.intersects_box(
|
||||||
|
x - half,
|
||||||
|
y - ENTITY_CULL_MARGIN,
|
||||||
|
z - half,
|
||||||
|
x + half,
|
||||||
|
y + entity.height + ENTITY_CULL_MARGIN,
|
||||||
|
z + half,
|
||||||
|
);
|
||||||
|
if (in_view) this.#drawn_entities += 1;
|
||||||
|
return in_view;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
if (!this.draw.visuals) return;
|
||||||
|
level.visuals.frame(this.#visible_chunks, level.ticks + partial_tick);
|
||||||
|
flush_batch();
|
||||||
|
set_current_texture(level.image.tex);
|
||||||
|
draw_visuals(level.visuals, level.image, [camera.x, camera.y, camera.z]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the cracks on the block being broken, and on the ones machines are breaking, drawn over their models' faces like
|
||||||
|
// minecraft's crumbling overlay, so a slab or a plant cracks where it is and not on a whole cube around it
|
||||||
|
render_destroy_progress(level: ClientLevel, game_mode: MultiPlayerGameMode | undefined) {
|
||||||
|
for (const { x, y, z, stage } of level.break_progress.values()) this.#draw_cracks(level, x, y, z, stage);
|
||||||
|
const block = game_mode?.destroy_pos;
|
||||||
|
if (!game_mode || !block) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const progress = Math.max(0, Math.min(1, game_mode.destroy_progress / game_mode.destroy_time));
|
const progress = Math.max(0, Math.min(1, game_mode.destroy_progress / game_mode.destroy_time));
|
||||||
const stage = Math.round(progress * 8);
|
const stage = Math.round(progress * BREAK_STAGES);
|
||||||
if (Number.isNaN(stage)) {
|
if (!Number.isNaN(stage)) this.#draw_cracks(level, block.x, block.y, block.z, stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
#draw_cracks(level: ClientLevel, x: number, y: number, z: number, stage: number) {
|
||||||
|
const value = level.get_block_value(x, y, z);
|
||||||
|
const info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK);
|
||||||
|
if (!info) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const tex = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
|
const region = get_sprite_region(`cubi:break_${stage}`);
|
||||||
|
for (const quad of this.#destroy_quads(info, value)) {
|
||||||
|
push_decal_quad(tex, quad, x, y, z, region);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the edges of the shape of the block being looked at, like minecraft's block outline: thin dark lines that keep
|
||||||
|
// the same width on screen however far away it is
|
||||||
|
render_block_outline(level: ClientLevel, hit: BlockHitResult | undefined, camera: Camera) {
|
||||||
|
if (!hit) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const value = level.get_block_value(hit.x, hit.y, hit.z);
|
||||||
|
const info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK);
|
||||||
|
if (!info) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const tex = AssetManager.instance.get<Texture>("bworld:textures");
|
const previous = get_current_texture();
|
||||||
const region = get_sprite_region(`engine:break_${stage}`);
|
flush_batch();
|
||||||
for (const push_face of BREAKING_FACES) {
|
set_current_texture(white_tex!);
|
||||||
push_face(
|
const eye = [camera.x, camera.y, camera.z];
|
||||||
tex,
|
for (const edge of shape_edges(shape_at(info, value))) {
|
||||||
block.x,
|
push_line(
|
||||||
block.y,
|
[hit.x + edge[0], hit.y + edge[1], hit.z + edge[2]],
|
||||||
block.z,
|
[hit.x + edge[3], hit.y + edge[4], hit.z + edge[5]],
|
||||||
region.x,
|
eye,
|
||||||
region.y,
|
|
||||||
region.width,
|
|
||||||
region.height,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
flush_batch();
|
||||||
|
if (previous) set_current_texture(previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the block's model at a value, baked once
|
||||||
|
#destroy_quads(block: BlockRegistry, value: number): BakedQuad[] {
|
||||||
|
const key = looks_by_state(block) ? value : value & ID_MASK;
|
||||||
|
let quads = this.#baked.get(key);
|
||||||
|
if (!quads) {
|
||||||
|
quads = bake_block(block, value, Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")));
|
||||||
|
this.#baked.set(key, quads);
|
||||||
|
}
|
||||||
|
return quads;
|
||||||
|
}
|
||||||
|
|
||||||
|
#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
|
||||||
|
const ENTITY_CULL_MARGIN = 0.5;
|
||||||
|
|
||||||
|
// minecraft's outline is black at 40%
|
||||||
|
const OUTLINE_COLOR = [0, 0, 0, 0.4] as const;
|
||||||
|
// half the line's width for each block it is away from the camera, about a pixel on a 1080p screen
|
||||||
|
const OUTLINE_HALF_WIDTH = 0.0012;
|
||||||
|
// how far out the outline is from the block's faces, so they don't hide it
|
||||||
|
const OUTLINE_GROW = 0.002;
|
||||||
|
|
||||||
|
// the 12 edges of each box of a shape, grown out a little, as [x1, y1, z1, x2, y2, z2]. edges two boxes share are
|
||||||
|
// drawn once
|
||||||
|
export function shape_edges(shape: Shape): number[][] {
|
||||||
|
const edges = new Map<string, number[]>();
|
||||||
|
for (const box of shape) {
|
||||||
|
const min = [box[0] - OUTLINE_GROW, box[1] - OUTLINE_GROW, box[2] - OUTLINE_GROW];
|
||||||
|
const max = [box[3] + OUTLINE_GROW, box[4] + OUTLINE_GROW, box[5] + OUTLINE_GROW];
|
||||||
|
// along each axis, from each of the 4 corners of the box's face at the low end of it
|
||||||
|
for (let axis = 0; axis < 3; axis++) {
|
||||||
|
const [a, b] = [(axis + 1) % 3, (axis + 2) % 3];
|
||||||
|
for (const [ea, eb] of [[0, 0], [0, 1], [1, 0], [1, 1]]) {
|
||||||
|
const from = [0, 0, 0];
|
||||||
|
from[axis] = min[axis];
|
||||||
|
from[a] = ea ? max[a] : min[a];
|
||||||
|
from[b] = eb ? max[b] : min[b];
|
||||||
|
const to = [...from];
|
||||||
|
to[axis] = max[axis];
|
||||||
|
const edge = [...from, ...to];
|
||||||
|
edges.set(edge.map((v) => v.toFixed(4)).join(","), edge);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...edges.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
// a line from a to b as a thin quad turned to face the eye, as wide on screen at both ends
|
||||||
|
function push_line(a: number[], b: number[], eye: number[]) {
|
||||||
|
const direction = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||||
|
const length = Math.hypot(direction[0], direction[1], direction[2]);
|
||||||
|
if (length === 0) return;
|
||||||
|
const mid = [(a[0] + b[0]) / 2 - eye[0], (a[1] + b[1]) / 2 - eye[1], (a[2] + b[2]) / 2 - eye[2]];
|
||||||
|
// across the line and across the view
|
||||||
|
const side = [
|
||||||
|
direction[1] * mid[2] - direction[2] * mid[1],
|
||||||
|
direction[2] * mid[0] - direction[0] * mid[2],
|
||||||
|
direction[0] * mid[1] - direction[1] * mid[0],
|
||||||
|
];
|
||||||
|
const side_length = Math.hypot(side[0], side[1], side[2]);
|
||||||
|
if (side_length === 0) return;
|
||||||
|
|
||||||
|
// each end as wide as its distance needs, and a half width longer so lines meet at the corners
|
||||||
|
const end = (point: number[], sign: number) => {
|
||||||
|
const distance = Math.hypot(point[0] - eye[0], point[1] - eye[1], point[2] - eye[2]);
|
||||||
|
const half = OUTLINE_HALF_WIDTH * distance;
|
||||||
|
const p = point.map((v, i) => v + direction[i] / length * half * sign);
|
||||||
|
const s = side.map((v) => v / side_length * half);
|
||||||
|
return [p.map((v, i) => v - s[i]), p.map((v, i) => v + s[i])];
|
||||||
|
};
|
||||||
|
const [a0, a1] = end(a, -1);
|
||||||
|
const [b0, b1] = end(b, 1);
|
||||||
|
const [r, g, bl, alpha] = OUTLINE_COLOR;
|
||||||
|
const vertex = (p: number[]) => push_vertex(p[0], p[1], p[2], 0, 0, r, g, bl, alpha);
|
||||||
|
// both ways round, since which way it faces depends on where the eye is
|
||||||
|
for (const corners of [[a0, b0, b1, a1], [a1, b1, b0, a0]]) {
|
||||||
|
vertex(corners[0]);
|
||||||
|
vertex(corners[1]);
|
||||||
|
vertex(corners[2]);
|
||||||
|
vertex(corners[0]);
|
||||||
|
vertex(corners[2]);
|
||||||
|
vertex(corners[3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// how far out from the face the cracks are drawn, so they don't fight the block's own face for depth
|
||||||
|
const DECAL_OFFSET = 1e-3;
|
||||||
|
|
||||||
|
// a quad of a block's model with a texture laid over it the way it lies on a full block's face, like minecraft's
|
||||||
|
// SheetedDecalTextureGenerator: the texture doesn't stretch to the quad, the quad shows the part of it where it is
|
||||||
|
function push_decal_quad(
|
||||||
|
texture: Texture,
|
||||||
|
quad: BakedQuad,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
z: number,
|
||||||
|
region: { x: number; y: number; width: number; height: number },
|
||||||
|
) {
|
||||||
|
const p = quad.positions;
|
||||||
|
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 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 length = Math.hypot(normal[0], normal[1], normal[2]) || 1;
|
||||||
|
const offset = normal.map((n) => n / length * DECAL_OFFSET);
|
||||||
|
|
||||||
|
const pad = 0.5;
|
||||||
|
const corner = (k: number) => {
|
||||||
|
const [px, py, pz] = [p[k * 3], p[k * 3 + 1], p[k * 3 + 2]];
|
||||||
|
const [u, v] = decal_uv(quad.face, px, py, pz).map((t) => Math.min(Math.max(t, 0), 1));
|
||||||
|
push_vertex(
|
||||||
|
x + px + offset[0],
|
||||||
|
y + py + offset[1],
|
||||||
|
z + pz + offset[2],
|
||||||
|
(region.x + pad + u * (region.width - 2 * pad)) / texture.width,
|
||||||
|
(region.y + pad + v * (region.height - 2 * pad)) / texture.height,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
corner(0);
|
||||||
|
corner(1);
|
||||||
|
corner(2);
|
||||||
|
corner(0);
|
||||||
|
corner(2);
|
||||||
|
corner(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// where a point on a face is on the texture, 0 to 1, the same way default model uvs wrap a texture around the block
|
||||||
|
function decal_uv(face: number, x: number, y: number, z: number): [number, number] {
|
||||||
|
switch (face) {
|
||||||
|
case FACE_INDEX.top:
|
||||||
|
return [x, z];
|
||||||
|
case FACE_INDEX.bottom:
|
||||||
|
return [x, 1 - z];
|
||||||
|
case FACE_INDEX.south:
|
||||||
|
return [x, 1 - y];
|
||||||
|
case FACE_INDEX.north:
|
||||||
|
return [1 - x, 1 - y];
|
||||||
|
case FACE_INDEX.west:
|
||||||
|
return [z, 1 - y];
|
||||||
|
default:
|
||||||
|
return [1 - z, 1 - y];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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++) {
|
||||||
@@ -167,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(
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// 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
|
||||||
|
import type { EntityBoneJson, EntityCubeJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
|
|
||||||
|
export type Vec3 = [number, number, number];
|
||||||
|
|
||||||
|
// 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's
|
||||||
|
export type Matrix = number[];
|
||||||
|
|
||||||
|
export const IDENTITY: Matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
||||||
|
|
||||||
|
// bedrock models are mirrored on x from the engine's, like blockbench shows them: +x is the model's right
|
||||||
|
export function model_pivot(bone: EntityBoneJson): Vec3 {
|
||||||
|
return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]];
|
||||||
|
}
|
||||||
|
|
||||||
|
// what animation does to a bone, in the model's bedrock space like its own pivot and rotation: degrees added to its
|
||||||
|
// rotation, pixels it moves and how much it's scaled, around its pivot
|
||||||
|
export type BoneOffsets = { rotation: Vec3; position: Vec3; scale: Vec3 };
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
function turn_around([px, py, pz]: Vec3, degrees: Vec3): Matrix {
|
||||||
|
const [rx, ry, rz] = degrees.map((n) => n * Math.PI / 180);
|
||||||
|
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>();
|
||||||
|
for (const bone of model.bones) {
|
||||||
|
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);
|
||||||
|
bones.set(bone.name, matrix);
|
||||||
|
}
|
||||||
|
return bones;
|
||||||
|
}
|
||||||
|
|
||||||
|
// turns around pivot by x, then y, then z (radians). y turns like the whole model does and x like the player's head
|
||||||
|
// pitch
|
||||||
|
export function rotation_around(pivot: Vec3, rx: number, ry: number, rz: number): Matrix {
|
||||||
|
const [sx, cx] = [Math.sin(rx), Math.cos(rx)];
|
||||||
|
const [sy, cy] = [Math.sin(ry), Math.cos(ry)];
|
||||||
|
const [sz, cz] = [Math.sin(rz), Math.cos(rz)];
|
||||||
|
const rot_x = [1, 0, 0, 0, 0, cx, -sx, 0, 0, sx, cx, 0];
|
||||||
|
const rot_y = [cy, 0, sy, 0, 0, 1, 0, 0, -sy, 0, cy, 0];
|
||||||
|
const rot_z = [cz, -sz, 0, 0, sz, cz, 0, 0, 0, 0, 1, 0];
|
||||||
|
const [px, py, pz] = pivot;
|
||||||
|
const rotation = multiply(rot_z, multiply(rot_y, rot_x));
|
||||||
|
return multiply(
|
||||||
|
[1, 0, 0, px, 0, 1, 0, py, 0, 0, 1, pz],
|
||||||
|
multiply(rotation, [1, 0, 0, -px, 0, 1, 0, -py, 0, 0, 1, -pz]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a after b
|
||||||
|
export function multiply(a: Matrix, b: Matrix): Matrix {
|
||||||
|
const out: Matrix = [];
|
||||||
|
for (let row = 0; row < 3; row++) {
|
||||||
|
for (let col = 0; col < 4; col++) {
|
||||||
|
let sum = col === 3 ? a[row * 4 + 3] : 0;
|
||||||
|
for (let k = 0; k < 3; k++) sum += a[row * 4 + k] * b[k * 4 + col];
|
||||||
|
out.push(sum);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function apply(m: Matrix, x: number, y: number, z: number): Vec3 {
|
||||||
|
return [
|
||||||
|
m[0] * x + m[1] * y + m[2] * z + m[3],
|
||||||
|
m[4] * x + m[5] * y + m[6] * z + m[7],
|
||||||
|
m[8] * x + m[9] * y + m[10] * z + m[11],
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// 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
|
||||||
|
import type { Texture } from "@/client/renderer/mod.ts";
|
||||||
|
import type { SpriteRegion } from "@/common/constants.ts";
|
||||||
|
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
|
import { apply, type Matrix, multiply, own_matrix, type Vec3 } from "./model_math.ts";
|
||||||
|
import { push_box, type VertexSink } from "./player_renderer.ts";
|
||||||
|
|
||||||
|
// bones is each bone's matrix, see bone_matrices. to_world takes the model's pixels, after the bones are turned, to the
|
||||||
|
// world. the texture is region of the atlas, stretched to the model's texture size. only picks the bones drawn, all of
|
||||||
|
// them when not given. emit gets the vertices, the batch by default
|
||||||
|
export function push_model(
|
||||||
|
model: EntityModelJson,
|
||||||
|
bones: Map<string, Matrix>,
|
||||||
|
atlas: Texture,
|
||||||
|
region: SpriteRegion,
|
||||||
|
to_world: (x: number, y: number, z: number) => Vec3,
|
||||||
|
tint?: Vec3,
|
||||||
|
only?: (bone: EntityBoneJson) => boolean,
|
||||||
|
emit?: VertexSink,
|
||||||
|
) {
|
||||||
|
const to_uv = (u: number, v: number): [number, number] => [
|
||||||
|
(region.x + u * region.width / model.texture_width) / atlas.width,
|
||||||
|
(region.y + v * region.height / model.texture_height) / atlas.height,
|
||||||
|
];
|
||||||
|
for (const bone of model.bones) {
|
||||||
|
if (only && !only(bone)) continue;
|
||||||
|
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 [ox, oy, oz] = cube.origin;
|
||||||
|
const [w, h, d] = cube.size;
|
||||||
|
// bedrock models are mirrored on x from the engine's, like blockbench shows them: +x is the model's right
|
||||||
|
const low: Vec3 = [-(ox + w) - inflate, oy - inflate, oz - inflate];
|
||||||
|
const high: Vec3 = [-ox + inflate, oy + h + inflate, oz + d + inflate];
|
||||||
|
push_box(cube.size, low, high, cube.uv, to_uv, transform, tint, emit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
import type { Camera } from "@/client/camera.ts";
|
||||||
|
import type { Entity } from "@/client/entity/entity.ts";
|
||||||
|
import type { ClientLevel } from "@/client/level/client_level.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";
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
// from the top of the head to the bottom of the plate
|
||||||
|
const GAP = 0.3;
|
||||||
|
// further than this they're not drawn, like minecraft's 64 blocks
|
||||||
|
const MAX_DISTANCE = 64;
|
||||||
|
// the plate's height around the text in font pixels: from a pixel above the letters to under their descenders
|
||||||
|
const PLATE_TOP = -1;
|
||||||
|
const PLATE_BOTTOM = 14;
|
||||||
|
const PLATE_PADDING = 2;
|
||||||
|
const PLATE_COLOR = [0, 0, 0, 0.25];
|
||||||
|
const TEXT_COLOR = [1, 1, 1, 1];
|
||||||
|
// the text sits this far in front of its plate, towards the camera, so they don't z-fight
|
||||||
|
const TEXT_LIFT = 0.002;
|
||||||
|
|
||||||
|
// names over other players' heads, always facing the camera like minecraft's. drawn after translucent terrain since
|
||||||
|
// the plate is see through. they're full bright, so they can be read in the dark
|
||||||
|
export function render_nameplates(
|
||||||
|
level: ClientLevel,
|
||||||
|
camera: Camera,
|
||||||
|
camera_entity: Entity | undefined,
|
||||||
|
partial_tick: number,
|
||||||
|
) {
|
||||||
|
const cos_yaw = Math.cos(camera.yaw);
|
||||||
|
const sin_yaw = Math.sin(camera.yaw);
|
||||||
|
const cos_pitch = Math.cos(camera.pitch);
|
||||||
|
const sin_pitch = Math.sin(camera.pitch);
|
||||||
|
// the camera's right, up and back in the world, see update_camera in renderer/core.ts
|
||||||
|
const right: [number, number, number] = [cos_yaw, 0, -sin_yaw];
|
||||||
|
const up: [number, number, number] = [sin_yaw * sin_pitch, cos_pitch, cos_yaw * sin_pitch];
|
||||||
|
const back: [number, number, number] = [sin_yaw * cos_pitch, -sin_pitch, cos_yaw * cos_pitch];
|
||||||
|
|
||||||
|
for (const entity of level.entities.values()) {
|
||||||
|
if (entity === camera_entity || !(entity instanceof RemotePlayer) || !entity.name) continue;
|
||||||
|
const pos = entity.render_position(partial_tick);
|
||||||
|
const dx = pos.x - camera.x;
|
||||||
|
const dy = pos.y - camera.y;
|
||||||
|
const dz = pos.z - camera.z;
|
||||||
|
if (dx * dx + dy * dy + dz * dz > MAX_DISTANCE * MAX_DISTANCE) continue;
|
||||||
|
|
||||||
|
// the plane's origin is the middle of the plate's top
|
||||||
|
const plate_height = (PLATE_BOTTOM - PLATE_TOP) * SCALE;
|
||||||
|
const top = pos.y + entity.height + GAP + plate_height;
|
||||||
|
const origin: [number, number, number] = [pos.x, top, pos.z];
|
||||||
|
const plate: Plane3d = { origin, right, up };
|
||||||
|
const text: Plane3d = {
|
||||||
|
origin: [origin[0] + back[0] * TEXT_LIFT, origin[1] + back[1] * TEXT_LIFT, origin[2] + back[2] * TEXT_LIFT],
|
||||||
|
right,
|
||||||
|
up,
|
||||||
|
};
|
||||||
|
|
||||||
|
const width = measure_text(entity.name, SCALE);
|
||||||
|
const padding = PLATE_PADDING * SCALE;
|
||||||
|
draw_rect_3d(plate, -width / 2 - padding, 0, width + padding * 2, plate_height, PLATE_COLOR);
|
||||||
|
draw_text_3d(text, entity.name, -width / 2, -PLATE_TOP * SCALE, SCALE, TEXT_COLOR);
|
||||||
|
}
|
||||||
|
flush_batch();
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
|
|
||||||
|
// 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
|
||||||
|
import { PLAYER_HEIGHT, PLAYER_SWIM_HEIGHT } from "@/common/constants.ts";
|
||||||
|
import { PLAYER_PARTS, type WornProperties } from "@/common/everything_registry.ts";
|
||||||
|
import type { EntityBoneJson, EntityModelJson } from "@/common/mod_data.ts";
|
||||||
|
import { apply, IDENTITY, type Matrix, multiply, rotation_around, type Vec3 } from "./model_math.ts";
|
||||||
|
|
||||||
|
export type PartName = typeof PLAYER_PARTS[number];
|
||||||
|
|
||||||
|
// minecraft's player model is 32 skin pixels tall, it's scaled to the player's height
|
||||||
|
export const PIXEL = PLAYER_HEIGHT / 32;
|
||||||
|
|
||||||
|
// a part of minecraft's player model, like its ModelParts. sizes and positions are in skin pixels, the model faces
|
||||||
|
// -z with its right side towards +x and its feet at 0. each part is a box from `from` to `from + size` around the
|
||||||
|
// pivot it turns on, with its texture at `texture` in a 1.8 (64x64) skin and a second layer drawn a bit bigger
|
||||||
|
export interface ModelPart {
|
||||||
|
name: PartName;
|
||||||
|
size: Vec3;
|
||||||
|
pivot: Vec3;
|
||||||
|
from: Vec3;
|
||||||
|
texture: [number, number];
|
||||||
|
overlay: [number, number];
|
||||||
|
inflate: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PARTS: ModelPart[] = [
|
||||||
|
{
|
||||||
|
name: "head",
|
||||||
|
size: [8, 8, 8],
|
||||||
|
pivot: [0, 24, 0],
|
||||||
|
from: [-4, 0, -4],
|
||||||
|
texture: [0, 0],
|
||||||
|
overlay: [32, 0],
|
||||||
|
inflate: 0.5,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "body",
|
||||||
|
size: [8, 12, 4],
|
||||||
|
pivot: [0, 12, 0],
|
||||||
|
from: [-4, 0, -2],
|
||||||
|
texture: [16, 16],
|
||||||
|
overlay: [16, 32],
|
||||||
|
inflate: 0.25,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "right_arm",
|
||||||
|
size: [4, 12, 4],
|
||||||
|
pivot: [5, 22, 0],
|
||||||
|
from: [-1, -10, -2],
|
||||||
|
texture: [40, 16],
|
||||||
|
overlay: [40, 32],
|
||||||
|
inflate: 0.25,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "left_arm",
|
||||||
|
size: [4, 12, 4],
|
||||||
|
pivot: [-5, 22, 0],
|
||||||
|
from: [-3, -10, -2],
|
||||||
|
texture: [32, 48],
|
||||||
|
overlay: [48, 48],
|
||||||
|
inflate: 0.25,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "right_leg",
|
||||||
|
size: [4, 12, 4],
|
||||||
|
pivot: [2, 12, 0],
|
||||||
|
from: [-2, -12, -2],
|
||||||
|
texture: [0, 16],
|
||||||
|
overlay: [0, 32],
|
||||||
|
inflate: 0.25,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "left_leg",
|
||||||
|
size: [4, 12, 4],
|
||||||
|
pivot: [-2, 12, 0],
|
||||||
|
from: [-2, -12, -2],
|
||||||
|
texture: [16, 48],
|
||||||
|
overlay: [0, 48],
|
||||||
|
inflate: 0.25,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// slim (alex) skins have 3 pixel wide arms, half a pixel lower, like minecraft's PlayerModel with slim set
|
||||||
|
const SLIM_ARMS: ModelPart[] = [
|
||||||
|
{
|
||||||
|
name: "right_arm",
|
||||||
|
size: [3, 12, 4],
|
||||||
|
pivot: [5, 21.5, 0],
|
||||||
|
from: [-1, -10, -2],
|
||||||
|
texture: [40, 16],
|
||||||
|
overlay: [40, 32],
|
||||||
|
inflate: 0.25,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "left_arm",
|
||||||
|
size: [3, 12, 4],
|
||||||
|
pivot: [-5, 21.5, 0],
|
||||||
|
from: [-2, -10, -2],
|
||||||
|
texture: [32, 48],
|
||||||
|
overlay: [48, 48],
|
||||||
|
inflate: 0.25,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
export const SLIM_PARTS = PARTS.map((part) => SLIM_ARMS.find((arm) => arm.name === part.name) ?? part);
|
||||||
|
|
||||||
|
// the right arm of the wide or slim model, for drawing it on its own in first person
|
||||||
|
export function right_arm(slim: boolean): ModelPart {
|
||||||
|
return (slim ? SLIM_PARTS : PARTS).find((part) => part.name === "right_arm")!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what a player's pose comes from, see Player and Entity.walk_animation
|
||||||
|
export interface PoseInput {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
z: number;
|
||||||
|
yaw: number;
|
||||||
|
pitch: number;
|
||||||
|
walk: { position: number; speed: number };
|
||||||
|
slim: boolean;
|
||||||
|
// how far over they've tipped and which way the body lies, see Player.update_swim_animation. none is standing
|
||||||
|
swim?: { amount: number; pitch: number };
|
||||||
|
// ticks, for the arms drifting while they swim in place
|
||||||
|
time?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// where a player is drawn this frame: each part's matrix, which turns its points (in skin pixels, around the model's
|
||||||
|
// feet, like a bone's) the way the part is turned, then the root's, which turns the whole model (lying flat to swim),
|
||||||
|
// and where the model is
|
||||||
|
export interface PlayerPose {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
z: number;
|
||||||
|
yaw: number;
|
||||||
|
slim: boolean;
|
||||||
|
root: Matrix;
|
||||||
|
parts: Record<PartName, Matrix>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the model lies flat around the middle of its length, moved down to the middle of the swimming box
|
||||||
|
const SWIM_PIVOT: Vec3 = [0, 16, 0];
|
||||||
|
const SWIM_DROP = PLAYER_SWIM_HEIGHT / 2 / PIXEL - SWIM_PIVOT[1];
|
||||||
|
// the crawl: arms go around this much per walk step (once a second swimming at full speed), legs flutter this fast and this far
|
||||||
|
const STROKE_RATE = 0.3;
|
||||||
|
const FLUTTER_RATE = 1.2;
|
||||||
|
const FLUTTER = 0.3;
|
||||||
|
// arms out a little so they go around beside the head, not through it
|
||||||
|
const STROKE_SPREAD = 0.15;
|
||||||
|
// swimming in place, the arms and legs drift slowly, about every 2 seconds
|
||||||
|
const DRIFT_RATE = 0.15;
|
||||||
|
const DRIFT = 0.25;
|
||||||
|
|
||||||
|
export function pose_at(input: PoseInput): PlayerPose {
|
||||||
|
// limbs swing opposite to each other, like minecraft's HumanoidModel.setupAnim
|
||||||
|
const swing = Math.cos(input.walk.position * 0.6662) * input.walk.speed;
|
||||||
|
const angles: Record<PartName, number> = {
|
||||||
|
head: input.pitch,
|
||||||
|
body: 0,
|
||||||
|
right_arm: -swing,
|
||||||
|
left_arm: swing,
|
||||||
|
right_leg: swing * 1.4,
|
||||||
|
left_leg: -swing * 1.4,
|
||||||
|
};
|
||||||
|
const spread: Record<PartName, number> = { head: 0, body: 0, right_arm: 0, left_arm: 0, right_leg: 0, left_leg: 0 };
|
||||||
|
let root = IDENTITY;
|
||||||
|
const swim = input.swim?.amount ?? 0;
|
||||||
|
if (swim > 0) {
|
||||||
|
// forward onto its front, then further for going down or less for going up
|
||||||
|
const tilt = swim * (Math.PI / 2 - input.swim!.pitch);
|
||||||
|
root = multiply([1, 0, 0, 0, 0, 1, 0, swim * SWIM_DROP, 0, 0, 1, 0], rotation_around(SWIM_PIVOT, -tilt, 0, 0));
|
||||||
|
// the head turns back up as much, so it faces where they look
|
||||||
|
angles.head = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, input.pitch + tilt));
|
||||||
|
const speed = input.walk.speed;
|
||||||
|
const drift = Math.sin((input.time ?? 0) * DRIFT_RATE) * DRIFT;
|
||||||
|
// arms go around half a turn apart, forward over the head and back under, like walking's -swing
|
||||||
|
const stroke = -input.walk.position * STROKE_RATE;
|
||||||
|
const arm = (offset: number) => drift * (1 - speed) + wrap(stroke + offset - drift) * speed;
|
||||||
|
const flutter = Math.cos(input.walk.position * FLUTTER_RATE) * FLUTTER * speed + drift * (1 - speed);
|
||||||
|
const swimming: Partial<Record<PartName, number>> = {
|
||||||
|
right_arm: arm(0),
|
||||||
|
left_arm: arm(Math.PI),
|
||||||
|
right_leg: flutter,
|
||||||
|
left_leg: -flutter,
|
||||||
|
};
|
||||||
|
for (const [name, angle] of Object.entries(swimming) as [PartName, number][]) {
|
||||||
|
angles[name] += (angle - angles[name]) * swim;
|
||||||
|
}
|
||||||
|
spread.right_arm = STROKE_SPREAD * swim;
|
||||||
|
spread.left_arm = -STROKE_SPREAD * swim;
|
||||||
|
}
|
||||||
|
const parts = {} as Record<PartName, Matrix>;
|
||||||
|
for (const part of input.slim ? SLIM_PARTS : PARTS) {
|
||||||
|
parts[part.name] = rotation_around(part.pivot, angles[part.name], 0, spread[part.name]);
|
||||||
|
}
|
||||||
|
return { x: input.x, y: input.y, z: input.z, yaw: input.yaw, slim: input.slim, root, parts };
|
||||||
|
}
|
||||||
|
|
||||||
|
// an angle the same way around, between -pi and pi
|
||||||
|
function wrap(angle: number): number {
|
||||||
|
return angle - 2 * Math.PI * Math.round(angle / (2 * Math.PI));
|
||||||
|
}
|
||||||
|
|
||||||
|
// from the model's skin pixels to the world: turned by the root, scaled to the player's height, then turned to their
|
||||||
|
// yaw
|
||||||
|
export function pose_to_world(pose: PlayerPose): (x: number, y: number, z: number) => Vec3 {
|
||||||
|
const [sin, cos] = [Math.sin(pose.yaw), Math.cos(pose.yaw)];
|
||||||
|
return (px, py, pz) => {
|
||||||
|
const [mx, my, mz] = apply(pose.root, px, py, pz).map((n) => n * PIXEL);
|
||||||
|
return [pose.x + mx * cos + mz * sin, pose.y + my, pose.z - mx * sin + mz * cos];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// a point of a part, around its pivot like ModelPart.from, where it is in the pose, in the model's pixels
|
||||||
|
export function part_point(pose: PlayerPose, part: ModelPart, x: number, y: number, z: number): Vec3 {
|
||||||
|
const [px, py, pz] = part.pivot;
|
||||||
|
return apply(pose.parts[part.name], x + px, y + py, z + pz);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the model and texture an item is drawn with on a player with or without slim arms
|
||||||
|
export function worn_look(worn: WornProperties, slim: boolean): { model: string; texture: string } {
|
||||||
|
if (slim && worn.slim_model) return { model: worn.slim_model, texture: worn.slim_texture ?? worn.texture };
|
||||||
|
return { model: worn.model, texture: (slim && worn.slim_texture) || worn.texture };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function is_part(name: string): name is PartName {
|
||||||
|
return (PLAYER_PARTS as readonly string[]).includes(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// whether a bone is that part or under it, so it goes where the part goes
|
||||||
|
export function on_part(model: EntityModelJson, bone: EntityBoneJson, part: PartName): boolean {
|
||||||
|
for (let at: EntityBoneJson | undefined = bone; at; at = model.bones.find((b) => b.name === at!.parent)) {
|
||||||
|
if (at.name === part) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a worn model's bones: one named like a player part turns with it, around the part's pivot. the rest follow their
|
||||||
|
// parent, or stay with the body
|
||||||
|
export function worn_bone_pose(pose: PlayerPose): (bone: EntityBoneJson) => Matrix {
|
||||||
|
return (bone) => is_part(bone.name) ? pose.parts[bone.name] : IDENTITY;
|
||||||
|
}
|
||||||
@@ -1,221 +1,172 @@
|
|||||||
import { PLAYER_HEIGHT } from "$/common/constants.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import type { Player } from "$/client/entity/player.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { push_vertex, type Texture } from "$/client/renderer/mod.ts";
|
|
||||||
|
|
||||||
export type Vec3 = [number, number, number];
|
import type { Player } from "@/client/entity/player.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 ModelPart,
|
||||||
|
part_point,
|
||||||
|
PARTS,
|
||||||
|
type PlayerPose,
|
||||||
|
pose_at,
|
||||||
|
pose_to_world,
|
||||||
|
SLIM_PARTS,
|
||||||
|
} from "./player_model.ts";
|
||||||
|
|
||||||
|
export type { Vec3 };
|
||||||
|
|
||||||
|
// how much of each color is left while something flashes red after being hurt, like minecraft's
|
||||||
|
export const HURT_TINT: Vec3 = [1, 0.6, 0.6];
|
||||||
|
|
||||||
// minecraft's player model is 32 skin pixels tall, it's scaled to the player's height
|
|
||||||
const PIXEL = PLAYER_HEIGHT / 32;
|
|
||||||
// keeps nearest sampling from picking the texel next to a face's edge
|
// keeps nearest sampling from picking the texel next to a face's edge
|
||||||
const UV_INSET = 0.01;
|
const UV_INSET = 0.01;
|
||||||
|
|
||||||
// a part of minecraft's player model, like its ModelParts. sizes and positions are in skin pixels, the model faces
|
|
||||||
// -z with its right side towards +x and its feet at 0. each part is a box from `from` to `from + size` around the
|
|
||||||
// pivot it turns on, with its texture at `texture` in a 1.8 (64x64) skin and a second layer drawn a bit bigger
|
|
||||||
interface ModelPart {
|
|
||||||
name: "head" | "body" | "right_arm" | "left_arm" | "right_leg" | "left_leg";
|
|
||||||
size: Vec3;
|
|
||||||
pivot: Vec3;
|
|
||||||
from: Vec3;
|
|
||||||
texture: [number, number];
|
|
||||||
overlay: [number, number];
|
|
||||||
inflate: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const PARTS: ModelPart[] = [
|
|
||||||
{
|
|
||||||
name: "head",
|
|
||||||
size: [8, 8, 8],
|
|
||||||
pivot: [0, 24, 0],
|
|
||||||
from: [-4, 0, -4],
|
|
||||||
texture: [0, 0],
|
|
||||||
overlay: [32, 0],
|
|
||||||
inflate: 0.5,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "body",
|
|
||||||
size: [8, 12, 4],
|
|
||||||
pivot: [0, 12, 0],
|
|
||||||
from: [-4, 0, -2],
|
|
||||||
texture: [16, 16],
|
|
||||||
overlay: [16, 32],
|
|
||||||
inflate: 0.25,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "right_arm",
|
|
||||||
size: [4, 12, 4],
|
|
||||||
pivot: [5, 22, 0],
|
|
||||||
from: [-1, -10, -2],
|
|
||||||
texture: [40, 16],
|
|
||||||
overlay: [40, 32],
|
|
||||||
inflate: 0.25,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "left_arm",
|
|
||||||
size: [4, 12, 4],
|
|
||||||
pivot: [-5, 22, 0],
|
|
||||||
from: [-3, -10, -2],
|
|
||||||
texture: [32, 48],
|
|
||||||
overlay: [48, 48],
|
|
||||||
inflate: 0.25,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "right_leg",
|
|
||||||
size: [4, 12, 4],
|
|
||||||
pivot: [2, 12, 0],
|
|
||||||
from: [-2, -12, -2],
|
|
||||||
texture: [0, 16],
|
|
||||||
overlay: [0, 32],
|
|
||||||
inflate: 0.25,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "left_leg",
|
|
||||||
size: [4, 12, 4],
|
|
||||||
pivot: [-2, 12, 0],
|
|
||||||
from: [-2, -12, -2],
|
|
||||||
texture: [16, 48],
|
|
||||||
overlay: [0, 48],
|
|
||||||
inflate: 0.25,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// slim (alex) skins have 3 pixel wide arms, half a pixel lower, like minecraft's PlayerModel with slim set
|
|
||||||
const SLIM_ARMS: ModelPart[] = [
|
|
||||||
{
|
|
||||||
name: "right_arm",
|
|
||||||
size: [3, 12, 4],
|
|
||||||
pivot: [5, 21.5, 0],
|
|
||||||
from: [-1, -10, -2],
|
|
||||||
texture: [40, 16],
|
|
||||||
overlay: [40, 32],
|
|
||||||
inflate: 0.25,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "left_arm",
|
|
||||||
size: [3, 12, 4],
|
|
||||||
pivot: [-5, 21.5, 0],
|
|
||||||
from: [-2, -10, -2],
|
|
||||||
texture: [32, 48],
|
|
||||||
overlay: [48, 48],
|
|
||||||
inflate: 0.25,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
const SLIM_PARTS = PARTS.map((part) => SLIM_ARMS.find((arm) => arm.name === part.name) ?? part);
|
|
||||||
|
|
||||||
// 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,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
// a face's corners as two triangles
|
||||||
|
const QUAD_CORNERS = [0, 1, 2, 0, 2, 3];
|
||||||
|
|
||||||
// a player with a minecraft skin, like minecraft's PlayerRenderer. the skin has to be the current texture
|
// how a player is posed this frame, for drawing them and what they wear
|
||||||
export function render_player(player: Player, skin: Texture, partial_tick: number) {
|
export function player_pose(player: Player, partial_tick: number): PlayerPose {
|
||||||
const { x, y, z } = player.render_position(partial_tick);
|
const { x, y, z } = player.render_position(partial_tick);
|
||||||
const yaw_sin = Math.sin(player.yaw);
|
const { yaw, pitch, slim } = player;
|
||||||
const yaw_cos = Math.cos(player.yaw);
|
|
||||||
|
|
||||||
// limbs swing opposite to each other, like minecraft's HumanoidModel.setupAnim
|
|
||||||
const walk = player.walk_animation(partial_tick);
|
const walk = player.walk_animation(partial_tick);
|
||||||
const swing = Math.cos(walk.position * 0.6662) * walk.speed;
|
const swim = player.render_swim(partial_tick);
|
||||||
const angles = {
|
return pose_at({ x, y, z, yaw, pitch, slim, walk, swim, time: player.level.time + partial_tick });
|
||||||
head: player.pitch,
|
}
|
||||||
body: 0,
|
|
||||||
right_arm: -swing,
|
|
||||||
left_arm: swing,
|
|
||||||
right_leg: swing * 1.4,
|
|
||||||
left_leg: -swing * 1.4,
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const part of player.slim ? SLIM_PARTS : PARTS) {
|
// a player with a minecraft skin, like minecraft's PlayerRenderer. the skin has to be the current texture. tint
|
||||||
const sin = Math.sin(angles[part.name]);
|
// multiplies its colors, for flashing red when hurt
|
||||||
const cos = Math.cos(angles[part.name]);
|
export function render_player(skin: Texture, pose: PlayerPose, tint?: Vec3) {
|
||||||
const [pivot_x, pivot_y, pivot_z] = part.pivot;
|
const to_world = pose_to_world(pose);
|
||||||
// turns around the pivot's x axis, then the whole model turns to the player's yaw
|
for (const part of pose.slim ? SLIM_PARTS : PARTS) {
|
||||||
const transform = (px: number, py: number, pz: number): Vec3 => {
|
// from points around the part's pivot to where they are in the world
|
||||||
const mx = (px + pivot_x) * PIXEL;
|
const transform = (x: number, y: number, z: number) => to_world(...part_point(pose, part, x, y, z));
|
||||||
const my = (py * cos - pz * sin + pivot_y) * PIXEL;
|
push_cube(skin, part, part.texture, 0, transform, tint);
|
||||||
const mz = (py * sin + pz * cos + pivot_z) * PIXEL;
|
push_cube(skin, part, part.overlay, part.inflate, transform, tint);
|
||||||
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
|
|
||||||
};
|
|
||||||
push_cube(skin, part, part.texture, 0, transform);
|
|
||||||
push_cube(skin, part, part.overlay, part.inflate, transform);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function push_cube(
|
// 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
|
||||||
|
export type VertexSink = typeof push_vertex;
|
||||||
|
|
||||||
|
// one layer of a part's box, its texture at uv and grown by inflate. transform takes points around the part's pivot
|
||||||
|
export function push_cube(
|
||||||
skin: Texture,
|
skin: Texture,
|
||||||
part: ModelPart,
|
part: ModelPart,
|
||||||
uv: [number, number],
|
uv: [number, number],
|
||||||
inflate: number,
|
inflate: number,
|
||||||
transform: (x: number, y: number, z: number) => Vec3,
|
transform: (x: number, y: number, z: number) => Vec3,
|
||||||
|
tint?: Vec3,
|
||||||
|
emit: VertexSink = push_vertex,
|
||||||
) {
|
) {
|
||||||
const low = part.from.map((n) => n - inflate) as Vec3;
|
const low = part.from.map((n) => n - inflate) as Vec3;
|
||||||
const high = part.from.map((n, i) => n + part.size[i] + inflate) as Vec3;
|
const high = part.from.map((n, i) => n + part.size[i] + inflate) as Vec3;
|
||||||
push_box(part.size, low, high, uv, (u, v) => [u / skin.width, v / skin.height], transform);
|
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],
|
||||||
|
emit: VertexSink = push_vertex,
|
||||||
) {
|
) {
|
||||||
const [w, h, d] = size;
|
const [w, h, d] = size;
|
||||||
|
// the box's 8 corners, transformed once each rather than once per vertex. indexed by x * 4 + y * 2 + z, 0 for
|
||||||
|
// the low end and 1 for the high one
|
||||||
|
const points: Vec3[] = [];
|
||||||
|
for (let i = 0; i < 8; i++) {
|
||||||
|
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;
|
||||||
const [r, g, b] = tint.map((c) => c * face.shade);
|
// 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 g = tint[1] * face.shade;
|
||||||
|
const b = tint[2] * face.shade;
|
||||||
|
|
||||||
for (const i of [0, 1, 2, 0, 2, 3]) {
|
for (const i of QUAD_CORNERS) {
|
||||||
const [cx, cy, cz, cu, cv] = face.corners[i];
|
const corner = face.corners[i];
|
||||||
const [px, py, pz] = transform(
|
const point = points[corner[0] * 4 + corner[1] * 2 + corner[2]];
|
||||||
cx ? high[0] : low[0],
|
emit(point[0], point[1], point[2], corner[3] ? u1 : u0, corner[4] ? v1 : v0, r, g, b, 1);
|
||||||
cy ? high[1] : low[1],
|
|
||||||
cz ? high[2] : low[2],
|
|
||||||
);
|
|
||||||
push_vertex(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, r, g, b, 1);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,40 @@
|
|||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
import { get_sprite_region } from "$/client/sprites.ts";
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
|
||||||
import { AssetManager } from "$/client/assets.ts";
|
import { mat4, vec3 } from "gl-matrix";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { SLOT_SIZE } from "@/common/constants.ts";
|
||||||
import { item_texture } from "$/common/utils.ts";
|
import { get_sprite_region } from "@/client/sprites.ts";
|
||||||
import { block_item_texture, cube_face_texture, cube_face_tint } from "$/common/block_models.ts";
|
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import { AssetManager } from "@/client/assets.ts";
|
||||||
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
|
import type { FluidVariant } from "@/common/mod_api/shared.ts";
|
||||||
|
import { item_texture } from "@/common/utils.ts";
|
||||||
|
import {
|
||||||
|
cube_face_texture,
|
||||||
|
cube_face_tint,
|
||||||
|
type DisplayTransform,
|
||||||
|
ITEM_FACE_SHADE,
|
||||||
|
item_tint,
|
||||||
|
} from "@/common/block_models.ts";
|
||||||
|
import {
|
||||||
|
display_matrix,
|
||||||
|
fluid_look,
|
||||||
|
item_block,
|
||||||
|
item_layers,
|
||||||
|
item_model_of,
|
||||||
|
type ItemModel,
|
||||||
|
sprite_u,
|
||||||
|
sprite_v,
|
||||||
|
} from "./item_renderer.ts";
|
||||||
import {
|
import {
|
||||||
draw_rect,
|
draw_rect,
|
||||||
draw_text,
|
draw_text,
|
||||||
draw_texture_region,
|
draw_texture_region,
|
||||||
draw_texture_region_skewed,
|
draw_texture_region_skewed,
|
||||||
|
push_vertex,
|
||||||
Texture,
|
Texture,
|
||||||
} from "$/client/renderer/mod.ts";
|
use_texture,
|
||||||
|
} 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
|
||||||
@@ -64,24 +87,26 @@ export function draw_nine_slice(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function draw_item(item: ItemStack, x: number, y: number) {
|
// show_count is for drawing an item where its count means nothing, like one shown on a screen
|
||||||
|
export function draw_item(item: ItemStack, x: number, y: number, show_count = item.max_amount !== 1) {
|
||||||
const item_info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
const item_info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||||
|
|
||||||
if (!item_info) {
|
if (!item_info) {
|
||||||
throw Error(`Didn't find item registry for '${item.type_id}'`);
|
throw Error(`Didn't find item registry for '${item.type_id}'`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const block_info = item_info.block_id
|
|
||||||
? EverythingRegistry.get<BlockRegistry>("blocks", item_info.block_id)
|
|
||||||
: undefined;
|
|
||||||
// blocks that aren't cubes, like plants, show a flat sprite
|
// blocks that aren't cubes, like plants, show a flat sprite
|
||||||
if (block_info && block_item_texture(block_info) === undefined) {
|
const model = item_model_of(item);
|
||||||
|
const block_info = item_block(item);
|
||||||
|
if (model) {
|
||||||
|
draw_item_model(model, x, y);
|
||||||
|
} else if (block_info) {
|
||||||
draw_item_block(block_info, x, y);
|
draw_item_block(block_info, x, y);
|
||||||
} else {
|
} else {
|
||||||
draw_item_item(item, item_info, x, y);
|
draw_item_item(item, item_info, x, y);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (item.max_amount !== 1) {
|
if (show_count) {
|
||||||
draw_text(
|
draw_text(
|
||||||
String(item.amount),
|
String(item.amount),
|
||||||
x + SLOT_SIZE + 2 - 11 * 2,
|
x + SLOT_SIZE + 2 - 11 * 2,
|
||||||
@@ -114,27 +139,145 @@ export function draw_item(item: ItemStack, x: number, y: number) {
|
|||||||
|
|
||||||
// ey its not a bad name
|
// ey its not a bad name
|
||||||
function draw_item_item(item: ItemStack, item_info: ItemRegistry, x: number, y: number) {
|
function draw_item_item(item: ItemStack, item_info: ItemRegistry, x: number, y: number) {
|
||||||
const texture_id = item_texture(item, item_info);
|
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(
|
||||||
|
AssetManager.instance.get("cubi:textures"),
|
||||||
|
sprite_region.x,
|
||||||
|
sprite_region.y,
|
||||||
|
sprite_region.width,
|
||||||
|
sprite_region.height,
|
||||||
|
x + 3,
|
||||||
|
y + 3,
|
||||||
|
SLOT_SIZE - 6,
|
||||||
|
SLOT_SIZE - 6,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
r,
|
||||||
|
g,
|
||||||
|
b,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
draw(item_texture(item, item_info));
|
||||||
|
for (const layer of item_layers(item)) draw(layer.texture, layer.color);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a fluid as a slot shows it, its texture tinted in its color over the slot's inside where an item's sprite goes.
|
||||||
|
// filled (0 to 1) is how much of it there is from the bottom up, like a tank's level: the texture is cut, not squashed
|
||||||
|
export function draw_fluid(fluid: FluidVariant, x: number, y: number, filled = 1) {
|
||||||
|
const { texture, tint: [r, g, b] } = fluid_look(fluid);
|
||||||
|
// nothing for NaN too, like amount / capacity before there's a capacity
|
||||||
|
const done = filled > 0 ? Math.min(1, filled) : 0;
|
||||||
|
if (done === 0) return;
|
||||||
|
const region = get_sprite_region(texture);
|
||||||
|
const size = SLOT_SIZE - 6;
|
||||||
draw_texture_region(
|
draw_texture_region(
|
||||||
AssetManager.instance.get("bworld:textures"),
|
AssetManager.instance.get("cubi:textures"),
|
||||||
sprite_region.x,
|
region.x,
|
||||||
sprite_region.y,
|
region.y + region.height * (1 - done),
|
||||||
sprite_region.width,
|
region.width,
|
||||||
sprite_region.height,
|
region.height * done,
|
||||||
x + 3,
|
x + 3,
|
||||||
y + 3,
|
y + 3 + size * (1 - done),
|
||||||
SLOT_SIZE - 6,
|
size,
|
||||||
SLOT_SIZE - 6,
|
size * done,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
r,
|
||||||
|
g,
|
||||||
|
b,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// from a model's points to a slot, as screen x and y and depth toward the viewer. with a gui transform, the transform
|
||||||
|
// starts from the model's 16 pixels across the slot's middle, y up. without one it's the cube icon's corners (see
|
||||||
|
// draw_item_block), so models are drawn at the same size and angle: seen from above the north west corner, west on the
|
||||||
|
// left and north on the right
|
||||||
|
function icon_matrix(x: number, y: number, gui?: DisplayTransform): mat4 {
|
||||||
|
if (gui) {
|
||||||
|
const unit = SLOT_SIZE * 16 / 18;
|
||||||
|
const base = mat4.fromTranslation(mat4.create(), [x + SLOT_SIZE / 2, y + SLOT_SIZE / 2, 0]);
|
||||||
|
return display_matrix(mat4.scale(base, base, [unit, -unit, unit]), gui);
|
||||||
|
}
|
||||||
|
const size = (SLOT_SIZE - 4 * 2) / 2;
|
||||||
|
const cx = x + SLOT_SIZE / 2;
|
||||||
|
const cy = y + SLOT_SIZE / 2 - 10;
|
||||||
|
// toward the viewer is -x, +y, -z
|
||||||
|
return mat4.fromValues(size, -size / 2, -1, 0, 0, -size, 1, 0, -size, -size / 2, -1, 0, cx, cy + size * 1.5, 0, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// each model's icon in a slot at 0, 0, as x y u v r g b per vertex. a slot's place only moves the icon (see
|
||||||
|
// icon_matrix), so it's worked out once per model and moved to each slot, rather than every slot every frame
|
||||||
|
const model_icons = new WeakMap<ItemModel, Float32Array>();
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
const atlas = AssetManager.instance.get<Texture>("cubi:textures");
|
||||||
|
use_texture(atlas.tex);
|
||||||
|
let icon = model_icons.get(model);
|
||||||
|
if (!icon) {
|
||||||
|
icon = model_icon(model, atlas);
|
||||||
|
model_icons.set(model, icon);
|
||||||
|
}
|
||||||
|
for (let i = 0; i < icon.length; i += 7) {
|
||||||
|
push_vertex(
|
||||||
|
x + icon[i],
|
||||||
|
y + icon[i + 1],
|
||||||
|
0,
|
||||||
|
icon[i + 2],
|
||||||
|
icon[i + 3],
|
||||||
|
icon[i + 4],
|
||||||
|
icon[i + 5],
|
||||||
|
icon[i + 6],
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function model_icon(model: ItemModel, atlas: Texture): Float32Array {
|
||||||
|
const matrix = icon_matrix(0, 0, model.display.gui);
|
||||||
|
// a mirroring matrix (like the y flip to the screen's y down) turns which way a face's corners go round
|
||||||
|
const flip = Math.sign(mat4.determinant(matrix));
|
||||||
|
const visible = model.quads
|
||||||
|
.map((quad) => {
|
||||||
|
const corners = [0, 1, 2, 3].map((i) =>
|
||||||
|
vec3.transformMat4(vec3.create(), quad.positions.slice(i * 3, i * 3 + 3) as vec3, matrix)
|
||||||
|
);
|
||||||
|
const e1 = vec3.subtract(vec3.create(), corners[1], corners[0]);
|
||||||
|
const e2 = vec3.subtract(vec3.create(), corners[3], corners[0]);
|
||||||
|
const facing = (e1[0] * e2[1] - e1[1] * e2[0]) * flip;
|
||||||
|
const depth = corners.reduce((sum, corner) => sum + corner[2], 0);
|
||||||
|
return { quad, corners, facing, depth };
|
||||||
|
})
|
||||||
|
.filter(({ facing }) => facing > 1e-6)
|
||||||
|
.sort((a, b) => a.depth - b.depth);
|
||||||
|
|
||||||
|
const vertices: number[] = [];
|
||||||
|
for (const { quad, corners } of visible) {
|
||||||
|
const region = get_sprite_region(quad.texture);
|
||||||
|
const [r, g, b] = model.block ? item_tint(model.block, quad.variables) : [1, 1, 1];
|
||||||
|
const shade = quad.shade ? ITEM_FACE_SHADE[quad.face] : 1;
|
||||||
|
for (const i of [0, 1, 2, 0, 2, 3]) {
|
||||||
|
vertices.push(
|
||||||
|
corners[i][0],
|
||||||
|
corners[i][1],
|
||||||
|
sprite_u(atlas, region, quad.uvs[i * 2]),
|
||||||
|
sprite_v(atlas, region, quad.uvs[i * 2 + 1]),
|
||||||
|
shade * r,
|
||||||
|
shade * g,
|
||||||
|
shade * b,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Float32Array(vertices);
|
||||||
|
}
|
||||||
|
|
||||||
function draw_item_block(block_info: BlockRegistry, x: number, y: number) {
|
function draw_item_block(block_info: BlockRegistry, x: number, y: number) {
|
||||||
const top_texture = cube_face_texture(block_info, "top");
|
const top_texture = cube_face_texture(block_info, "top");
|
||||||
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);
|
||||||
|
|||||||
@@ -0,0 +1,621 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||||
|
// 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
|
||||||
|
// block, made when its section is meshed and kept by chunk. what they draw are instances of models, and every instance
|
||||||
|
// 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
|
||||||
|
// 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 type {
|
||||||
|
FluidInstance,
|
||||||
|
Instances,
|
||||||
|
ItemStack as ApiItemStack,
|
||||||
|
ModelRef,
|
||||||
|
RotatingInstance,
|
||||||
|
TransformedInstance,
|
||||||
|
Visual,
|
||||||
|
VisualBlock,
|
||||||
|
} from "@/common/mod_api/client.ts";
|
||||||
|
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
|
||||||
|
import {
|
||||||
|
bake_block,
|
||||||
|
bake_model,
|
||||||
|
type BakedQuad,
|
||||||
|
find_model,
|
||||||
|
item_tint,
|
||||||
|
type ModelElementJson,
|
||||||
|
type ModelJson,
|
||||||
|
states_of,
|
||||||
|
} from "@/common/block_models.ts";
|
||||||
|
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
||||||
|
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
|
||||||
|
import type { ModelFace } from "@/common/mod_data.ts";
|
||||||
|
import { ItemStack } from "@/common/inventory.ts";
|
||||||
|
import { chunk_key, item_texture } from "@/common/utils.ts";
|
||||||
|
import {
|
||||||
|
create_vertex_buffer,
|
||||||
|
destroy_buffer,
|
||||||
|
draw_instances,
|
||||||
|
INSTANCE_FLOATS,
|
||||||
|
MODEL_VERTEX_BYTES,
|
||||||
|
type Texture,
|
||||||
|
write_buffer,
|
||||||
|
} from "@/client/renderer/mod.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";
|
||||||
|
|
||||||
|
export interface VisualRegistration {
|
||||||
|
mod: string;
|
||||||
|
create: (block: VisualBlock, instances: Instances) => Visual;
|
||||||
|
// the block's model isn't in the terrain, the visual draws all of it
|
||||||
|
replaces_model: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// each block's visual by the block's numeric id, see ctx.render.register_visual
|
||||||
|
export const block_visuals = new Map<number, VisualRegistration>();
|
||||||
|
|
||||||
|
const AXES: Record<string, vec3> = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
|
||||||
|
|
||||||
|
// what visuals read from their level
|
||||||
|
export interface VisualsLevel {
|
||||||
|
get_block_data(x: number, y: number, z: number): Readonly<Record<string, unknown>> | undefined;
|
||||||
|
// block light << 4 | sky light
|
||||||
|
get_light(x: number, y: number, z: number): number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// an instance as the engine keeps it, see INSTANCE_FLOATS
|
||||||
|
export interface DrawnInstance {
|
||||||
|
group: InstanceGroup;
|
||||||
|
// where it is in its group, -1 once it's deleted
|
||||||
|
index: number;
|
||||||
|
// takes its model to the world, after it spins around its block's middle
|
||||||
|
placement: mat4;
|
||||||
|
axis: vec3;
|
||||||
|
rpm: number;
|
||||||
|
// degrees
|
||||||
|
offset: number;
|
||||||
|
// packed like ClientLevel.get_light
|
||||||
|
light: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a quad of an instanced model: 4 corners counter clockwise seen from the front, x y z each in the model's space, their
|
||||||
|
// uvs in atlas pixels, so they don't depend on the atlas's size, its tint, and whether the gpu shades it by the way it
|
||||||
|
// faces
|
||||||
|
export interface InstanceQuad {
|
||||||
|
positions: number[];
|
||||||
|
uvs: number[];
|
||||||
|
tint: number[];
|
||||||
|
shade: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// what to give sprite_u and sprite_v for uvs in atlas pixels
|
||||||
|
const ATLAS_PIXELS = { width: 1, height: 1 } as Texture;
|
||||||
|
|
||||||
|
// a model's baked quads as an instanced model's, each tinted
|
||||||
|
export function instance_quads(quads: BakedQuad[], tint: (quad: BakedQuad) => number[]): InstanceQuad[] {
|
||||||
|
return quads.map((quad) => {
|
||||||
|
const region = get_sprite_region(quad.texture);
|
||||||
|
const uvs = quad.uvs.map((pixels, i) =>
|
||||||
|
i % 2 === 0 ? sprite_u(ATLAS_PIXELS, region, pixels) : sprite_v(ATLAS_PIXELS, region, pixels)
|
||||||
|
);
|
||||||
|
return { positions: quad.positions, uvs, tint: tint(quad), shade: quad.shade };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// the instances of one model, drawn in one draw call. their data is changed on the cpu and written to the gpu once a
|
||||||
|
// frame, from the first instance that changed to the last
|
||||||
|
export class InstanceGroup {
|
||||||
|
quads: InstanceQuad[];
|
||||||
|
// drawn blended after the rest, back to front by center, like a fluid's box
|
||||||
|
readonly translucent: boolean;
|
||||||
|
// where it is in the world, for drawing translucent ones back to front
|
||||||
|
center = vec3.create();
|
||||||
|
readonly instances: DrawnInstance[] = [];
|
||||||
|
data = new Float32Array(INSTANCE_FLOATS * 16);
|
||||||
|
// the instances changed since the gpu last got them, by index
|
||||||
|
dirty_from = Infinity;
|
||||||
|
dirty_to = -1;
|
||||||
|
// quads changed since the gpu last got them
|
||||||
|
model_changed = false;
|
||||||
|
// made the first time it's drawn
|
||||||
|
gpu?: { model: GPUBuffer; instances: GPUBuffer; capacity: number };
|
||||||
|
|
||||||
|
constructor(quads: InstanceQuad[], translucent = false) {
|
||||||
|
this.quads = quads;
|
||||||
|
this.translucent = translucent;
|
||||||
|
}
|
||||||
|
|
||||||
|
// for a model that changes, like a fluid's box filling up
|
||||||
|
set_quads(quads: InstanceQuad[]) {
|
||||||
|
this.quads = quads;
|
||||||
|
this.model_changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
add(instance: DrawnInstance) {
|
||||||
|
instance.index = this.instances.length;
|
||||||
|
this.instances.push(instance);
|
||||||
|
if (this.data.length < this.instances.length * INSTANCE_FLOATS) {
|
||||||
|
const data = new Float32Array(this.data.length * 2);
|
||||||
|
data.set(this.data);
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
this.write(instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the last instance moves into its place, so the ones drawn are always the first ones
|
||||||
|
remove(instance: DrawnInstance) {
|
||||||
|
if (instance.index < 0) return;
|
||||||
|
const last = this.instances.pop()!;
|
||||||
|
if (last !== instance) {
|
||||||
|
last.index = instance.index;
|
||||||
|
this.instances[last.index] = last;
|
||||||
|
this.write(last);
|
||||||
|
}
|
||||||
|
instance.index = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// after any of its fields changed
|
||||||
|
write(instance: DrawnInstance) {
|
||||||
|
const index = instance.index;
|
||||||
|
if (index < 0) return;
|
||||||
|
const at = index * INSTANCE_FLOATS;
|
||||||
|
this.data.set(instance.placement, at);
|
||||||
|
this.data.set(instance.axis, at + 16);
|
||||||
|
this.data[at + 19] = instance.rpm;
|
||||||
|
this.data[at + 20] = instance.offset;
|
||||||
|
this.data[at + 21] = ((instance.light >> 4) + 0.5) / 16;
|
||||||
|
this.data[at + 22] = ((instance.light & 15) + 0.5) / 16;
|
||||||
|
this.dirty_from = Math.min(this.dirty_from, index);
|
||||||
|
this.dirty_to = Math.max(this.dirty_to, index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Entry {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
z: number;
|
||||||
|
value: number;
|
||||||
|
mod: string;
|
||||||
|
light: number;
|
||||||
|
// undefined when making it threw, until the block changes
|
||||||
|
visual?: Visual;
|
||||||
|
instances: Set<DrawnInstance>;
|
||||||
|
// on_frame threw, so it isn't called again
|
||||||
|
frame_failed?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a level's visuals
|
||||||
|
export class Visuals {
|
||||||
|
// by chunk_key, then the block's index in its chunk counted from y 0, see #index
|
||||||
|
#chunks = new Map<number, Map<number, Entry>>();
|
||||||
|
#level: VisualsLevel;
|
||||||
|
// baked once per level, since a level's mods don't change
|
||||||
|
#models?: Record<string, ModelJson>;
|
||||||
|
// models from models/ by id and turns, blocks' own by value, and items by how they look
|
||||||
|
#model_groups = new Map<string, InstanceGroup>();
|
||||||
|
#block_groups = new Map<number, InstanceGroup>();
|
||||||
|
#item_groups = new Map<string, InstanceGroup>();
|
||||||
|
// a fluid box's model is its own, and goes with it
|
||||||
|
#fluid_groups = new Set<InstanceGroup>();
|
||||||
|
|
||||||
|
constructor(level: VisualsLevel) {
|
||||||
|
this.#level = level;
|
||||||
|
}
|
||||||
|
|
||||||
|
has(chunk_x: number, chunk_z: number) {
|
||||||
|
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
|
||||||
|
}
|
||||||
|
|
||||||
|
*groups(): Iterable<InstanceGroup> {
|
||||||
|
yield* this.#model_groups.values();
|
||||||
|
yield* this.#block_groups.values();
|
||||||
|
yield* this.#item_groups.values();
|
||||||
|
yield* this.#fluid_groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the blocks with visuals a chunk's section was meshed with, as pairs of the block's index in the section (see
|
||||||
|
// section_index) and its value. bottom is the section's lowest y. visuals in it for blocks that are gone or
|
||||||
|
// 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, bottom: number, found: Uint32Array) {
|
||||||
|
const key = chunk_key(chunk_x, chunk_z);
|
||||||
|
const entries = this.#chunks.get(key) ?? 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) {
|
||||||
|
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 entry = old.get(index);
|
||||||
|
old.delete(index);
|
||||||
|
if (entry?.value === value) {
|
||||||
|
this.#relight(entry);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (entry) {
|
||||||
|
this.#delete(entry);
|
||||||
|
entries.delete(index);
|
||||||
|
}
|
||||||
|
const made = this.#create(x, y, z, value);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a field of the block's client data changed
|
||||||
|
data_changed(x: number, y: number, z: number) {
|
||||||
|
const entry = this.#entry(x, y, z);
|
||||||
|
if (entry?.visual?.update) run_visual(entry, "update", () => entry.visual!.update!());
|
||||||
|
}
|
||||||
|
|
||||||
|
unload(chunk_x: number, chunk_z: number) {
|
||||||
|
const key = chunk_key(chunk_x, chunk_z);
|
||||||
|
for (const entry of this.#chunks.get(key)?.values() ?? []) this.#delete(entry);
|
||||||
|
this.#chunks.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// every visual goes, and the gpu buffers with them
|
||||||
|
dispose() {
|
||||||
|
for (const key of this.#chunks.keys()) {
|
||||||
|
for (const entry of this.#chunks.get(key)!.values()) this.#delete(entry);
|
||||||
|
}
|
||||||
|
this.#chunks.clear();
|
||||||
|
for (const group of this.groups()) destroy_group(group);
|
||||||
|
this.#model_groups.clear();
|
||||||
|
this.#block_groups.clear();
|
||||||
|
this.#item_groups.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// the visuals in these chunks get their on_frame. every instance is drawn either way, it's the gpu that skips what's
|
||||||
|
// out of view
|
||||||
|
frame(chunks: Iterable<{ x: number; z: number }>, time: number) {
|
||||||
|
for (const chunk of chunks) {
|
||||||
|
for (const entry of this.#chunks.get(chunk_key(chunk.x, chunk.z))?.values() ?? []) {
|
||||||
|
const visual = entry.visual;
|
||||||
|
if (visual?.on_frame && !entry.frame_failed) {
|
||||||
|
entry.frame_failed = !run_visual(entry, "on_frame", () => visual.on_frame!(time));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#entry(x: number, y: number, z: number) {
|
||||||
|
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
|
||||||
|
return this.#chunks.get(key)?.get(this.#index(x, y, z));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
const registration = block_visuals.get(value & ID_MASK);
|
||||||
|
const block = EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK);
|
||||||
|
if (!registration || !block) return undefined;
|
||||||
|
const light = this.#level.get_light(x, y, z);
|
||||||
|
const entry: Entry = { x, y, z, value, mod: registration.mod, light, instances: new Set() };
|
||||||
|
const level = this.#level;
|
||||||
|
const view: VisualBlock = {
|
||||||
|
id: block.id,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
z,
|
||||||
|
states: Object.freeze(states_of(block, value)),
|
||||||
|
get_client_data: (field) => structuredClone(level.get_block_data(x, y, z)?.[field]) as never,
|
||||||
|
};
|
||||||
|
const made = run_visual(entry, "create", () => {
|
||||||
|
entry.visual = registration.create(view, this.#instances(entry, block));
|
||||||
|
});
|
||||||
|
// nothing it made before it threw is drawn
|
||||||
|
if (!made) this.#remove_instances(entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
#delete(entry: Entry) {
|
||||||
|
const visual = entry.visual;
|
||||||
|
if (visual?.on_delete) run_visual(entry, "on_delete", () => visual.on_delete!());
|
||||||
|
this.#remove_instances(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
#remove_instances(entry: Entry) {
|
||||||
|
for (const instance of entry.instances) this.#remove_instance(instance);
|
||||||
|
entry.instances.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#remove_instance(instance: DrawnInstance) {
|
||||||
|
instance.group.remove(instance);
|
||||||
|
if (this.#fluid_groups.delete(instance.group)) destroy_group(instance.group);
|
||||||
|
}
|
||||||
|
|
||||||
|
#relight(entry: Entry) {
|
||||||
|
const light = this.#level.get_light(entry.x, entry.y, entry.z);
|
||||||
|
if (light === entry.light) return;
|
||||||
|
entry.light = light;
|
||||||
|
for (const instance of entry.instances) {
|
||||||
|
instance.light = light;
|
||||||
|
instance.group.write(instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#instances(entry: Entry, block: BlockRegistry): Instances {
|
||||||
|
const corner = mat4.fromTranslation(mat4.create(), [entry.x, entry.y, entry.z]);
|
||||||
|
const add = (group: InstanceGroup) => {
|
||||||
|
const instance: DrawnInstance = {
|
||||||
|
group,
|
||||||
|
index: -1,
|
||||||
|
placement: mat4.clone(corner),
|
||||||
|
axis: AXES.y,
|
||||||
|
rpm: 0,
|
||||||
|
offset: 0,
|
||||||
|
light: entry.light,
|
||||||
|
};
|
||||||
|
group.add(instance);
|
||||||
|
entry.instances.add(instance);
|
||||||
|
return instance;
|
||||||
|
};
|
||||||
|
const remove = (instance: DrawnInstance) => () => {
|
||||||
|
this.#remove_instance(instance);
|
||||||
|
entry.instances.delete(instance);
|
||||||
|
};
|
||||||
|
const model_group = (model: ModelRef | undefined) =>
|
||||||
|
model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model);
|
||||||
|
const transformed = (instance: DrawnInstance): TransformedInstance => ({
|
||||||
|
set_transform(matrix) {
|
||||||
|
if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix");
|
||||||
|
mat4.multiply(instance.placement, corner, matrix as mat4);
|
||||||
|
instance.group.write(instance);
|
||||||
|
},
|
||||||
|
delete: remove(instance),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
transformed: (model) => transformed(add(model_group(model))),
|
||||||
|
item: (stack) => transformed(add(this.#item_group(stack))),
|
||||||
|
fluid: (fluid) => {
|
||||||
|
const { texture, tint } = fluid_look(fluid);
|
||||||
|
const group = new InstanceGroup([], true);
|
||||||
|
this.#fluid_groups.add(group);
|
||||||
|
const instance = add(group);
|
||||||
|
return {
|
||||||
|
set_box(from, to) {
|
||||||
|
const box = [from, to].map((corner) => [0, 1, 2].map((axis) => corner?.[axis]));
|
||||||
|
if (!box.flat().every(Number.isFinite)) throw new Error("a box is from [x, y, z] to [x, y, z]");
|
||||||
|
group.set_quads(fluid_box(texture, tint, box[0], box[1]));
|
||||||
|
vec3.set(
|
||||||
|
group.center,
|
||||||
|
entry.x + (box[0][0] + box[1][0]) / 32,
|
||||||
|
entry.y + (box[0][1] + box[1][1]) / 32,
|
||||||
|
entry.z + (box[0][2] + box[1][2]) / 32,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
delete: remove(instance),
|
||||||
|
} satisfies FluidInstance;
|
||||||
|
},
|
||||||
|
rotating(model): RotatingInstance {
|
||||||
|
const instance = add(model_group(model));
|
||||||
|
return {
|
||||||
|
set_rotation(axis, rpm, offset = 0) {
|
||||||
|
if (!AXES[axis]) throw new Error(`an axis is "x", "y" or "z", not ${axis}`);
|
||||||
|
instance.axis = AXES[axis];
|
||||||
|
instance.rpm = rpm;
|
||||||
|
instance.offset = offset;
|
||||||
|
instance.group.write(instance);
|
||||||
|
},
|
||||||
|
delete: remove(instance),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#model_group(ref: ModelRef): InstanceGroup {
|
||||||
|
const { model, x = 0, y = 0 } = typeof ref === "string" ? { model: ref } : ref;
|
||||||
|
const key = `${model} ${x} ${y}`;
|
||||||
|
let group = this.#model_groups.get(key);
|
||||||
|
if (!group) {
|
||||||
|
this.#models ??= Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
|
||||||
|
const json = find_model(model, this.#models);
|
||||||
|
if (!json) throw new Error(`there's no model ${model}`);
|
||||||
|
group = new InstanceGroup(instance_quads(bake_model(json, undefined, y, x), () => [1, 1, 1]));
|
||||||
|
this.#model_groups.set(key, group);
|
||||||
|
}
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
|
||||||
|
#block_group(block: BlockRegistry, value: number): InstanceGroup {
|
||||||
|
let group = this.#block_groups.get(value);
|
||||||
|
if (!group) {
|
||||||
|
this.#models ??= Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
|
||||||
|
const quads = bake_block(block, value, this.#models);
|
||||||
|
group = new InstanceGroup(instance_quads(quads, (quad) => item_tint(block, quad.variables)));
|
||||||
|
this.#block_groups.set(value, group);
|
||||||
|
}
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
|
||||||
|
// stacks that look the same share one: the same item, texture and layers in the same colors, like bottles of one
|
||||||
|
// juice
|
||||||
|
#item_group(stack: ApiItemStack): InstanceGroup {
|
||||||
|
if (!EverythingRegistry.get("items", stack?.id)) throw new Error(`there's no item ${stack?.id}`);
|
||||||
|
const item = new ItemStack(stack.id);
|
||||||
|
if (stack.data !== undefined) item.data = structuredClone(stack.data);
|
||||||
|
const key = JSON.stringify([item.type_id, item_texture(item), item_layers(item)]);
|
||||||
|
let group = this.#item_groups.get(key);
|
||||||
|
if (!group) {
|
||||||
|
group = new InstanceGroup(item_quads(item));
|
||||||
|
this.#item_groups.set(key, group);
|
||||||
|
}
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// an item's model the way push_item draws it, the size it's drawn on the ground. its shading is in its tints already,
|
||||||
|
// like a dropped item's, so the gpu doesn't shade it again
|
||||||
|
function item_quads(item: ItemStack): InstanceQuad[] {
|
||||||
|
const vertices: number[][] = [];
|
||||||
|
push_item(ATLAS_PIXELS, item, ground_transform(item), [1, 1, 1], (x, y, z, u, v, r = 1, g = 1, b = 1) => {
|
||||||
|
vertices.push([x, y, z, u, v, r, g, b]);
|
||||||
|
});
|
||||||
|
const quads: InstanceQuad[] = [];
|
||||||
|
// two triangles a quad, 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]];
|
||||||
|
quads.push({
|
||||||
|
positions: corners.flatMap(([x, y, z]) => [x, y, z]),
|
||||||
|
uvs: corners.flatMap(([, , , u, v]) => [u, v]),
|
||||||
|
tint: corners[0].slice(5, 8),
|
||||||
|
shade: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return quads;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a box's faces, by the axis they're across and whether they're at its high end or its low one
|
||||||
|
const BOX_FACES: { face: ModelFace; axis: number; high: boolean }[] = [
|
||||||
|
{ face: "west", axis: 0, high: false },
|
||||||
|
{ face: "east", axis: 0, high: true },
|
||||||
|
{ face: "bottom", axis: 1, high: false },
|
||||||
|
{ face: "top", axis: 1, high: true },
|
||||||
|
{ face: "north", axis: 2, high: false },
|
||||||
|
{ face: "south", axis: 2, high: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
// a box of a texture from one corner to the other, in pixels, like a fluid in a tank. it's cut where it goes from one
|
||||||
|
// block into the next, and each piece is textured with the part of the texture it covers in its block, like a model
|
||||||
|
// element's faces are, so the texture is never stretched and repeats once a block. only the outside faces are drawn.
|
||||||
|
// nothing for a box that's flat or inside out
|
||||||
|
export function fluid_box(texture: string, tint: number[], from: number[], to: number[]): InstanceQuad[] {
|
||||||
|
if ([0, 1, 2].some((axis) => to[axis] <= from[axis])) return [];
|
||||||
|
// where each axis's pieces start and end
|
||||||
|
const cuts = [0, 1, 2].map((axis) => {
|
||||||
|
const points = [from[axis]];
|
||||||
|
for (let at = (Math.floor(from[axis] / 16) + 1) * 16; at < to[axis]; at += 16) points.push(at);
|
||||||
|
return [...points, to[axis]];
|
||||||
|
});
|
||||||
|
const model: ModelJson = { id: "cubi:fluid_box", textures: { fluid: texture }, elements: [] };
|
||||||
|
const quads: InstanceQuad[] = [];
|
||||||
|
for (let i = 0; i < cuts[0].length - 1; i++) {
|
||||||
|
for (let j = 0; j < cuts[1].length - 1; j++) {
|
||||||
|
for (let k = 0; k < cuts[2].length - 1; k++) {
|
||||||
|
const low = [cuts[0][i], cuts[1][j], cuts[2][k]];
|
||||||
|
const high = [cuts[0][i + 1], cuts[1][j + 1], cuts[2][k + 1]];
|
||||||
|
const block = low.map((at) => Math.floor(at / 16));
|
||||||
|
const element: ModelElementJson = {
|
||||||
|
from: low.map((at, axis) => at - block[axis] * 16) as [number, number, number],
|
||||||
|
to: high.map((at, axis) => at - block[axis] * 16) as [number, number, number],
|
||||||
|
faces: {},
|
||||||
|
};
|
||||||
|
for (const { face, axis, high: side } of BOX_FACES) {
|
||||||
|
if (side ? high[axis] === to[axis] : low[axis] === from[axis]) {
|
||||||
|
element.faces[face] = { texture: "#fluid" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const baked = bake_model({ ...model, elements: [element] }, undefined);
|
||||||
|
for (const quad of baked) {
|
||||||
|
quad.positions = quad.positions.map((at, n) => at + block[n % 3]);
|
||||||
|
}
|
||||||
|
quads.push(...instance_quads(baked, () => tint));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return quads;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a group's gpu buffers go, for a group that won't be drawn again
|
||||||
|
function destroy_group(group: InstanceGroup) {
|
||||||
|
if (!group.gpu) return;
|
||||||
|
destroy_buffer(group.gpu.model);
|
||||||
|
destroy_buffer(group.gpu.instances);
|
||||||
|
group.gpu = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// false when it threw, which is logged with the mod and block
|
||||||
|
function run_visual(entry: Entry, what: string, fn: () => void) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${entry.mod}] the visual at ${entry.x} ${entry.y} ${entry.z} threw in ${what}:`, e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// every instance, a draw call per model, and the translucent ones after the rest, back to front from the camera so each
|
||||||
|
// shows what's behind it. a group's model goes to the gpu the first time it's drawn and again when it changed, and its
|
||||||
|
// instances whenever they changed. the atlas has to be the current texture
|
||||||
|
export function draw_visuals(visuals: Visuals, atlas: Texture, camera: Readonly<vec3>) {
|
||||||
|
const translucent: InstanceGroup[] = [];
|
||||||
|
for (const group of visuals.groups()) {
|
||||||
|
if (group.translucent) translucent.push(group);
|
||||||
|
else draw_group(group, atlas);
|
||||||
|
}
|
||||||
|
const distance = (group: InstanceGroup) => vec3.squaredDistance(group.center, camera);
|
||||||
|
translucent.sort((a, b) => distance(b) - distance(a));
|
||||||
|
for (const group of translucent) draw_group(group, atlas);
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw_group(group: InstanceGroup, atlas: Texture) {
|
||||||
|
const count = group.instances.length;
|
||||||
|
if (count === 0 || group.quads.length === 0) return;
|
||||||
|
const capacity = group.data.length / INSTANCE_FLOATS;
|
||||||
|
if (group.gpu && group.model_changed) {
|
||||||
|
destroy_buffer(group.gpu.model);
|
||||||
|
group.gpu.model = create_vertex_buffer(pack_model(group.quads, atlas));
|
||||||
|
}
|
||||||
|
group.model_changed = false;
|
||||||
|
if (!group.gpu || group.gpu.capacity !== capacity) {
|
||||||
|
// the whole buffer again, when it's new or the cpu copy grew
|
||||||
|
if (group.gpu) destroy_buffer(group.gpu.instances);
|
||||||
|
group.gpu = {
|
||||||
|
model: group.gpu?.model ?? create_vertex_buffer(pack_model(group.quads, atlas)),
|
||||||
|
instances: create_vertex_buffer(group.data),
|
||||||
|
capacity,
|
||||||
|
};
|
||||||
|
} else if (group.dirty_to >= 0) {
|
||||||
|
const from = group.dirty_from * INSTANCE_FLOATS;
|
||||||
|
write_buffer(
|
||||||
|
group.gpu.instances,
|
||||||
|
from * 4,
|
||||||
|
group.data,
|
||||||
|
from,
|
||||||
|
(group.dirty_to + 1) * INSTANCE_FLOATS - from,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
group.dirty_from = Infinity;
|
||||||
|
group.dirty_to = -1;
|
||||||
|
draw_instances(group.gpu.model, group.quads.length, group.gpu.instances, count, group.translucent);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a model's quads as vertices for vs_instance, 4 a quad, see MODEL_VERTEX_BYTES
|
||||||
|
export function pack_model(quads: InstanceQuad[], atlas: Texture): Uint8Array<ArrayBuffer> {
|
||||||
|
const bytes = new Uint8Array(quads.length * 4 * MODEL_VERTEX_BYTES);
|
||||||
|
const view = new DataView(bytes.buffer);
|
||||||
|
const normal = vec3.create();
|
||||||
|
quads.forEach((quad, q) => {
|
||||||
|
const p = quad.positions;
|
||||||
|
const corner = (k: number) => vec3.fromValues(p[k * 3], p[k * 3 + 1], p[k * 3 + 2]);
|
||||||
|
// counterclockwise seen from the front, so it points out of the front
|
||||||
|
const [a, b, d] = [corner(0), corner(1), corner(3)];
|
||||||
|
vec3.normalize(normal, vec3.cross(normal, vec3.sub(b, b, a), vec3.sub(d, d, a)));
|
||||||
|
const tint = quad.tint;
|
||||||
|
for (let k = 0; k < 4; k++) {
|
||||||
|
const at = (q * 4 + k) * MODEL_VERTEX_BYTES;
|
||||||
|
for (let axis = 0; axis < 3; axis++) view.setFloat32(at + axis * 4, p[k * 3 + axis], true);
|
||||||
|
view.setUint16(at + 12, Math.round(quad.uvs[k * 2] / atlas.width * 65535), true);
|
||||||
|
view.setUint16(at + 14, Math.round(quad.uvs[k * 2 + 1] / atlas.height * 65535), true);
|
||||||
|
for (let c = 0; c < 3; c++) bytes[at + 16 + c] = Math.round(tint[c] * 255);
|
||||||
|
bytes[at + 19] = quad.shade ? 255 : 0;
|
||||||
|
for (let axis = 0; axis < 3; axis++) view.setInt8(at + 20 + axis, Math.round(normal[axis] * 127));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user