Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement world border #364

Merged
merged 8 commits into from
Jun 15, 2023
Merged

Implement world border #364

merged 8 commits into from
Jun 15, 2023

Conversation

tachibanayui
Copy link
Contributor

Description

Basic implementation of world border
World border is not enabled by default. It can be enabled by inserting WorldBorderBundle bundle. Currently, this PR only implements world borders per instance, I'm considering expanding this per client. However, the same functionality can be achieved by Visibility Layers #362

Playground:
fn border_controls(
    mut events: EventReader<ChatMessageEvent>,
    mut instances: Query<(Entity, &WorldBorderDiameter, &mut WorldBorderCenter), With<Instance>>,
    mut event_writer: EventWriter<SetWorldBorderSizeEvent>,
) {
    for x in events.iter() {
        let parts: Vec<&str> = x.message.split(' ').collect();
        match parts[0] {
            "add" => {
                let Ok(value) = parts[1].parse::<f64>() else {
                    return;
                };

                let Ok(speed) = parts[2].parse::<i64>() else {
                    return;
                };

                let Ok((entity, diameter, _)) = instances.get_single_mut() else {
                    return;
                };

                event_writer.send(SetWorldBorderSizeEvent {
                    instance: entity,
                    new_diameter: diameter.diameter() + value,
                    speed,
                })
            }
            "center" => {
                let Ok(x) = parts[1].parse::<f64>() else {
                    return;
                };

                let Ok(z) = parts[2].parse::<f64>() else {
                    return;
                };

                instances.single_mut().2 .0 = DVec2 { x, y: z };
            }
            _ => (),
        }
    }
}

example: cargo run --package valence --example world_border
tests: cargo test --package valence --lib -- tests::world_border

Related
part of #210

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to have doc comments instead of an example for this. We're trying to cut down on the number of examples because of the maintenance workload.

Can you update your playground to use the entire template? It makes it easier to switch between playgrounds if we can just copy and paste the entire file.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I plan to provide both examples and module-level documentation (which I'm currently writing).

Here is the entire playground:

use valence::client::chat::ChatMessageEvent;
use valence::client::despawn_disconnected_clients;
use valence::client::world_border::{
    SetWorldBorderSizeEvent, WorldBorderBundle, WorldBorderCenter, WorldBorderDiameter,
};
use valence::network::ConnectionMode;
use valence::prelude::*;

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

const SPAWN_Y: i32 = 64;

pub fn build_app(app: &mut App) {
    app.insert_resource(NetworkSettings {
        connection_mode: ConnectionMode::Offline,
        ..Default::default()
    })
    .add_plugins(DefaultPlugins)
    .add_startup_system(setup)
    .add_system(init_clients)
    .add_system(despawn_disconnected_clients)
    .add_system(toggle_gamemode_on_sneak.in_schedule(EventLoopSchedule))
    .add_system(border_controls);
}

fn setup(
    mut commands: Commands,
    server: Res<Server>,
    biomes: Res<BiomeRegistry>,
    dimensions: Res<DimensionTypeRegistry>,
) {
    let mut instance = Instance::new(ident!("overworld"), &dimensions, &biomes, &server);

    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)
        .insert(WorldBorderBundle::new([0.0, 0.0], 10.0));
}

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

fn border_controls(
    mut events: EventReader<ChatMessageEvent>,
    mut instances: Query<(Entity, &WorldBorderDiameter, &mut WorldBorderCenter), With<Instance>>,
    mut event_writer: EventWriter<SetWorldBorderSizeEvent>,
) {
    for x in events.iter() {
        let parts: Vec<&str> = x.message.split(' ').collect();
        match parts[0] {
            "add" => {
                let Ok(value) = parts[1].parse::<f64>() else {
                    return;
                };

                let Ok(speed) = parts[2].parse::<i64>() else {
                    return;
                };

                let Ok((entity, diameter, _)) = instances.get_single_mut() else {
                    return;
                };

                event_writer.send(SetWorldBorderSizeEvent {
                    instance: entity,
                    new_diameter: diameter.diameter() + value,
                    speed,
                })
            }
            "center" => {
                let Ok(x) = parts[1].parse::<f64>() else {
                    return;
                };

                let Ok(z) = parts[2].parse::<f64>() else {
                    return;
                };

                instances.single_mut().2 .0 = DVec2 { x, y: z };
            }
            _ => (),
        }
    }
}

Copy link
Member

@rj00a rj00a Jun 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know I said I didn't want to have a bunch of small examples, but I've changed my mind on this issue somewhat. Not relevant for this PR, but in the future we should separate "here's how to use this API" examples (like this one) from "here's a complete minigame" examples (like parkour.rs).

crates/valence_client/src/world_border.rs Outdated Show resolved Hide resolved
@tachibanayui tachibanayui requested a review from dyc3 June 13, 2023 17:36
Copy link
Collaborator

@dyc3 dyc3 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The playground and example work, but needs some changes.

Also, fix the clippy stuff

pub struct MovingWorldBorder {
pub old_diameter: f64,
pub new_diameter: f64,
pub speed: i64,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change speed to duration

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we use Duration instead of i64 here too?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, thats a good idea.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm leaning toward keeping speed as the name because I want it to closely resemble the underlying packet. The way I see this component as a low-level abstraction for sending border interpolation packet. I'll definitely change the one in event though because that one is mostly gonna be used by the user

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

speed implies that the number represents a rate of change, which is not correct. duration implies that the number indicates a span of time, which is correct.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find duration is a much better description too. But wiki.vg documents it as speed, so to avoid confusion, I decided to name it speed too. Should I rename it and make a doc comment about it?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

pub struct WorldBorderPortalTpBoundary(pub i32);

#[derive(Component)]
pub struct WorldBorderDiameter(f64);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a doc comment to this type to explain that you need to use the event to change the diameter.

Comment on lines 168 to 169
/// An event for controlling world border diameter. Please refer to the module documentation for example usage.
pub struct SetWorldBorderSizeEvent {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Show usage in the doc comment here

Comment on lines 148 to 154
#[derive(Component)]
pub struct MovingWorldBorder {
pub old_diameter: f64,
pub new_diameter: f64,
pub speed: i64,
pub timestamp: Instant,
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs doc comments to explain what these are. Do all the fields need to be public?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure commenting on each field is necessary because this struct is essentially the Set Border Lerp Size packet with a timestamp. I also believe that all fields should be public if we want to keep both Event and Component Change Tracking as ways to modify world border diameter

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, but the type still needs a brief comment to explain what it is.

/// The new diameter of the world border
pub new_diameter: f64,
/// How long the border takes to reach it new_diameter in millisecond. Set to 0 to move immediately.
pub speed: i64,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change speed to duration

@tachibanayui tachibanayui requested a review from dyc3 June 13, 2023 19:54
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd move all this code to an optional valence_world_border crate since it doesn't make much sense for this to be in valence_client. Bring the world border packets with you.

}
}

fn border_controls(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This panics in multiple different ways when the user input is invalid. I suggest demonstrating world border functionality without user input to keep the example focused. Perhaps changing the world border diameter and center on a timer or something.

event_writer.send(SetWorldBorderSizeEvent {
instance: entity,
new_diameter: diameter.diameter() + value,
duration: Duration::from_millis(speed as u64),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This disconnected me when I passed in a duration of zero.

failed to write packet: failed to encode field `old_diameter` in `WorldBorderInitializeS2c`: attempt to encode non-finite f64 (NaN)

Comment on lines 236 to 242
// This might be delayed by 1 tick
commands.entity(entity).insert(MovingWorldBorder {
new_diameter: *new_diameter,
old_diameter: diameter.diameter(),
duration: duration.as_millis() as i64,
timestamp: Instant::now(),
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the MovingWorldBorder component is included in the bundle it's best to just assume it's present.

pub struct WorldBorderDiameter(f64);

impl WorldBorderDiameter {
pub fn diameter(&self) -> f64 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub fn diameter(&self) -> f64 {
pub fn get(&self) -> f64 {

}

/// This component represents the `Set Border Lerp Size` packet with timestamp.
/// It is used for actually lerping the world border diamater.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// It is used for actually lerping the world border diamater.
/// It is used for actually lerping the world border diameter.

#[derive(Component)]
pub struct WorldBorderPortalTpBoundary(pub i32);

/// World border diameter can be read by querying
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// World border diameter can be read by querying
/// The world border diameter can be read by calling

To avoid confusion with ECS queries.

(diameter.0, 0)
};

ins.write_packet(&WorldBorderInitializeS2c {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This packet is being sent every tick. Did you forget to add Changed<WorldBorderTpBoundary>?

Change documentation as pointed out by rj
Updated examples
Fix divide by zero when setting duration of SetWorldBorderSizeEvent to 0
@tachibanayui tachibanayui requested a review from rj00a June 14, 2023 18:54
Copy link
Member

@rj00a rj00a left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a few more things.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this file was left here by accident.

//!
//! ## Querying world border diameter
//! World border diameter can be read by querying
//! [`WorldBorderDiameter::diameter()`]. Note: If you want to modify the
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
//! [`WorldBorderDiameter::diameter()`]. Note: If you want to modify the
//! [`WorldBorderDiameter::get()`]. Note: If you want to modify the

//! Access to the rest of the world border properties is fairly straight forward
//! by querying their respective component. [`WorldBorderBundle`] contains
//! references for all properties of world border and their respective component
#![allow(clippy::type_complexity)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs some more crate-level lints.

#![deny(
    rustdoc::broken_intra_doc_links,
    rustdoc::private_intra_doc_links,
    rustdoc::missing_crate_level_docs,
    rustdoc::invalid_codeblock_attributes,
    rustdoc::invalid_rust_codeblocks,
    rustdoc::bare_urls,
    rustdoc::invalid_html_tags
)]
#![warn(
    trivial_casts,
    trivial_numeric_casts,
    unused_lifetimes,
    unused_import_braces,
    unreachable_pub,
    clippy::dbg_macro
)]

(A future cargo feature will save us from having to paste this everywhere)

@@ -89,7 +89,9 @@ valence_nbt = { path = "crates/valence_nbt", features = ["uuid"] }
valence_network.path = "crates/valence_network"
valence_player_list.path = "crates/valence_player_list"
valence_registry.path = "crates/valence_registry"
valence_world_border.path = "crates/valence_world_border"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The graph in crates/README.md needs an update. Should have an edge going from world_border to client.

remove tests in world border crate
@tachibanayui tachibanayui requested a review from rj00a June 15, 2023 04:14
@rj00a rj00a merged commit 61f2279 into valence-rs:main Jun 15, 2023
@rj00a rj00a mentioned this pull request Jun 19, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants