Use idiomatic names

The Rust stdlib uses "Kind" instead of "Type".
This commit is contained in:
Ryan 2022-07-05 19:21:52 -07:00
parent fcda380f2a
commit 3ac711ca74
16 changed files with 147 additions and 147 deletions

View file

@ -14,14 +14,14 @@ pub fn build() -> anyhow::Result<()> {
let max_block_state = blocks.iter().map(|b| b.max_state_id).max().unwrap(); let max_block_state = blocks.iter().map(|b| b.max_state_id).max().unwrap();
let state_to_type = blocks let state_to_kind = blocks
.iter() .iter()
.map(|b| { .map(|b| {
let min = b.min_state_id; let min = b.min_state_id;
let max = b.max_state_id; let max = b.max_state_id;
let name = ident(b.name.to_pascal_case()); let name = ident(b.name.to_pascal_case());
quote! { quote! {
#min..=#max => BlockType::#name, #min..=#max => BlockKind::#name,
} }
}) })
.collect::<TokenStream>(); .collect::<TokenStream>();
@ -65,7 +65,7 @@ pub fn build() -> anyhow::Result<()> {
.collect::<TokenStream>(); .collect::<TokenStream>();
quote! { quote! {
BlockType::#block_type_name => match name { BlockKind::#block_type_name => match name {
#arms #arms
_ => None, _ => None,
}, },
@ -119,7 +119,7 @@ pub fn build() -> anyhow::Result<()> {
.collect::<TokenStream>(); .collect::<TokenStream>();
quote! { quote! {
BlockType::#block_type_name => match name { BlockKind::#block_type_name => match name {
#arms #arms
_ => self, _ => self,
}, },
@ -140,7 +140,7 @@ pub fn build() -> anyhow::Result<()> {
let filter_light = b.filter_light as u8; let filter_light = b.filter_light as u8;
quote! { quote! {
BlockType::#type_name => #filter_light, BlockKind::#type_name => #filter_light,
} }
}) })
.collect::<TokenStream>(); .collect::<TokenStream>();
@ -158,45 +158,45 @@ pub fn build() -> anyhow::Result<()> {
}) })
.collect::<TokenStream>(); .collect::<TokenStream>();
let type_to_state = blocks let kind_to_state = blocks
.iter() .iter()
.map(|b| { .map(|b| {
let typ = ident(b.name.to_pascal_case()); let kind = ident(b.name.to_pascal_case());
let state = ident(b.name.to_shouty_snake_case()); let state = ident(b.name.to_shouty_snake_case());
quote! { quote! {
BlockType::#typ => BlockState::#state, BlockKind::#kind => BlockState::#state,
} }
}) })
.collect::<TokenStream>(); .collect::<TokenStream>();
let block_type_variants = blocks let block_kind_variants = blocks
.iter() .iter()
.map(|b| ident(b.name.to_pascal_case())) .map(|b| ident(b.name.to_pascal_case()))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let block_type_from_str_arms = blocks let block_kind_from_str_arms = blocks
.iter() .iter()
.map(|b| { .map(|b| {
let name = &b.name; let name = &b.name;
let name_ident = ident(name.to_pascal_case()); let name_ident = ident(name.to_pascal_case());
quote! { quote! {
#name => Some(BlockType::#name_ident), #name => Some(BlockKind::#name_ident),
} }
}) })
.collect::<TokenStream>(); .collect::<TokenStream>();
let block_type_to_str_arms = blocks let block_kind_to_str_arms = blocks
.iter() .iter()
.map(|b| { .map(|b| {
let name = &b.name; let name = &b.name;
let name_ident = ident(name.to_pascal_case()); let name_ident = ident(name.to_pascal_case());
quote! { quote! {
BlockType::#name_ident => #name, BlockKind::#name_ident => #name,
} }
}) })
.collect::<TokenStream>(); .collect::<TokenStream>();
let block_type_props_arms = blocks let block_kind_props_arms = blocks
.iter() .iter()
.filter(|&b| !b.props.is_empty()) .filter(|&b| !b.props.is_empty())
.map(|b| { .map(|b| {
@ -209,7 +209,7 @@ pub fn build() -> anyhow::Result<()> {
}) })
.collect::<TokenStream>(); .collect::<TokenStream>();
let block_type_count = blocks.len(); let block_kind_count = blocks.len();
let prop_names = blocks let prop_names = blocks
.iter() .iter()
@ -305,16 +305,16 @@ pub fn build() -> anyhow::Result<()> {
impl BlockState { impl BlockState {
/// Returns the default block state for a given block type. /// Returns the default block state for a given block type.
pub const fn from_type(typ: BlockType) -> Self { pub const fn from_kind(kind: BlockKind) -> Self {
match typ { match kind {
#type_to_state #kind_to_state
} }
} }
/// Returns the [`BlockType`] of this block state. /// Returns the [`BlockKind`] of this block state.
pub const fn to_type(self) -> BlockType { pub const fn to_kind(self) -> BlockKind {
match self.0 { match self.0 {
#state_to_type #state_to_kind
_ => unreachable!(), _ => unreachable!(),
} }
} }
@ -351,7 +351,7 @@ pub fn build() -> anyhow::Result<()> {
/// ///
/// If this block does not have the property, then `None` is returned. /// If this block does not have the property, then `None` is returned.
pub const fn get(self, name: PropName) -> Option<PropValue> { pub const fn get(self, name: PropName) -> Option<PropValue> {
match self.to_type() { match self.to_kind() {
#get_arms #get_arms
_ => None _ => None
} }
@ -363,7 +363,7 @@ pub fn build() -> anyhow::Result<()> {
/// then the orginal block is returned unchanged. /// then the orginal block is returned unchanged.
#[must_use] #[must_use]
pub const fn set(self, name: PropName, val: PropValue) -> Self { pub const fn set(self, name: PropName, val: PropValue) -> Self {
match self.to_type() { match self.to_kind() {
#set_arms #set_arms
_ => self, _ => self,
} }
@ -372,27 +372,27 @@ pub fn build() -> anyhow::Result<()> {
/// If this block is `air`, `cave_air` or `void_air`. /// If this block is `air`, `cave_air` or `void_air`.
pub const fn is_air(self) -> bool { pub const fn is_air(self) -> bool {
matches!( matches!(
self.to_type(), self.to_kind(),
BlockType::Air | BlockType::CaveAir | BlockType::VoidAir BlockKind::Air | BlockKind::CaveAir | BlockKind::VoidAir
) )
} }
/// Is the block visually transparent? /// Is the block visually transparent?
pub const fn is_transparent(self) -> bool { pub const fn is_transparent(self) -> bool {
matches!(self.to_type(), #(BlockType::#is_transparent_types)|*) matches!(self.to_kind(), #(BlockKind::#is_transparent_types)|*)
} }
// TODO: is_solid // TODO: is_solid
/// If this block is water or lava. /// If this block is water or lava.
pub const fn is_liquid(self) -> bool { pub const fn is_liquid(self) -> bool {
matches!(self.to_type(), BlockType::Water | BlockType::Lava) matches!(self.to_kind(), BlockKind::Water | BlockKind::Lava)
} }
/// Returns the amount of light that is normally filtered by this block. /// Returns the amount of light that is normally filtered by this block.
/// The returned value is in `0..=15`. /// The returned value is in `0..=15`.
pub const fn filter_light(self) -> u8 { pub const fn filter_light(self) -> u8 {
match self.to_type() { match self.to_kind() {
#filter_light_arms #filter_light_arms
} }
} }
@ -402,17 +402,17 @@ pub fn build() -> anyhow::Result<()> {
/// An enumeration of all block types. /// An enumeration of all block types.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum BlockType { pub enum BlockKind {
#(#block_type_variants,)* #(#block_kind_variants,)*
} }
impl BlockType { impl BlockKind {
/// Construct a block type from its snake_case name. /// Construct a block type from its snake_case name.
/// ///
/// Returns `None` if the given name is not valid. /// Returns `None` if the given name is not valid.
pub fn from_str(name: &str) -> Option<BlockType> { pub fn from_str(name: &str) -> Option<BlockKind> {
match name { match name {
#block_type_from_str_arms #block_kind_from_str_arms
_ => None _ => None
} }
} }
@ -420,29 +420,29 @@ pub fn build() -> anyhow::Result<()> {
/// Get the snake_case name of this block type. /// Get the snake_case name of this block type.
pub const fn to_str(self) -> &'static str { pub const fn to_str(self) -> &'static str {
match self { match self {
#block_type_to_str_arms #block_kind_to_str_arms
} }
} }
/// Returns the default block state for a given block type. /// Returns the default block state for a given block type.
pub const fn to_state(self) -> BlockState { pub const fn to_state(self) -> BlockState {
BlockState::from_type(self) BlockState::from_kind(self)
} }
/// Returns a slice of all properties this block type has. /// Returns a slice of all properties this block type has.
pub const fn props(self) -> &'static [PropName] { pub const fn props(self) -> &'static [PropName] {
match self { match self {
#block_type_props_arms #block_kind_props_arms
_ => &[], _ => &[],
} }
} }
/// An array of all block types. /// An array of all block types.
pub const ALL: [Self; #block_type_count] = [#(Self::#block_type_variants,)*]; pub const ALL: [Self; #block_kind_count] = [#(Self::#block_kind_variants,)*];
} }
/// The default block type is `air`. /// The default block type is `air`.
impl Default for BlockType { impl Default for BlockKind {
fn default() -> Self { fn default() -> Self {
Self::Air Self::Air
} }
@ -626,7 +626,7 @@ fn parse_blocks_json() -> anyhow::Result<Vec<Block>> {
vals: match &s { vals: match &s {
State::Enum { values, .. } => values.clone(), State::Enum { values, .. } => values.clone(),
State::Int { values, .. } => values.clone(), State::Int { values, .. } => values.clone(),
State::Bool { .. } => vec!["true".to_string(), "false".to_string()], State::Bool { .. } => vec!["true".to_owned(), "false".to_owned()],
}, },
}) })
.collect(), .collect(),

View file

@ -158,12 +158,12 @@ enum Type {
/// Also known as OptVarInt /// Also known as OptVarInt
OptEntityId, OptEntityId,
Pose, Pose,
CatVariant, CatKind,
FrogVariant, FrogKind,
OptGlobalPosition, OptGlobalPosition,
PaintingVariant, PaintingKind,
// ==== Specialized ==== // // ==== Specialized ==== //
BoatVariant, BoatKind,
MainHand, MainHand,
} }
@ -204,11 +204,11 @@ impl Type {
Type::VillagerData => quote! { VillagerData::default() }, Type::VillagerData => quote! { VillagerData::default() },
Type::OptEntityId => quote! { None }, Type::OptEntityId => quote! { None },
Type::Pose => quote! { Pose::default() }, Type::Pose => quote! { Pose::default() },
Type::CatVariant => quote! { CatVariant::default() }, Type::CatKind => quote! { CatKind::default() },
Type::FrogVariant => quote! { FrogVariant::default() }, Type::FrogKind => quote! { FrogKind::default() },
Type::OptGlobalPosition => quote! { () }, // TODO Type::OptGlobalPosition => quote! { () }, // TODO
Type::PaintingVariant => quote! { PaintingVariant::default() }, Type::PaintingKind => quote! { PaintingKind::default() },
Type::BoatVariant => quote! { BoatVariant::default() }, Type::BoatKind => quote! { BoatKind::default() },
Type::MainHand => quote! { MainHand::default() }, Type::MainHand => quote! { MainHand::default() },
} }
} }
@ -235,11 +235,11 @@ impl Type {
Type::VillagerData => 16, Type::VillagerData => 16,
Type::OptEntityId => 17, Type::OptEntityId => 17,
Type::Pose => 18, Type::Pose => 18,
Type::CatVariant => 19, Type::CatKind => 19,
Type::FrogVariant => 20, Type::FrogKind => 20,
Type::OptGlobalPosition => 21, Type::OptGlobalPosition => 21,
Type::PaintingVariant => 22, Type::PaintingKind => 22,
Type::BoatVariant => 1, Type::BoatKind => 1,
Type::MainHand => 0, Type::MainHand => 0,
} }
} }
@ -387,8 +387,8 @@ const BOAT: Class = Class {
typ: Type::Float(0.0), typ: Type::Float(0.0),
}, },
Field { Field {
name: "typ", name: "kind",
typ: Type::BoatVariant, typ: Type::BoatKind,
}, },
Field { Field {
name: "left_paddle_turning", name: "left_paddle_turning",
@ -1040,7 +1040,7 @@ const ENTITIES: &[Class] = &[
inherit: Some(&BASE_ENTITY), inherit: Some(&BASE_ENTITY),
fields: &[Field { fields: &[Field {
name: "variant", name: "variant",
typ: Type::PaintingVariant, typ: Type::PaintingKind,
}], }],
events: &[], events: &[],
}, },
@ -1427,7 +1427,7 @@ const ENTITIES: &[Class] = &[
fields: &[ fields: &[
Field { Field {
name: "variant", name: "variant",
typ: Type::FrogVariant, typ: Type::FrogKind,
}, },
Field { Field {
name: "tongue_target", name: "tongue_target",
@ -1639,7 +1639,7 @@ const ENTITIES: &[Class] = &[
fields: &[ fields: &[
Field { Field {
name: "variant", name: "variant",
typ: Type::CatVariant, typ: Type::CatKind,
}, },
Field { Field {
name: "lying", name: "lying",
@ -2168,7 +2168,7 @@ pub fn build() -> anyhow::Result<()> {
} }
} }
let entity_type_variants = entities let entity_kind_variants = entities
.iter() .iter()
.map(|c| ident(c.name.to_pascal_case())) .map(|c| ident(c.name.to_pascal_case()))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -2201,11 +2201,11 @@ pub fn build() -> anyhow::Result<()> {
Type::VillagerData => quote! { VillagerData }, Type::VillagerData => quote! { VillagerData },
Type::OptEntityId => quote! { Option<EntityId> }, Type::OptEntityId => quote! { Option<EntityId> },
Type::Pose => quote! { Pose }, Type::Pose => quote! { Pose },
Type::CatVariant => quote! { CatVariant }, Type::CatKind => quote! { CatKind },
Type::FrogVariant => quote! { FrogVariant }, Type::FrogKind => quote! { FrogKind },
Type::OptGlobalPosition => quote! { () }, // TODO Type::OptGlobalPosition => quote! { () }, // TODO
Type::PaintingVariant => quote! { PaintingVariant }, Type::PaintingKind => quote! { PaintingKind },
Type::BoatVariant => quote! { BoatVariant }, Type::BoatKind => quote! { BoatKind },
Type::MainHand => quote! { MainHand }, Type::MainHand => quote! { MainHand },
}; };
quote! { quote! {
@ -2358,11 +2358,11 @@ pub fn build() -> anyhow::Result<()> {
Type::VillagerData => standard_getter_setter(quote!(VillagerData)), Type::VillagerData => standard_getter_setter(quote!(VillagerData)),
Type::OptEntityId => standard_getter_setter(quote!(Option<EntityId>)), Type::OptEntityId => standard_getter_setter(quote!(Option<EntityId>)),
Type::Pose => standard_getter_setter(quote!(Pose)), Type::Pose => standard_getter_setter(quote!(Pose)),
Type::CatVariant => standard_getter_setter(quote!(CatVariant)), Type::CatKind => standard_getter_setter(quote!(CatKind)),
Type::FrogVariant => standard_getter_setter(quote!(FrogVariant)), Type::FrogKind => standard_getter_setter(quote!(FrogKind)),
Type::OptGlobalPosition => quote! {}, // TODO Type::OptGlobalPosition => quote! {}, // TODO
Type::PaintingVariant => standard_getter_setter(quote!(PaintingVariant)), Type::PaintingKind => standard_getter_setter(quote!(PaintingKind)),
Type::BoatVariant => standard_getter_setter(quote!(BoatVariant)), Type::BoatKind => standard_getter_setter(quote!(BoatKind)),
Type::MainHand => standard_getter_setter(quote!(MainHand)), Type::MainHand => standard_getter_setter(quote!(MainHand)),
} }
}) })
@ -2457,11 +2457,11 @@ pub fn build() -> anyhow::Result<()> {
let finished = quote! { let finished = quote! {
/// Identifies a type of entity, such as `chicken`, `zombie` or `item`. /// Identifies a type of entity, such as `chicken`, `zombie` or `item`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum EntityType { pub enum EntityKind {
#(#entity_type_variants,)* #(#entity_kind_variants,)*
} }
impl Default for EntityType { impl Default for EntityKind {
fn default() -> Self { fn default() -> Self {
Self::Marker Self::Marker
} }
@ -2471,19 +2471,19 @@ pub fn build() -> anyhow::Result<()> {
/// An enum encoding the type of an entity along with any data specific to that entity type. /// An enum encoding the type of an entity along with any data specific to that entity type.
pub enum EntityData { pub enum EntityData {
#(#entity_type_variants(#entity_type_variants),)* #(#entity_kind_variants(#entity_kind_variants),)*
} }
impl EntityData { impl EntityData {
pub(super) fn new(typ: EntityType) -> Self { pub(super) fn new(kind: EntityKind) -> Self {
match typ { match kind {
#(EntityType::#entity_type_variants => Self::#entity_type_variants(#entity_type_variants::new()),)* #(EntityKind::#entity_kind_variants => Self::#entity_kind_variants(#entity_kind_variants::new()),)*
} }
} }
pub(super) fn typ(&self) -> EntityType { pub(super) fn kind(&self) -> EntityKind {
match self { match self {
#(Self::#entity_type_variants(_) => EntityType::#entity_type_variants,)* #(Self::#entity_kind_variants(_) => EntityKind::#entity_kind_variants,)*
} }
} }
@ -2491,7 +2491,7 @@ pub fn build() -> anyhow::Result<()> {
let mut data = Vec::new(); let mut data = Vec::new();
match self { match self {
#(Self::#entity_type_variants(e) => e.initial_metadata(&mut data),)* #(Self::#entity_kind_variants(e) => e.initial_metadata(&mut data),)*
} }
if data.is_empty() { if data.is_empty() {
@ -2506,7 +2506,7 @@ pub fn build() -> anyhow::Result<()> {
let mut data = Vec::new(); let mut data = Vec::new();
match self { match self {
#(Self::#entity_type_variants(e) => e.updated_metadata(&mut data),)* #(Self::#entity_kind_variants(e) => e.updated_metadata(&mut data),)*
} }
if data.is_empty() { if data.is_empty() {
@ -2519,13 +2519,13 @@ pub fn build() -> anyhow::Result<()> {
pub(crate) fn event_codes(&self) -> &[u8] { pub(crate) fn event_codes(&self) -> &[u8] {
match self { match self {
#(Self::#entity_type_variants(e) => e.event_codes(),)* #(Self::#entity_kind_variants(e) => e.event_codes(),)*
} }
} }
pub(super) fn clear_modifications(&mut self) { pub(super) fn clear_modifications(&mut self) {
match self { match self {
#(Self::#entity_type_variants(e) => e.clear_modifications(),)* #(Self::#entity_kind_variants(e) => e.clear_modifications(),)*
} }
} }
} }

View file

@ -13,7 +13,7 @@ use valence::entity::meta::Pose;
use valence::entity::EntityData; use valence::entity::EntityData;
use valence::text::Color; use valence::text::Color;
use valence::{ use valence::{
async_trait, ident, Biome, BlockState, Dimension, DimensionId, EntityId, EntityType, Server, async_trait, ident, Biome, BlockState, Dimension, DimensionId, EntityId, EntityKind, Server,
SharedServer, ShutdownResult, TextFormat, SharedServer, ShutdownResult, TextFormat,
}; };
@ -135,7 +135,7 @@ impl Config for Game {
world.meta.player_list_mut().insert( world.meta.player_list_mut().insert(
client.uuid(), client.uuid(),
client.username().to_string(), client.username().to_owned(),
client.textures().cloned(), client.textures().cloned(),
client.game_mode(), client.game_mode(),
0, 0,
@ -146,7 +146,7 @@ impl Config for Game {
client_id, client_id,
server server
.entities .entities
.create_with_uuid(EntityType::Player, client.uuid()) .create_with_uuid(EntityKind::Player, client.uuid())
.unwrap() .unwrap()
.0, .0,
); );

View file

@ -9,7 +9,7 @@ use valence::config::{Config, ServerListPing};
use valence::text::Color; use valence::text::Color;
use valence::util::to_yaw_and_pitch; use valence::util::to_yaw_and_pitch;
use valence::{ use valence::{
async_trait, DimensionId, EntityId, EntityType, Server, SharedServer, ShutdownResult, async_trait, DimensionId, EntityId, EntityKind, Server, SharedServer, ShutdownResult,
TextFormat, TextFormat,
}; };
use vek::{Mat3, Vec3}; use vek::{Mat3, Vec3};
@ -70,7 +70,7 @@ impl Config for Game {
} }
self.cows.lock().unwrap().extend((0..200).map(|_| { self.cows.lock().unwrap().extend((0..200).map(|_| {
let (id, e) = server.entities.create(EntityType::Cow); let (id, e) = server.entities.create(EntityKind::Cow);
e.set_world(world_id); e.set_world(world_id);
id id
})); }));
@ -98,7 +98,7 @@ impl Config for Game {
world.meta.player_list_mut().insert( world.meta.player_list_mut().insert(
client.uuid(), client.uuid(),
client.username().to_string(), client.username().to_owned(),
client.textures().cloned(), client.textures().cloned(),
client.game_mode(), client.game_mode(),
0, 0,

View file

@ -99,7 +99,7 @@ impl Config for Game {
world.meta.player_list_mut().insert( world.meta.player_list_mut().insert(
client.uuid(), client.uuid(),
client.username().to_string(), client.username().to_owned(),
client.textures().cloned(), client.textures().cloned(),
client.game_mode(), client.game_mode(),
0, 0,

View file

@ -105,5 +105,5 @@ pub struct BiomeMoodSound {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct BiomeParticle { pub struct BiomeParticle {
pub probability: f32, pub probability: f32,
pub typ: Ident, pub kind: Ident,
} }

View file

@ -11,15 +11,15 @@ include!(concat!(env!("OUT_DIR"), "/block.rs"));
impl fmt::Debug for BlockState { impl fmt::Debug for BlockState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let typ = self.to_type(); let kind = self.to_kind();
write!(f, "{}", typ.to_str())?; write!(f, "{}", kind.to_str())?;
let props = typ.props(); let props = kind.props();
if !props.is_empty() { if !props.is_empty() {
let mut list = f.debug_list(); let mut list = f.debug_list();
for &p in typ.props() { for &p in kind.props() {
struct KeyVal<'a>(&'a str, &'a str); struct KeyVal<'a>(&'a str, &'a str);
impl<'a> fmt::Debug for KeyVal<'a> { impl<'a> fmt::Debug for KeyVal<'a> {
@ -58,10 +58,10 @@ mod tests {
#[test] #[test]
fn get_set_consistency() { fn get_set_consistency() {
for typ in BlockType::ALL { for kind in BlockKind::ALL {
let block = typ.to_state(); let block = kind.to_state();
for &prop in typ.props() { for &prop in kind.props() {
let new_block = block.set(prop, block.get(prop).unwrap()); let new_block = block.set(prop, block.get(prop).unwrap());
assert_eq!(new_block, block); assert_eq!(new_block, block);
} }

View file

@ -14,10 +14,10 @@ use vek::Vec3;
use crate::biome::{Biome, BiomeGrassColorModifier, BiomePrecipitation}; use crate::biome::{Biome, BiomeGrassColorModifier, BiomePrecipitation};
use crate::dimension::{Dimension, DimensionEffects}; use crate::dimension::{Dimension, DimensionEffects};
use crate::entity::data::Player; use crate::entity::data::Player;
use crate::entity::{velocity_to_packet_units, EntityType}; use crate::entity::{velocity_to_packet_units, EntityKind};
use crate::player_textures::SignedPlayerTextures; use crate::player_textures::SignedPlayerTextures;
use crate::protocol::packets::play::c2s::{ use crate::protocol::packets::play::c2s::{
C2sPlayPacket, DiggingStatus, InteractType, PlayerCommandId, C2sPlayPacket, DiggingStatus, InteractKind, PlayerCommandId,
}; };
use crate::protocol::packets::play::s2c::{ use crate::protocol::packets::play::s2c::{
Animate, Biome as BiomeRegistryBiome, BiomeAdditionsSound, BiomeEffects, BiomeMoodSound, Animate, Biome as BiomeRegistryBiome, BiomeAdditionsSound, BiomeEffects, BiomeMoodSound,
@ -470,10 +470,10 @@ impl Client {
self.events.push_back(ClientEvent::InteractWithEntity { self.events.push_back(ClientEvent::InteractWithEntity {
id, id,
sneaking: p.sneaking, sneaking: p.sneaking,
typ: match p.typ { kind: match p.kind {
InteractType::Interact(hand) => InteractWithEntity::Interact(hand), InteractKind::Interact(hand) => InteractWithEntity::Interact(hand),
InteractType::Attack => InteractWithEntity::Attack, InteractKind::Attack => InteractWithEntity::Attack,
InteractType::InteractAt((target, hand)) => { InteractKind::InteractAt((target, hand)) => {
InteractWithEntity::InteractAt { target, hand } InteractWithEntity::InteractAt { target, hand }
} }
}, },
@ -871,7 +871,7 @@ impl Client {
&mut self.send, &mut self.send,
SystemChat { SystemChat {
chat: msg, chat: msg,
typ: VarInt(0), kind: VarInt(0),
}, },
); );
} }
@ -882,7 +882,7 @@ impl Client {
// longer visible. // longer visible.
self.loaded_entities.retain(|&id| { self.loaded_entities.retain(|&id| {
if let Some(entity) = entities.get(id) { if let Some(entity) = entities.get(id) {
debug_assert!(entity.typ() != EntityType::Marker); debug_assert!(entity.kind() != EntityKind::Marker);
if self.new_position.distance(entity.position()) <= view_dist as f64 * 16.0 { if self.new_position.distance(entity.position()) <= view_dist as f64 * 16.0 {
if let Some(meta) = entity.updated_metadata_packet(id) { if let Some(meta) = entity.updated_metadata_packet(id) {
send_packet(&mut self.send, meta); send_packet(&mut self.send, meta);
@ -1002,7 +1002,7 @@ impl Client {
let entity = entities let entity = entities
.get(id) .get(id)
.expect("entities in spatial index should be valid"); .expect("entities in spatial index should be valid");
if entity.typ() != EntityType::Marker if entity.kind() != EntityKind::Marker
&& entity.uuid() != self.uuid && entity.uuid() != self.uuid
&& self.loaded_entities.insert(id) && self.loaded_entities.insert(id)
{ {
@ -1108,22 +1108,22 @@ fn make_dimension_codec(shared: &SharedServer) -> RegistryCodec {
RegistryCodec { RegistryCodec {
dimension_type_registry: DimensionTypeRegistry { dimension_type_registry: DimensionTypeRegistry {
typ: ident!("dimension_type"), kind: ident!("dimension_type"),
value: dims, value: dims,
}, },
biome_registry: BiomeRegistry { biome_registry: BiomeRegistry {
typ: ident!("worldgen/biome"), kind: ident!("worldgen/biome"),
value: biomes, value: biomes,
}, },
chat_type_registry: ChatTypeRegistry { chat_type_registry: ChatTypeRegistry {
typ: ident!("chat_type"), kind: ident!("chat_type"),
value: vec![ChatTypeRegistryEntry { value: vec![ChatTypeRegistryEntry {
name: ident!("system"), name: ident!("system"),
id: 0, id: 0,
element: ChatType { element: ChatType {
chat: ChatTypeChat {}, chat: ChatTypeChat {},
narration: ChatTypeNarration { narration: ChatTypeNarration {
priority: "system".to_string(), priority: "system".to_owned(),
}, },
}, },
}], }],
@ -1207,7 +1207,7 @@ fn to_biome_registry_item(biome: &Biome, id: i32) -> BiomeRegistryBiome {
}, },
particle: biome.particle.as_ref().map(|p| BiomeParticle { particle: biome.particle.as_ref().map(|p| BiomeParticle {
probability: p.probability, probability: p.probability,
options: BiomeParticleOptions { typ: p.typ.clone() }, options: BiomeParticleOptions { kind: p.kind.clone() },
}), }),
}, },
} }

View file

@ -40,7 +40,7 @@ pub enum ClientEvent {
/// If the client was sneaking during the interaction. /// If the client was sneaking during the interaction.
sneaking: bool, sneaking: bool,
/// The type of interaction that occurred. /// The type of interaction that occurred.
typ: InteractWithEntity, kind: InteractWithEntity,
}, },
SteerBoat { SteerBoat {
left_paddle_turning: bool, left_paddle_turning: bool,

View file

@ -7,7 +7,7 @@ use std::iter::FusedIterator;
use std::num::NonZeroU32; use std::num::NonZeroU32;
use bitfield_struct::bitfield; use bitfield_struct::bitfield;
pub use data::{EntityData, EntityType}; pub use data::{EntityData, EntityKind};
use rayon::iter::ParallelIterator; use rayon::iter::ParallelIterator;
use uuid::Uuid; use uuid::Uuid;
use vek::{Aabb, Vec3}; use vek::{Aabb, Vec3};
@ -37,8 +37,8 @@ impl Entities {
/// Spawns a new entity with the default data. The new entity's [`EntityId`] /// Spawns a new entity with the default data. The new entity's [`EntityId`]
/// is returned. /// is returned.
pub fn create(&mut self, typ: EntityType) -> (EntityId, &mut Entity) { pub fn create(&mut self, kind: EntityKind) -> (EntityId, &mut Entity) {
self.create_with_uuid(typ, Uuid::from_bytes(rand::random())) self.create_with_uuid(kind, Uuid::from_bytes(rand::random()))
.expect("UUID collision") .expect("UUID collision")
} }
@ -49,7 +49,7 @@ impl Entities {
/// world. If it does, `None` is returned and the entity is not spawned. /// world. If it does, `None` is returned and the entity is not spawned.
pub fn create_with_uuid( pub fn create_with_uuid(
&mut self, &mut self,
typ: EntityType, kind: EntityKind,
uuid: Uuid, uuid: Uuid,
) -> Option<(EntityId, &mut Entity)> { ) -> Option<(EntityId, &mut Entity)> {
match self.uuid_to_entity.entry(uuid) { match self.uuid_to_entity.entry(uuid) {
@ -57,7 +57,7 @@ impl Entities {
Entry::Vacant(ve) => { Entry::Vacant(ve) => {
let (k, e) = self.sm.insert(Entity { let (k, e) = self.sm.insert(Entity {
flags: EntityFlags(0), flags: EntityFlags(0),
data: EntityData::new(typ), data: EntityData::new(kind),
world: None, world: None,
new_position: Vec3::default(), new_position: Vec3::default(),
old_position: Vec3::default(), old_position: Vec3::default(),
@ -219,9 +219,9 @@ impl Entity {
&mut self.data &mut self.data
} }
/// Returns the [`EntityType`] of this entity. /// Returns the [`EntityKind`] of this entity.
pub fn typ(&self) -> EntityType { pub fn kind(&self) -> EntityKind {
self.data.typ() self.data.kind()
} }
pub fn world(&self) -> Option<WorldId> { pub fn world(&self) -> Option<WorldId> {
@ -497,7 +497,7 @@ impl Entity {
_ => Some(EntitySpawnPacket::SpawnEntity(AddEntity { _ => Some(EntitySpawnPacket::SpawnEntity(AddEntity {
entity_id: VarInt(this_id.to_network_id()), entity_id: VarInt(this_id.to_network_id()),
object_uuid: self.uuid, object_uuid: self.uuid,
typ: VarInt(self.typ() as i32), kind: VarInt(self.kind() as i32),
position: self.new_position, position: self.new_position,
pitch: ByteAngle::from_degrees(self.pitch), pitch: ByteAngle::from_degrees(self.pitch),
yaw: ByteAngle::from_degrees(self.yaw), yaw: ByteAngle::from_degrees(self.yaw),

View file

@ -46,15 +46,15 @@ impl Encode for Direction {
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct VillagerData { pub struct VillagerData {
pub typ: VillagerType, pub kind: VillagerKind,
pub profession: VillagerProfession, pub profession: VillagerProfession,
pub level: i32, pub level: i32,
} }
impl VillagerData { impl VillagerData {
pub const fn new(typ: VillagerType, profession: VillagerProfession, level: i32) -> Self { pub const fn new(kind: VillagerKind, profession: VillagerProfession, level: i32) -> Self {
Self { Self {
typ, kind,
profession, profession,
level, level,
} }
@ -64,7 +64,7 @@ impl VillagerData {
impl Default for VillagerData { impl Default for VillagerData {
fn default() -> Self { fn default() -> Self {
Self { Self {
typ: Default::default(), kind: Default::default(),
profession: Default::default(), profession: Default::default(),
level: 1, level: 1,
} }
@ -73,14 +73,14 @@ impl Default for VillagerData {
impl Encode for VillagerData { impl Encode for VillagerData {
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> { fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
VarInt(self.typ as i32).encode(w)?; VarInt(self.kind as i32).encode(w)?;
VarInt(self.profession as i32).encode(w)?; VarInt(self.profession as i32).encode(w)?;
VarInt(self.level).encode(w) VarInt(self.level).encode(w)
} }
} }
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub enum VillagerType { pub enum VillagerKind {
Desert, Desert,
Jungle, Jungle,
#[default] #[default]
@ -151,7 +151,7 @@ impl Encode for MainHand {
} }
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub enum BoatVariant { pub enum BoatKind {
#[default] #[default]
Oak, Oak,
Spruce, Spruce,
@ -161,14 +161,14 @@ pub enum BoatVariant {
DarkOak, DarkOak,
} }
impl Encode for BoatVariant { impl Encode for BoatKind {
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> { fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
VarInt(*self as i32).encode(w) VarInt(*self as i32).encode(w)
} }
} }
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub enum CatVariant { pub enum CatKind {
Tabby, Tabby,
#[default] #[default]
Black, Black,
@ -183,33 +183,33 @@ pub enum CatVariant {
AllBlack, AllBlack,
} }
impl Encode for CatVariant { impl Encode for CatKind {
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> { fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
VarInt(*self as i32).encode(w) VarInt(*self as i32).encode(w)
} }
} }
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub enum FrogVariant { pub enum FrogKind {
#[default] #[default]
Temperate, Temperate,
Warm, Warm,
Cold, Cold,
} }
impl Encode for FrogVariant { impl Encode for FrogKind {
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> { fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
VarInt(*self as i32).encode(w) VarInt(*self as i32).encode(w)
} }
} }
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub enum PaintingVariant { pub enum PaintingKind {
#[default] #[default]
Default, // TODO Default, // TODO
} }
impl Encode for PaintingVariant { impl Encode for PaintingKind {
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> { fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
VarInt(*self as i32).encode(w) VarInt(*self as i32).encode(w)
} }

View file

@ -135,7 +135,7 @@ impl FromStr for Ident {
type Err = ParseError; type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
Ident::new(s.to_string()) Ident::new(s.to_owned())
} }
} }

View file

@ -41,7 +41,7 @@ pub use chunk_pos::ChunkPos;
pub use client::{Client, Clients}; pub use client::{Client, Clients};
pub use config::Config; pub use config::Config;
pub use dimension::{Dimension, DimensionId}; pub use dimension::{Dimension, DimensionId};
pub use entity::{Entities, Entity, EntityId, EntityType}; pub use entity::{Entities, Entity, EntityId, EntityKind};
pub use ident::Ident; pub use ident::Ident;
pub use server::{start_server, NewClientData, Server, SharedServer, ShutdownResult}; pub use server::{start_server, NewClientData, Server, SharedServer, ShutdownResult};
pub use spatial_index::SpatialIndex; pub use spatial_index::SpatialIndex;

View file

@ -588,7 +588,7 @@ pub mod play {
AddEntity 0x00 { AddEntity 0x00 {
entity_id: VarInt, entity_id: VarInt,
object_uuid: Uuid, object_uuid: Uuid,
typ: VarInt, kind: VarInt,
position: Vec3<f64>, position: Vec3<f64>,
pitch: ByteAngle, pitch: ByteAngle,
yaw: ByteAngle, yaw: ByteAngle,
@ -640,7 +640,7 @@ pub mod play {
def_struct! { def_struct! {
BlockEntityData 0x07 { BlockEntityData 0x07 {
location: BlockPos, location: BlockPos,
typ: VarInt, // TODO: use enum here kind: VarInt, // TODO: use enum here
data: nbt::Blob, data: nbt::Blob,
} }
} }
@ -816,7 +816,7 @@ pub mod play {
LevelChunkBlockEntity { LevelChunkBlockEntity {
packed_xz: i8, packed_xz: i8,
y: i16, y: i16,
typ: VarInt, kind: VarInt,
data: nbt::Blob, data: nbt::Blob,
} }
} }
@ -865,7 +865,7 @@ pub mod play {
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DimensionTypeRegistry { pub struct DimensionTypeRegistry {
#[serde(rename = "type")] #[serde(rename = "type")]
pub typ: Ident, pub kind: Ident,
pub value: Vec<DimensionTypeRegistryEntry>, pub value: Vec<DimensionTypeRegistryEntry>,
} }
@ -901,7 +901,7 @@ pub mod play {
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BiomeRegistry { pub struct BiomeRegistry {
#[serde(rename = "type")] #[serde(rename = "type")]
pub typ: Ident, pub kind: Ident,
pub value: Vec<Biome>, pub value: Vec<Biome>,
} }
@ -971,13 +971,13 @@ pub mod play {
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BiomeParticleOptions { pub struct BiomeParticleOptions {
#[serde(rename = "type")] #[serde(rename = "type")]
pub typ: Ident, pub kind: Ident,
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ChatTypeRegistry { pub struct ChatTypeRegistry {
#[serde(rename = "type")] #[serde(rename = "type")]
pub typ: Ident, pub kind: Ident,
pub value: Vec<ChatTypeRegistryEntry>, pub value: Vec<ChatTypeRegistryEntry>,
} }
@ -1044,7 +1044,7 @@ pub mod play {
PlayerChat 0x30 { PlayerChat 0x30 {
message: Text, message: Text,
/// Index into the chat type registry /// Index into the chat type registry
typ: VarInt, kind: VarInt,
sender: Uuid, sender: Uuid,
// TODO more fields // TODO more fields
} }
@ -1183,7 +1183,7 @@ pub mod play {
SystemChat 0x5f { SystemChat 0x5f {
chat: Text, chat: Text,
/// Index into the chat type registry. /// Index into the chat type registry.
typ: VarInt, kind: VarInt,
} }
} }
@ -1398,13 +1398,13 @@ pub mod play {
def_struct! { def_struct! {
Interact 0x0f { Interact 0x0f {
entity_id: VarInt, entity_id: VarInt,
typ: InteractType, kind: InteractKind,
sneaking: bool, sneaking: bool,
} }
} }
def_enum! { def_enum! {
InteractType: VarInt { InteractKind: VarInt {
Interact: Hand = 0, Interact: Hand = 0,
Attack = 1, Attack = 1,
InteractAt: (Vec3<f32>, Hand) = 2 InteractAt: (Vec3<f32>, Hand) = 2

View file

@ -532,11 +532,11 @@ async fn handle_status(
}); });
if let Some(data) = favicon_png { if let Some(data) = favicon_png {
let mut buf = "data:image/png;base64,".to_string(); let mut buf = "data:image/png;base64,".to_owned();
base64::encode_config_buf(data, base64::STANDARD, &mut buf); base64::encode_config_buf(data, base64::STANDARD, &mut buf);
json.as_object_mut() json.as_object_mut()
.unwrap() .unwrap()
.insert("favicon".to_string(), Value::String(buf)); .insert("favicon".to_owned(), Value::String(buf));
} }
c.enc c.enc

View file

@ -320,7 +320,7 @@ enum HoverEvent {
ShowEntity { ShowEntity {
name: Box<Text>, name: Box<Text>,
#[serde(rename = "type")] #[serde(rename = "type")]
typ: Ident, kind: Ident,
// TODO: id (hyphenated entity UUID as a string) // TODO: id (hyphenated entity UUID as a string)
}, },
} }