Commit graph

378 commits

Author SHA1 Message Date
Carson McManus a57800959f
Rough click slot packet validation (#293)
## Description

This adds some validation for incoming inventory packets that makes it
so that you can't just spawn items by sending malicious packets. It adds
type 1 and type 2 validations as outlined in #292.

This also adds some new helpers, `InventoryWindow` and
`InventoryWindowMut`.

fixes #292

<details>

<summary>Playground</summary>

```rust
use valence::client::{default_event_handler, despawn_disconnected_clients};
use valence::prelude::event::PlayerInteractBlock;
use valence::prelude::*;

#[allow(unused_imports)]
use crate::extras::*;

const SPAWN_Y: i32 = 64;
const CHEST_POS: [i32; 3] = [0, SPAWN_Y + 1, 3];

pub fn build_app(app: &mut App) {
    app.add_plugin(ServerPlugin::new(()).with_connection_mode(ConnectionMode::Offline))
        .add_startup_system(setup)
        .add_system(default_event_handler.in_schedule(EventLoopSchedule))
        .add_system(init_clients)
        .add_system(despawn_disconnected_clients)
        .add_systems((toggle_gamemode_on_sneak, open_chest).in_schedule(EventLoopSchedule));
}

fn setup(mut commands: Commands, server: Res<Server>) {
    let mut instance = server.new_instance(DimensionId::default());

    for z in -5..5 {
        for x in -5..5 {
            instance.insert_chunk([x, z], Chunk::default());
        }
    }

    for z in -25..25 {
        for x in -25..25 {
            instance.set_block([x, SPAWN_Y, z], BlockState::GRASS_BLOCK);
        }
    }
    instance.set_block(CHEST_POS, BlockState::CHEST);

    commands.spawn(instance);

    let mut inventory = Inventory::new(InventoryKind::Generic9x3);
    inventory.set_slot(0, ItemStack::new(ItemKind::Apple, 100, None));
    inventory.set_slot(1, ItemStack::new(ItemKind::Diamond, 40, None));
    inventory.set_slot(2, ItemStack::new(ItemKind::Diamond, 30, None));
    commands.spawn(inventory);
}

fn init_clients(
    mut clients: Query<(&mut Position, &mut Location, &mut Inventory), Added<Client>>,
    instances: Query<Entity, With<Instance>>,
) {
    for (mut pos, mut loc, mut inv) in &mut clients {
        pos.0 = [0.5, SPAWN_Y as f64 + 1.0, 0.5].into();
        loc.0 = instances.single();

        inv.set_slot(24, ItemStack::new(ItemKind::Apple, 100, None));
        inv.set_slot(25, ItemStack::new(ItemKind::Apple, 10, None));
    }
}

// Add new systems here!

fn open_chest(
    mut commands: Commands,
    inventories: Query<Entity, (With<Inventory>, Without<Client>)>,
    mut events: EventReader<PlayerInteractBlock>,
) {
    let Ok(inventory) = inventories.get_single() else {
        return;
    };

    for event in events.iter() {
        if event.position != CHEST_POS.into() {
            continue;
        }
        let open_inventory = OpenInventory::new(inventory);
        commands.entity(event.client).insert(open_inventory);
    }
}

```

</details>

## Test Plan

Steps:
1. `cargo test`

---------

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2023-03-24 05:53:32 -07:00
Ryan Johnson 8d93ddee24
Revise examples guideline and remove some examples. (#301)
# Description

- Removed the advice about making examples as small as possible in
CONTRIBUTING.md
- Remove a couple of low-value examples. I would like to remove more,
but their functionality would have to be covered by better examples
first.

My reasons are:
- Examples are tedious to update and maintain. Boilerplate is
inevitable.
- The "Boilerplate to code" ratio is higher when examples are smaller.
- Examples are likely the first thing that new users will try out, so we
ought to make a good first impression by showing something substantial.
- Complicated examples are better for showing how to use Valence in
practice and serve as a useful reference.
- Lots of small examples can distract from the more impressive ones.
Tiny examples don't add much value.
2023-03-23 06:54:07 -07:00
Ryan Johnson 1aae22ca3e
dump_schedule utility (#300)
## Description

Adds the `dump_schedule` crate which is a simple tool that writes
valence's schedule graph to a file named ~~`graph.gv`~~ `graph.svg`.

## Test Plan

Steps:
1. `cargo r -p dump_schedule`
2. Paste the contents of `graph.gv` to https://edotor.net/
3. Look at the pretty graph.
2023-03-23 01:01:50 -07:00
AviiNL 628a0ff3c3
fix key input with filters, also removed regex from gui and make text… (#298)
… filters case-insensitive

Closes #297

## Description

Up and down arrow to select previous/next packet now ignore filtered
packets.

## Test Plan

1. Query the server using refresh on the server browser
2. Uncheck QueryResponseS2c in the packet-selector list
3. Click HandshakeC2s
4. Press down arrow until last packet is selected
5. It shouldn't go "blank" anymore when going from QueryRequestC2s to
QueryPingC2s

As an additive request, I've removed the regex check from the main GUI
filter box, such that this is now case-insensitive when filtering
specific packets.
CLI still uses regex to be able to filter on multiple packets
(unchanged)
2023-03-21 23:49:44 -07:00
Ryan Johnson 4cf6e1a207
Entity Rework (#294)
## Description

Closes #269
Closes #199 

- Removes `McEntity` and replaces it with bundles of components, one for
each entity type.
- Tracked data types are now separate components rather than stuffing
everything into a `TrackedData` enum.
- Tracked data is now cached in binary form within each entity,
eliminating some work when entities enter the view of clients.
- Complete redesign of entity code generator.
- More docs for some components.
- Field bits are moved out of the entity extractor and into the valence
entity module.
- Moved hitbox code to separate module.
- Refactor instance update systems to improve parallelism.

### TODOs
- [x] Update examples.
- [x] Update `default_event_handler`.
- [x] Fix bugs.

## Test Plan

Steps:
1. Check out the entity module docs with `cargo d --open`.
2. Run examples.
2023-03-21 23:29:38 -07:00
qualterz c9fbd1a24e
Weather implementation (#260)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

<!-- Describe the changes you've made. You may include any justification
you want here. -->

An implementation of basic weather systems.

The weather component attached to a world instance would be handled for
all clients, except those that have their own weather component; these
clients would be handled separately.

## Test Plan

<!-- Explain how you tested your changes, and include any code that you
used to test this. -->
<!-- If there is an example that is sufficient to use in place of a
playground, replace the playground section with a note that indicates
this. -->

<details>

<summary>Playground</summary>

```rust
fn handle_command_events(
    instances: Query<Entity, With<Instance>>,
    mut exec_cmds: EventReader<CommandExecution>,
    mut commands: Commands,
) {
    for cmd in exec_cmds.iter() {
        let msg = cmd.command.to_string();
        let ent = instances.single();

        match msg.as_str() {
            "ar" => {
                commands.entity(ent).insert(Rain(WEATHER_LEVEL.end));
            }
            "rr" => {
                commands.entity(ent).remove::<Rain>();
            }
            "at" => {
                commands.entity(ent).insert(Thunder(WEATHER_LEVEL.end));
            }
            "rt" => {
                commands.entity(ent).remove::<Thunder>();
            }
            _ => (),
        };
    }
}
```

</details>

<!-- You need to include steps regardless of whether or not you are
using a playground. -->
Steps:
1. Run `cargo test --package valence --lib -- weather::test`

#### Related
Part of #210
Past approach #106

<!-- Link to any issues that have context for this or that this PR
fixes. -->
2023-03-16 08:43:26 -04:00
Ryan Johnson 2c0fb2d8c4
Refactor Schedule (#289)
## Description

- Tweak the system schedule to be more parallel-friendly and explicit.
Dependencies between systems is clearer.
- System and resource configuration is better encapsulated in each
module by using plugins.

The schedule graph for `Main` now looks like this (using
`bevy_mod_debugdump`):


![graph](https://user-images.githubusercontent.com/31678482/225321113-0ec4f4dd-86f6-45fe-8158-12a451536770.svg)

### Unresolved

- What to do about ambiguous systems? Many systems here are ambiguous
because they take `&mut Client`, but the order they write packets isn't
really important. Marking them as ambiguous explicitly with
`.ambiguous_with*` across module boundaries seems difficult and
cumbersome.

## Test Plan

Steps:
1. Run examples. Check that I didn't screw up the system order.
2023-03-15 16:12:59 -07:00
Joe Sorensen 255b78e02c
tiny one line change to fix writing packets not working (#290)
## Description

With component division, the WritePacket trait was pub(crate), which
disallowed writing packets outside of valence. This 1 line PR fixes
that.

## Test Plan

It might be a good idea to include examples/tests that use packet
writing to catch this, but it's most likely not strictly necessary.
2023-03-15 07:36:55 -07:00
AviiNL 68cf6e83a0
Abstract scoreboard display position (#286)
## Description

The scoreboard display packet has a position field that can contain one
of the following:
- 0: List
- 1: Sidebar
- 2: BelowName
- 3..=18: Team specific sidebar indexed as 3 + team color (according to
wiki.vg)

I'm not really sure how team specific sidebars are supposed to work, so
left that as a byte, maybe that can have some more abstraction?

## Test Plan

<details>

<summary>Playground</summary>

```rust
use valence::client::despawn_disconnected_clients;
use valence::client::event::default_event_handler;
use valence::prelude::*;
use valence::protocol::packet::s2c::play::scoreboard_display::ScoreboardPosition;
use valence::protocol::packet::s2c::play::scoreboard_objective_update::{Mode, RenderType};
use valence::protocol::packet::s2c::play::scoreboard_player_update::Action;
use valence::protocol::packet::s2c::play::{
    ScoreboardDisplayS2c, ScoreboardObjectiveUpdateS2c, ScoreboardPlayerUpdateS2c,
};
use valence::protocol::var_int::VarInt;

const SPAWN_Y: i32 = 64;

pub fn build_app(app: &mut App) {
    app.add_plugin(ServerPlugin::new(()))
        .add_system(default_event_handler.in_schedule(EventLoopSchedule))
        .add_startup_system(setup)
        .add_system(init_clients)
        .add_system(scoreboard)
        .add_system(despawn_disconnected_clients)
        .add_systems(PlayerList::default_systems());
}

fn setup(mut commands: Commands, server: Res<Server>) {
    let mut instance = server.new_instance(DimensionId::default());

    for z in -5..5 {
        for x in -5..5 {
            instance.insert_chunk([x, z], Chunk::default());
        }
    }

    for z in -25..25 {
        for x in -25..25 {
            instance.set_block([x, SPAWN_Y, z], BlockState::GRASS_BLOCK);
        }
    }

    commands.spawn(instance);
}

fn init_clients(
    mut clients: Query<&mut Client, Added<Client>>,
    instances: Query<Entity, With<Instance>>,
) {
    for mut client in &mut clients {
        client.set_position([0.0, SPAWN_Y as f64 + 1.0, 0.0]);
        client.set_instance(instances.single());
        client.set_game_mode(GameMode::Creative);
    }
}

// Add new systems here!
fn scoreboard(mut clients: Query<&mut Client, Added<Client>>) {
    for mut client in &mut clients {
        client.write_packet(&ScoreboardObjectiveUpdateS2c {
            objective_name: "sidebar",
            mode: Mode::Create {
                objective_display_name: "Sidebar".into_text(),
                render_type: RenderType::Integer,
            },
        });
        client.write_packet(&ScoreboardPlayerUpdateS2c {
            action: Action::Update {
                objective_score: VarInt(42),
                objective_name: "sidebar",
            },
            entity_name: "name",
        });
        client.write_packet(&ScoreboardDisplayS2c {
            position: ScoreboardPosition::Sidebar, // Position is now an Enum
            score_name: "sidebar",
        });
    }
}
```

</details>

---------

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2023-03-12 04:51:49 -07:00
Ryan Johnson 41907261e3
Update feature_request.md
Removed line break.
2023-03-11 20:07:00 -08:00
Ryan Johnson 5300e6478a
Replace yaml issue templates with markdown templates (#287)
## Description

Replaces the issue forms with the old markdown issue templates. Some
details have changed too.

I've found the issue forms to be inflexible and the interface a bit
clunky. We can switch back if the situation improves.
2023-03-11 20:04:46 -08:00
Ryan Johnson b46cc502aa
Client Component Division (#266)
## Description

Divides the `Client` component into a set of smaller components as
described by #199 (with many deviations). `McEntity` will be dealt with
in a future PR.

- Divide `Client` into smaller components (There's a lot to look at).
- Move common components to `component` module.
- Remove `Username` type from `valence_protocol` because the added
complexity wasn't adding much benefit.
- Clean up the inventory module.

I've stopped worrying about the "Effect When Added" and "Effect When
Removed" behavior of components so much, and instead assume that all
components of a particular thing are required unless otherwise stated.

## Test Plan

Steps:
1. Run examples and tests.

A large number of tweaks have been made to the inventory module. I tried
to preserve semantics but I could have made a mistake there.

---------

Co-authored-by: Carson McManus <dyc3@users.noreply.github.com>
Co-authored-by: Carson McManus <carson.mcmanus1@gmail.com>
2023-03-11 06:04:14 -08:00
Guac 8bd20e964e
Fix ScoreboardPlayerUpdate packet (#285)
## Description

Fix the contents of the `ScoreboardPlayerUpdateS2c` packet resolving
#284.

## Test Plan

Run the included playground code.

<details>

<summary>Playground</summary>

```rust
use valence::client::despawn_disconnected_clients;
use valence::client::event::default_event_handler;
use valence::prelude::*;
use valence::protocol::packet::s2c::play::scoreboard_objective_update::{Mode, RenderType};
use valence::protocol::packet::s2c::play::scoreboard_player_update::Action;
use valence::protocol::packet::s2c::play::{
    ScoreboardObjectiveUpdateS2c, ScoreboardPlayerUpdateS2c,
};
use valence::protocol::var_int::VarInt;

pub fn build_app(app: &mut App) {
    app.add_plugin(ServerPlugin::new(()))
        .add_system(default_event_handler.in_schedule(EventLoopSchedule))
        .add_startup_system(setup)
        .add_system(init_clients)
        .add_system(scoreboard)
        .add_system(despawn_disconnected_clients);
}

fn setup(world: &mut World) {
    let mut instance = world
        .resource::<Server>()
        .new_instance(DimensionId::default());

    for z in -5..5 {
        for x in -5..5 {
            instance.insert_chunk([x, z], Chunk::default());
        }
    }

    world.spawn(instance);
}

fn init_clients(
    mut clients: Query<&mut Client, Added<Client>>,
    instances: Query<Entity, With<Instance>>,
) {
    let instance = instances.get_single().unwrap();

    for mut client in &mut clients {
        client.set_instance(instance);
    }
}

// Add new systems here!
fn scoreboard(mut clients: Query<&mut Client, Added<Client>>) {
    for mut client in &mut clients {
        client.write_packet(&ScoreboardObjectiveUpdateS2c {
            objective_name: "test",
            mode: Mode::Create {
                objective_display_name: "test display".into_text(),
                render_type: RenderType::Integer,
            },
        });
        client.write_packet(&ScoreboardPlayerUpdateS2c {
            action: Action::Update {
                objective_score: VarInt(0),
                objective_name: "test",
            },
            entity_name: "name",
        });
        client.write_packet(&ScoreboardPlayerUpdateS2c {
            action: Action::Remove {
                objective_name: "test",
            },
            entity_name: "name",
        });
    }
}

```

</details>
2023-03-11 02:41:48 -08:00
AviiNL 104fbedf4c
Packet inspector updates (#283)
## Description

Updated packet inspector to have a more clear indication of which packet
is selected, and added up and down keybinds for selecting previous and
next packet respectively
2023-03-10 03:57:55 -08:00
AviiNL cd7dd8cc4c
Fix Particle packet id (#281)
Fixes #267

## Description

Swap packet ids `ParticleS2c` with `LightUpdateS2c`

## Test Plan

Steps:
1. Run the `particles.rs` example
2023-03-09 04:02:03 -08:00
AviiNL 491e3a61d7
Packet inspector gui (#238)
Fixes #235

## Description

A GUI Project for the packet inspector

## Test Plan

Steps:
1. Start (any) server
2. Start the proxy `cargo r -r -p packet_inspector_gui --
127.0.0.1:25560 127.0.0.1:25565`
3. Join server (127.0.0.1:25560)
4. Magic
2023-03-09 03:09:53 -08:00
AviiNL 52fadb6dd8
Rename valence_protocol to valence::protocol (#280)
## Description

Replaced the remaining `valence_protcol` with `valence::protocol` in the
examples
2023-03-09 03:08:31 -08:00
wjwzpeajhc 7cd483afb7
Replaced valence_protocol and valence_nbt imports with valence ones (#279)
## Description

This PR replace `valence_protocol` and `valence_nbt` imports in
`crates/valence/examples` with `valence` ones so you don't have to
change imports or import the crates when you copy the examples and have
only `valence` as a dependency.
2023-03-08 14:18:56 -08:00
AviiNL 4c0f070d27
Add caching layer to CI (#277)
Added a caching layer to the CI

This creates a cache on first run (should exist because of this pr now)
The hash is calculated from the Cargo.toml files (recursively if i've
done it correctly)
So whenever a Cargo.toml file changes, it invalidates the cache.

Local crates are _not_ cached, so they get recompiled regardless, but it
already shaves off like half the total time from the action runners.
2023-03-08 11:51:47 -05:00
Ryan Johnson e933fd69f5
Add RawPacket (#276)
## Description

Adds a `RawPacket` type to `valence_protocol`. This type simply reads
and writes data to a slice, analogous to the `RawBytes` type in the same
module.

## Test Plan

Steps:
1. `cargo t -p valence_protocol`
2023-03-07 20:15:30 -08:00
Ryan Johnson 4a541a907a
Tweak templates (#273)
## Description

Change the issue and pull request templates.

- Remove HTML comments from the markdown because it's often not deleted
and takes up space in the final commit description.
- Remove the "related" section in the PR template because links to other
issues will naturally end up in the "description" section.
- Remove some placeholder text in the feature request template.
- Remove the check boxes from the bug report template to avoid creating
"tasks".
- The number of sections in the bug report template was a bit daunting
IMO so I trimmed it down a bit.

Co-authored-by: Carson McManus <dyc3@users.noreply.github.com>
2023-03-07 08:01:30 -05:00
Ryan e49ab70f16 Fix typo in packet_group macro 2023-03-07 04:23:11 -08:00
Ryan Johnson e64f1b7123
Add packet_name (#274)
## Description

Adds `packet_name` method to the `Packet` trait to help with #238.

## Test Plan

Steps:
1. `cargo t -p valence_protocol`
2023-03-07 04:12:08 -08:00
Ryan Johnson a69cc5d1c3
Tweak README.md 2023-03-06 19:48:20 -08:00
Ryan Johnson 7e7af6e7c1
Set bevy version to 0.10 (#272)
## Description

Sets Bevy dependencies to version 0.10 instead of the previous commit
hash.
2023-03-06 18:50:48 -08:00
Ryan Johnson 190a60a13a
Emphasize project status in README.md 2023-03-06 15:41:32 -08:00
Carson McManus 9f8ff321c7
Inventory module docs and more helper functions (#268)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

<!-- Describe the changes you've made. You may include any justification
you want here. -->

This mostly adds docs, but it also adds (and documents) some new helper
functions:

- `set_title()` - Allows us to put `must_use` on `replace_title`
- `set_slot()` - Allows us to put `must_use` on `replace_slot`
- `set_slot_amount()` - Allows users to modify stack counts without
cloning the entire stack and replacing it. Useful if the stack has a lot
of NBT data.
- `first_empty_slot()`
- `first_empty_slot_in()` - Useful, trivial to provide

## Test Plan

<!-- Explain how you tested your changes, and include any code that you
used to test this. -->
<!-- If there is an example that is sufficient to use in place of a
playground, replace the playground section with a note that indicates
this. -->

<details>

<summary>Playground</summary>

```rust
N/A
```

</details>

<!-- You need to include steps regardless of whether or not you are
using a playground. -->
Steps:
1. `cargo test -p valence --doc`

#### Related

<!-- Link to any issues that have context for this or that this PR
fixes. -->
2023-03-04 16:31:21 -08:00
Ryan Johnson 62f882eec7
Update to Bevy 0.10 (#265)
## Description

Fix #264

Bevy version is pinned to a recent commit on the main branch until 0.10
is released.

## Test Plan

Run examples and tests. Behavior should be the same.

scheduling is a bit tricky so I may have made some subtle mistakes.
2023-03-04 03:35:11 -08:00
Supermath101 cc2571d7e6
Changed setup() to not be an exclusive system (#258)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

In the [examples of the `valence`
crate](https://github.com/valence-rs/valence/tree/main/crates/valence/examples),
the `setup()` functions are currently [exclusive
systems](https://bevy-cheatbook.github.io/programming/exclusive.html).
My reasoning for making these a standard system is twofold:
- Exclusive systems can be considered an advanced Bevy topic. I don't
think you should be using advanced concepts in examples meant to be an
introduction to the way this project/framework is used.
- In instances where developers try to use these examples, adding
another startup system would result is running the systems sequentially.
That leaves performance on the table (albeit only during startup).

---------

Co-authored-by: Supermath101 <unknown>
Co-authored-by: Supermath101 <>
2023-02-27 12:13:56 -08:00
Ryan Johnson 7af119da72
Replace EncodePacket and DecodePacket with Packet (#261)
## Description

Combines the `EncodePacket` and `DecodePacket` trait into a single
`Packet` trait. This makes `valence_protocol` simpler and easier to use.
This can be done because all packets were made to be bidirectional in
#253.

Additionally, a `packet_id` method has been added. This should help with
#238.

## Test Plan

Steps:
1. Run examples, packet_inspector, etc. Behavior should be the same.
2023-02-25 11:21:25 -08:00
Ryan Johnson 6e8ebbe000
Fix CI (#259)
Gets CI working again by switching to `macos-11` from `macos-latest`.

No idea why it works. We should switch back to `macos-latest`
eventually.
2023-02-24 18:26:26 -08:00
Ryan Johnson 0960ad7ead
Refactor valence_protocol (#253)
## Description

- Remove duplicate packet definitions by using `Cow`.
- Rename packets to match yarn mappings.
- Remove some top-level re-exports.
- Move every packet into its own module for consistency.
- Move packet-specific types from the `types` module into the
appropriate packet module.
- Remove internal use of `EncodePacket`/`DecodePacket` derives and move
packet identification to `packet_group`. This can be done because there
are no duplicate packets anymore.
- Simplify some events.

In a future PR I plan to clean things up further by properly bounding
packet data (to prevent DoS exploits) and fixing any remaining
inconsistencies with the game's packet definitions.

## Test Plan

Behavior of `valence_protocol` should be the same.

Steps:
1. Use the packet inspector against the vanilla server to ensure packet
behavior has not changed.
2. Run the examples.
3. Run `valence_stresser`.
2023-02-23 22:16:22 -08:00
Jade Ellis 9931c8a80b
Provide API for getting the wall variant of blocks (#255)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

This adds an API for getting the wall / attachable variant of a block. 
Unlike #117 it does not add convenience methods for orientation, and it
does not modify the example to use this code.

## Test Plan

<!-- Explain how you tested your changes, and include any code that you
used to test this. -->
<!-- If there is an example that is sufficient to use in place of a
playground, replace the playground section with a note that indicates
this. -->

The extractor is not tested. 
The API has some tests in the test module.

#### Related

<!-- Link to any issues that have context for this or that this PR
fixes. -->

#115 - it does not fix this, as it doesn't modify the example, but it
could lead to it.

---------

Co-authored-by: EmperialDev <saroke.dev@gmail.com>
2023-02-23 21:21:27 -08:00
Jade Ellis 7cd059b9b3
Add a minimal chat example (#248)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

Take 3 of #247.

I've added a minimal chat example - ignoring chat signing, etc. It's in
the file `crates/valence/examples/chat.rs`.

## Test Plan

Manual, unfortunately :(

Steps:
1. Open two minecraft clients, with two separate accounts (or usernames
if using offline mode)
2. Connect to the server in both clients
3. Type a chat message, checking it appears to both clients, with the
correct username.
4. Type a command, checking it appears only to the sender.

---------

Co-authored-by: Carson McManus <dyc3@users.noreply.github.com>
2023-02-21 09:28:07 -05:00
qualterz 1cd6be0781
Minimal stresser implementation (#240)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

<!-- Describe the changes you've made. You may include any justification
you want here. -->

An implementation of a Minecraft server stresser for testing purposes.

The potential of this pull request is to implement a minimal stresser
binary package that would be bound to the local `valence_protocol`
package, so it would be always up to date with the latest Valence
Minecraft protocol implementation.

The MVP version is going to be able concurrently connect headless
clients to a target Minecraft server.

## Test Plan

<!-- Explain how you tested your changes, and include any code that you
used to test this. -->
<!-- If there is an example that is sufficient to use in place of a
playground, replace the playground section with a note that indicates
this. -->

<!-- <details>

<summary>Playground</summary>

```rust
PASTE YOUR PLAYGROUND CODE HERE
```

</details> -->

<!-- You need to include steps regardless of whether or not you are
using a playground. -->
Steps:
1. Ensure that the connection mode is offline
2. Run `cargo run --example bench_players` or any other example
3. Run `cargo run --package valence_stresser -- --target 127.0.0.1:25565
--count 1000`
4. Monitor the `bench_players` output
 
#### Related

closes #211

---------

Co-authored-by: Carson McManus <dyc3@users.noreply.github.com>
2023-02-21 08:54:16 -05:00
Carson McManus 0319635a8b
Implement Drop Item Events (#252)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

<!-- Describe the changes you've made. You may include any justification
you want here. -->
Dropping items is heavily coupled to inventories. Clients also predict
state changes when they try to drop items, so we need to be able to
replicate that change in order to stay in sync.

This will also remove `DropItem` events in favor of just `DropItemStack`
events. Having 2 event streams that basically mean the same thing seems
verbose and error prone.

As of right now, these changes require the event loop to have a
reference to the client's inventory. This seems like something we are
going to need to do a lot more of to complete #199.

## Test Plan

<!-- Explain how you tested your changes, and include any code that you
used to test this. -->
<!-- If there is an example that is sufficient to use in place of a
playground, replace the playground section with a note that indicates
this. -->

<details>

<summary>Playground</summary>

```rust
use tracing::info;
use valence::client::despawn_disconnected_clients;
use valence::client::event::{default_event_handler, DropItemStack};
use valence::prelude::*;

#[allow(unused_imports)]
use crate::extras::*;

const SPAWN_Y: i32 = 64;

pub fn build_app(app: &mut App) {
    app.add_plugin(ServerPlugin::new(()).with_connection_mode(ConnectionMode::Offline))
        .add_system_to_stage(EventLoop, default_event_handler)
        .add_startup_system(setup)
        .add_system(init_clients)
        .add_system(despawn_disconnected_clients)
        .add_system(toggle_gamemode_on_sneak)
        .add_system(drop_items);
}

fn setup(world: &mut World) {
    let mut instance = world
        .resource::<Server>()
        .new_instance(DimensionId::default());

    for z in -5..5 {
        for x in -5..5 {
            instance.insert_chunk([x, z], Chunk::default());
        }
    }

    for z in -25..25 {
        for x in -25..25 {
            instance.set_block([x, SPAWN_Y, z], BlockState::GRASS_BLOCK);
        }
    }

    world.spawn(instance);
}

fn init_clients(
    mut clients: Query<&mut Client, Added<Client>>,
    instances: Query<Entity, With<Instance>>,
) {
    let instance = instances.get_single().unwrap();

    for mut client in &mut clients {
        client.set_position([0.5, SPAWN_Y as f64 + 1.0, 0.5]);
        client.set_instance(instance);
        client.set_game_mode(GameMode::Creative);
    }
}

fn drop_items(clients: Query<&Client>, mut drop_stack_events: EventReader<DropItemStack>) {
    if drop_stack_events.is_empty() {
        return;
    }

    for event in drop_stack_events.iter() {
        info!("drop stack: {:?}", event);
    }
}

```

</details>

<!-- You need to include steps regardless of whether or not you are
using a playground. -->
Steps:
1. `cargo test -p valence --tests`
2. Run playground `cargo run -p playground`
3. Open creative menu
4. Pick an item and click to drop it outside of the creative menu
5. Pick an entire stack of an item, place it in your hotbar
6. Hover over the item, press your drop key to drop an item from the
stack
7. Press shift to switch to survival
8. Select the item stack in your hotbar, press your drop key to drop an
item from the stack
9. Open your inventory, grab the stack, hover outside the window and
click to drop the entire stack
10. Grab another stack from creative, place it in your hotbar
11. switch back to survival, select the stack, and press your control +
drop key to drop the entire stack
12. For each item you dropped, you should see a log message with the
event

#### Related

<!-- Link to any issues that have context for this or that this PR
fixes. -->
2023-02-20 15:37:09 -08:00
Ryan Johnson 7d05cb8309
Block entity fixes (#251)
Clean up unresolved issues from #32
2023-02-19 12:26:32 -08:00
Mrln 1ceafe0ce0
Add block entities (#32)
This PR aims to add block entities.
Fixes #5

---------

Co-authored-by: Ryan Johnson <ryanj00a@gmail.com>
2023-02-18 10:16:01 -08:00
Ryan Johnson bcd686990d
Tweak README.md 2023-02-17 14:05:10 -08:00
Ryan Johnson 286e6aa0d0
Fix CI (#245)
## Description

Attempting to fix the CI failures in #32 by switching to the stable
toolchain.
2023-02-16 19:48:55 -08:00
Gingeh 50018a52bf
Add sounds (#244)
This is my first time contributing here so I was pretty unfamiliar with
the codebase and may have done some things incorrectly.

## Description
 - Added a sound extractor to extract sound event ids and identifiers
 - Added a `Sound` enum (with a build script) to represent sound effects
 - Added a `play_sound` method to `Instance` and `Client`
 - Re-implemented sound effects in the parkour example

## Test Plan
I tested this using the sounds I added to the parkour example.

#### Related
Hopefully fixes #206
2023-02-15 02:36:21 -08:00
Riley Sutton bee44d32b5
Add ping calculation system (#243)
## Description

Add the ping computation system and capability to send ping to
connecting clients.

Currently the player list will only update upon connection. Should
another ticket be made for updating this since it seems out of scope for
this issue?

## Test Plan

Printing ping per keepalive packet on a different computer on my
network. It seems to work fine but would need extra feedback.

#### Related

#207
2023-02-14 22:22:14 -08:00
Joel Ellis f0027aa097
Colorise the inspector output based on S2C or C2S (#242)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

<!-- Describe the changes you've made. You may include any justification
you want here. -->
I've used the popular `owo-colors` library to colourise the output of
the `packet_inspector`.
This makes it a lot easier to see who's sending what for debugging
purposes.

In future, I'd like to be able to filter out common, low-information
packets like `SetPlayerPosition` and `KeepAlive` as well, but that's not
in this PR.


![image](https://user-images.githubusercontent.com/28905212/218880818-69c0461c-bd23-45c4-9fd4-7c5868be4b67.png)

## Test Plan

No tests - just eyeball 😄.
2023-02-14 15:31:17 -08:00
Ryan Johnson 909f7d3909
Clean up dimension/biome code (#239) 2023-02-14 03:36:52 -08:00
Guac c494b83a56
VarInt/VarLong Encode and Decode Optimizations (#227)
Aims to improve upon VarInt/VarLong Encode and Decode procedures (#208).
# Baselines:
## VarInt:

![VarInt::decode](https://user-images.githubusercontent.com/60993440/218295740-c7507993-1c1f-4d71-a42b-4ba9f1437bd7.png)

![VarInt::encode](https://user-images.githubusercontent.com/60993440/218295804-3cda044a-e2e4-4109-83ce-6e0a135d467b.png)
## VarLong

![VarLong::encode](https://user-images.githubusercontent.com/60993440/218295958-e445c2ea-ec2e-422f-92a4-d53bf41c8ec4.png)

![VarLong::decode](https://user-images.githubusercontent.com/60993440/218296047-802cec4a-b69b-435b-a140-0d9bf5df49a8.png)
2023-02-14 03:04:32 -08:00
Carson McManus e1a3e2dc00
make dropping an item in creative not crash the server (#234)
<!-- Please make sure that your PR is aligned with the guidelines in
CONTRIBUTING.md to the best of your ability. -->
<!-- Good PRs have tests! Make sure you have sufficient test coverage.
-->

## Description

<!-- Describe the changes you've made. You may include any justification
you want here. -->
Added a quick and dirty bounds check because we haven't created drop
item/itemstack event(s) yet.

## Test Plan

<!-- Explain how you tested your changes, and include any code that you
used to test this. -->
<!-- If there is an example that is sufficient to use in place of a
playground, replace the playground section with a note that indicates
this. -->

use the `building` example

<!-- You need to include steps regardless of whether or not you are
using a playground. -->
Steps:
1. `cargo run --example building`
2. open inventory
3. pick an item
4. drop the item outside of the inventory window
5. see that the server does not panic

#### Related

<!-- Link to any issues that have context for this or that this PR
fixes. -->
fixes #233
2023-02-11 20:04:52 -08:00
Ryan Johnson cb9230ec34
ECS Rewrite (#184)
This PR redesigns Valence's architecture around the Bevy Entity
Component System framework (`bevy_ecs` and `bevy_app`). Along the way, a
large number of changes and improvements have been made.
- Valence is now a Bevy plugin. This allows Valence to integrate with
the wider Bevy ecosystem.
- The `Config` trait has been replaced with the plugin struct which is
much easier to configure. Async callbacks are grouped into their own
trait.
- `World` has been renamed to `Instance` to avoid confusion with
`bevy_ecs::world::World`.
- Entities, clients, player list, and inventories are all just ECS
components/resources. There is no need for us to have our own
generational arena/slotmap/etc for each one.
- Client events use Bevy's event system. Users can read events with the
`EventReader` system parameter. This also means that events are
dispatched at an earlier stage of the program where access to the full
server is available. There is a special "event loop" stage which is used
primarily to avoid the loss of ordering information between events.
- Chunks have been completely overhauled to be simpler and faster. The
distinction between loaded and unloaded chunks has been mostly
eliminated. The per-section bitset that tracked changes has been
removed, which should further reduce memory usage. More operations on
chunks are available such as removal and cloning.
- The full client's game profile is accessible rather than just the
textures.
- Replaced `vek` with `glam` for parity with Bevy.
- Basic inventory support has been added.
- Various small changes to `valence_protocol`.
- New Examples
- The terrain and anvil examples are now fully asynchronous and will not
block the main tick loop while chunks are loading.

# TODOs
- [x] Implement and dispatch client events.
- ~~[ ] Finish implementing the new entity/chunk update algorithm.~~ New
approach ended up being slower. And also broken.
- [x] [Update rust-mc-bot to
1.19.3](https://github.com/Eoghanmc22/rust-mc-bot/pull/3).
- [x] Use rust-mc-bot to test for and fix any performance regressions.
Revert to old entity/chunk update algorithm if the new one turns out to
be slower for some reason.
- [x] Make inventories an ECS component.
- [x] Make player lists an ECS ~~component~~ resource.
- [x] Expose all properties of the client's game profile.
- [x] Update the examples.
- [x] Update `valence_anvil`.
- ~~[ ] Update `valence_spatial_index` to use `glam` instead of `vek`.~~
Maybe later
- [x] Make entity events use a bitset.
- [x] Update docs.

Closes #69
Closes #179
Closes #53

---------

Co-authored-by: Carson McManus <dyc3@users.noreply.github.com>
Co-authored-by: AviiNL <me@avii.nl>
Co-authored-by: Danik Vitek <x3665107@gmail.com>
Co-authored-by: Snowiiii <71594357+Snowiiii@users.noreply.github.com>
2023-02-11 09:51:53 -08:00
Guac 44ea6915db
Implement remaining clientbound packets (#197)
Aims to close #186
2023-02-03 22:30:12 -08:00
Ryan Johnson 9f8250d4f9
Update README.md with current project status. 2023-02-03 19:04:54 -08:00
CaveNightingale ca269cd03e
Add a simple SNBT parser (#201)
To implement the hoverEvent show_item, we need an SNBT parser and a SNBT
serializer.
An SNBT parser is implemented in this commit.
2023-02-03 03:16:27 -08:00