Commit graph

311 commits

Author SHA1 Message Date
Carson McManus 4194acaa67
Use Option<InventoryId> for open_inventory on client (#167)
- automatically handle CloseContainer packet so the client updates open_inventory
- Use `Option<InventoryId>` for `open_inventory` on client

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2022-12-19 06:55:26 -08:00
Terminator c4ed95a7d3
Performance enhancements for #141 (#173)
This PR also includes the Criterion benchmark.

## Before this commit
> Benchmarking BlockState::to_kind
> Benchmarking BlockState::to_kind: Warming up for 3.0000 s Benchmarking
BlockState::to_kind: Collecting 100 samples in estimated 20.045 s (273k
iterations) Benchmarking BlockState::to_kind: Analyzing
> BlockState::to_kind     time:   [68.925 µs 69.202 µs 69.477 µs]
> 
> Found 5 outliers among 100 measurements (5.00%)
>   4 (4.00%) high mild
>   1 (1.00%) high severe

## After this commit
> Benchmarking BlockState::to_kind
> Benchmarking BlockState::to_kind: Warming up for 3.0000 s Benchmarking
BlockState::to_kind: Collecting 100 samples in estimated 20.010 s (3.8M
iterations) Benchmarking BlockState::to_kind: Analyzing
> BlockState::to_kind     time:   [1.5814 µs 1.5859 µs 1.5912 µs]
> change: [-97.692% -97.678% -97.666%] (p = 0.00 < 0.05)
>                         Performance has improved.
> Found 4 outliers among 100 measurements (4.00%)
>   4 (4.00%) high mild

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2022-12-19 06:25:26 -08:00
Ryan aeea435a7e Fix examples, but for real this time 2022-12-19 06:24:06 -08:00
Ryan 4e302ca09f Remove remaining unnecessary casts in examples 2022-12-19 06:11:03 -08:00
Ryan 985f7891e4 Remove unnecessary casts in death example 2022-12-19 02:17:35 -08:00
Ryan 01ff465db9 Remove unnecessary casts in parkour example 2022-12-19 01:50:51 -08:00
Ryan Johnson d85b7f5e89
Update packet inspector and fix packet bugs (#172)
- Implement `encoded_len` for packet enums.
- Fix bug in `has_next_packet` causing a later `unwrap` to panic.
- Add robust `encoded_len` check in `PacketEncoder` for debug builds.
- Split packet inspector regex into separate "inclusive" and "exclusive"
arguments because the `regex` crate does not support negative lookahead.
- Better `Debug` impls for `Ident` and `Compound`.
- Remove read/write timeouts from packet inspector.
2022-12-16 08:23:48 -08:00
Terminator c73abacc98
Re-visit From impl for native data types found in NBT data format. (#169) 2022-12-15 18:38:52 -08:00
Ryan Johnson 740778ec41
Update chunk data packet cache lazily (#170)
Previously, the chunk data cache was regenerated at the end of each tick
every time a block or biome was modified in a chunk. This causes
performance problems in situations where chunks are being modified every
tick, like the conway example or redstone machines.

This changes things so that the chunk data packet is regenerated only
when a client actually needs to load the chunk. This isn't perfect
because the regeneration cannot happen in parallel, but the benefits
outweigh the costs. (The chunk data packet _is_ generated in parallel
when the chunk is first created. There is also some parallelism when
clients are loading different chunks. The packet cache is guarded by a
`Mutex`.)

This has revealed that compression is surprisingly slow. This should be
investigated later.
2022-12-13 22:56:22 -08:00
Carson McManus 8b50e93b0e
add swap_slot to Inventory (#168)
This effectively exposes the slice `swap` method:
https://doc.rust-lang.org/std/primitive.slice.html#method.swap
2022-12-11 09:35:14 -08:00
Ryan Johnson ae7eaf15fc
Big Optimizations (#164)
Closes #84

# Changes

- Implemented new algorithm for tracking loaded entities and chunks.
- The client does not need to maintain a list of loaded chunks and
entities anymore, as this information can be inferred using carefully
maintained data from the previous tick.
- Chunks are used as a spatial partition for entities. Entity visibility
is now based on chunk visibility rather than the euclidean distance to
clients.
- The BVH is no longer strictly necessary, so it has been moved to the
new `valence_spatial_index` crate.
- The API has been generalized to support things other than entities.
The crate does not have a dependency on the main `valence` crate.
- Chunk, entity, and player list packets are now aggressively cached to
increase performance.
- Chunk packets now include some filler light data. This makes the
vanilla client lag a lot less.
- Entities and chunks must now be marked as deleted before they are
removed.
- Improved `ChunkPos` interface.
- Added function to get the duration per tick.
- Added `Index` and `IndexMut` impls to collection types.

As a result of the above changes, performance under heavy load has
increased significantly. With the rust-mc-bot test on my machine, I went
from a max of ~1000 players to ~4000 players.
2022-12-11 02:37:02 -08:00
Carson McManus 4188bd71bb
re-implement inventory_piano example (#166)
# Test plan

```
cargo r -r --example inventory_piano
```

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2022-12-10 18:08:32 -08:00
Ryan b61bdbb71d Fix conflicting Debug impl on bitfield structs 2022-12-09 17:02:37 -08:00
Ryan Johnson 842ddb4127
Optimize sending tracked entity data (#163) 2022-11-30 15:55:46 -08:00
Ryan Johnson 0e28e5ad05
Improve slab_rc implementation (#162) 2022-11-29 17:14:04 -08:00
Ryan Johnson 58f8197913
Client Cleanup (#159)
# Noteworthy Changes
- Simplified the `client` module and update procedure. Sending packets
is not deferred unless necessary.
- Client events are no longer buffered in `Client` before reaching the
user.
- Expanded `ClientEvent` to account for most packets.
- Most types containing custom `state` now implement `Deref` and
`DerefMut`. This means you don't have to write `.state` all over the
place. `Server` was excluded from this because it does not play well
with the borrow checker.
- Fixed bugs related to entity visibility.
- Client now correctly holds the semaphore permit from the initial
connection.
- Other miscellaneous API changes throughout the project. 

# Known Issues
- Inventory stuff is still incomplete. The inventory examples have been
temporarily disabled.
2022-11-29 03:37:32 -08:00
Sandro Marques 6437381339
Translation key extractor and code generator (#160)
Generates a new `translation_key.rs` with all bundled translations.
Closes #158.
2022-11-27 05:12:08 -08:00
Sandro Marques 86be031a31
Implement missing text component types (#144)
Implements the remaining text component types. Should hopefully close
#19.

Co-authored-by: Ryan <ryanj00a@gmail.com>
2022-11-19 16:48:01 -08:00
Ryan Johnson 4226201fed
Replace log crate with tracing (#157)
The `tracing` crate seems to be the go-to
logging/profiling/instrumentation solution nowadays. Perhaps in the
future we could use `tracing` for profiling instead of (or in addition
to) the `perf`-based `cargo flamegraph` command. This would sidestep the
issue of `rayon` polluting the output. I conducted an initial experiment
by adding some more spans but wasn't very happy with the result.

Log messages have also been improved. There is some additional context
and events are raised when clients are added/removed from the server.
2022-11-16 18:22:44 -08:00
Ryan Johnson ab2e1081ed
Re-export common items at the root of valence_protocol (#156) 2022-11-14 22:30:20 -08:00
Ryan 74e4f10ec5 Don't send empty MOTION_BLOCKING heightmap
The client seems to initialize it to zero when you don't send it, so
there's no point in sending an empty motion_blocking.
2022-11-14 17:18:49 -08:00
Ryan 21590a396c Fix cargo:rerun-if-changed=... in valence_protocol 2022-11-14 12:08:32 -08:00
Ryan Johnson 4b155f4c9b
Expand on the "encoded buf" idea in valence_protocol (#155)
Adds a `Cached<T>` type and renames some things.
2022-11-14 01:01:28 -08:00
Ryan Johnson b8e41cbb9a
Change 'Flexible' bullet in README.md
With the introduction of `valence_protocol` and some future plans, I've decided it's unrealistic to try and hide all the protocol code. There are situations where direct access is necessary.
2022-11-13 06:44:22 -08:00
Ryan Johnson 420f2d1b7c
Move protocol code to valence_protocol + redesigns (#153)
Closes #83 

This PR aims to move all of Valence's networking code to the new
`valence_protocol` crate. Anything not specific to valence is going in
the new crate. It also redesigns the way packets are defined and makes a
huge number of small additions and improvements. It should be much
easier to see where code is supposed to go from now on.

`valence_protocol` is a new library which enables interactions with
Minecraft's protocol. It is completely decoupled from valence and can be
used to build new clients, servers, tools, etc.

There are two additions that will help with #5 especially:
- It is now easy to define new packets or modifications of existing
packets. Not all packets need to be bidirectional.
- The `CachedEncode` type has been created. This is used to safely cache
redundant calls to `Encode::encode`.
2022-11-13 06:10:42 -08:00
Ryan Johnson 9f1c946839
Check off proxy support in README.md 2022-11-12 16:45:57 -08:00
emortaldev b1561eda73
Fix proxy joins (#154) 2022-11-12 06:32:00 -08:00
Ryan 923fabe890 Fix missing tokio context on client disconnect
The `PlayPacketController` might spawn a tokio task, but it was not in a
tokio context when that happened. This is because tokio contexts are
thread-local, but rayon tasks run in their own thread pool.
2022-11-09 18:30:44 -08:00
UStuej bb43856c9e
Implement radians conversions for ByteAngle (#149)
Adds `from_radians` function and `to_radians` method for `ByteAngle`.
2022-11-01 22:00:38 -07:00
Ryan Johnson ff136c2a4a
Clean up Config docs and add compression threshold (#148) 2022-11-01 20:27:08 -07:00
Carson McManus a885b949da
Better consume for inventories (#147)
- rework `consume_one` into `consume`
- update `consume_one_held_item` to `consume_held_item` to match
`consume`
- remove an unnecessary clone

Originally, I was planning on removing this function altogether. After
thinking about it for a bit though, I think it provides enough of a
convenience for end users to warrant keeping it.

This also implements the fix that was originally in #124
2022-11-01 19:31:28 -07:00
Ryan Johnson f4714cf255
Redesign packet processing and improve Client update procedure. (#146)
Closes #82
Closes #43
Closes #64

# Changes and Improvements
- Packet encoding/decoding happens within `Client` instead of being sent
over a channel first. This is better for performance and lays the
groundwork for #83.
- Reduce the amount of copying necessary by leveraging the `bytes` crate
and recent changes to `EncodePacket`. Performance is noticeably improved
with maximum players in the `rust-mc-bot` test going from 750 to 1050.
- Packet encoding/decoding code is decoupled from IO. This is easier to
understand and more suitable for a future protocol lib.
- Precise control over the number of bytes that are buffered for
sending/receiving. This is important for limiting maximum memory usage
correctly.
- "packet controllers" are introduced, which are convenient structures
for managing packet IO before and during the play state.
- `byte_channel` module is created to help implement the
`PlayPacketController`. This is essentially a channel of bytes
implemented with an `Arc<Mutex<BytesMut>>`.
- Error handling in the update procedure for clients was improved using
`anyhow::Result<()>` to exit as early as possible. The `client` module
is a bit cleaner as a result.
- The `LoginPlay` packet is always sent before all other play packets.
We no longer have to worry about the behavior of packets sent before
that packet. Most packet deferring performed currently can be
eliminated.
- The packet_inspector was rewritten in response to the above changes.
- Timeouts on IO operations behave better.

# Known Issues
- The packet_inspector now re-encodes packets rather than just decoding
them. This will cause problems when trying to use it with the vanilla
server because there are missing clientbound packets and other issues.
This will be fixed when the protocol module is moved to a separate
crate.
2022-11-01 03:11:51 -07:00
Ryan a20ed2ac21 Bump valence_nbt version 2022-10-30 15:26:47 -07:00
Gijs de Jong 7e24cf014c
Set length range for verify_token to (4, 16) (#143)
Notchian servers [ALWAYS](https://wiki.vg/Protocol#Encryption_Request)
have a `verify_token` length of 4.
This PR updates the range of the `BoundedArray` to support this.
2022-10-29 14:23:22 -07:00
Terminator e80bbc22b3
Avoid calling to_kind() in is_air() (#142)
This PR changes is_air() to not call to_kind() to increase performance.

Example flamegraphs of real usecase of parsing java chunks to
UnloadedChunk:

Before this change:

![flamegraph](https://user-images.githubusercontent.com/13693773/198851700-f455d055-a18d-495c-9989-110e3f569ad9.svg)



After this change:

![flamegraph](https://user-images.githubusercontent.com/13693773/198851673-01f2a6d8-1cb0-4ae7-b57b-6e47a38d9cee.svg)
2022-10-29 13:56:48 -07:00
Ryan Johnson 56ebcaf50d
Add Username<S> type (#132)
There are a number of places where usernames are passed around. Using this type ensures that the contained string is actually a valid username and not some other kind of string. For instance you can use it as a function argument to indicate that only valid usernames are accepted, or return it from a function to indicate that only valid usernames are produced.

This is analogous to the existing `Ident<S>` type.
2022-10-22 20:17:06 -07:00
Carson McManus bbbeb7ae28
don't bother marking the inventory as dirty when handling SetCreativeModeSlot (#134)
fixes #133

### Test plan

1. run building example
2. open inventory
3. place any item in hotbar
4. try to pick it up
5. see that it does not disappear
2022-10-22 18:36:17 -07:00
Ryan c683a0d94c Add warning about missing "plains" biome 2022-10-22 14:01:25 -07:00
Ryan Johnson b08a0a6845
Uncheck proxy support in README.md
Unchecking this for now since there is a bug preventing it from working fully.
2022-10-21 20:00:19 -07:00
Tert0 c707ed1d04
Proxy Support (#48)
This PR adds Proxy Support.

Closes #39

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2022-10-21 19:50:13 -07:00
Ryan Johnson 4253928b4d
Redesign SignedPlayerTextures (#130)
Combines `PlayerTextures` and `SignedPlayerTextures` into one type. The
skin URL is now non-optional because it appears to always be present.
2022-10-21 19:10:37 -07:00
Ryan Johnson f4d36554d7
Make replaceable blocks place correctly in the building example. (#129)
Closes #114

Note that this is a band-aid solution to a more general problem. In the
future, there should be a function in the `block` module to handle all
these placement rules.
2022-10-21 04:55:15 -07:00
Ryan Johnson ce457a3d20
Add prelude module to valence. (#128)
This removes boilerplate code in the examples and reduces friction when getting started.
2022-10-21 04:54:32 -07:00
EmperialDev 4a3ee77858
Added sequence where it was missing (#127) 2022-10-20 12:21:05 -07:00
Ryan Johnson 101aa3721b
Add code of conduct (#126) 2022-10-19 18:07:43 -07:00
Ryan Johnson 71d82c5330
Add encoded_len method to Encode trait. (#125)
This allows packets to calculate their exact length up front.
This isn't currently tested or being used for anything, but that will come in later changes.
2022-10-19 01:52:02 -07:00
Ryan 9b8fbc5d82 Better "encryption enabled" message in packet_inspector 2022-10-19 01:42:32 -07:00
Terminator 03e89adeb8
(valence_nbt) Add reverse From<Value> for Option<T> (#122)
This way we can use generic bounds to specify the return type and get `None` if the value does not match the type.
2022-10-18 14:40:46 -07:00
Ryan dc46f27d5d Fix math in chunk module 2022-10-18 01:45:26 -07:00
Ryan Johnson d22f1edae1
Update valence_nbt to version 0.3.0 (#120)
Improves write performance and adds `binary_encoded_len` to compounds.
2022-10-17 21:11:20 -07:00