1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 14:26:04 +00:00

random fixes

This commit is contained in:
mat 2022-12-24 17:43:33 -06:00
parent eff339661f
commit ba5b7b5cab
12 changed files with 3002 additions and 1978 deletions

1
Cargo.lock generated
View file

@ -367,6 +367,7 @@ dependencies = [
"azalea-protocol-macros",
"azalea-registry",
"azalea-world",
"bevy_ecs",
"byteorder",
"bytes",
"flate2",

View file

@ -1,5 +1,5 @@
use crate::ResourceLocation;
use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use azalea_buf::{BufReadError, McBuf, McBufReadable, McBufWritable};
use std::{
io::{Cursor, Write},
ops::{Add, AddAssign, Mul, Rem, Sub},
@ -109,7 +109,7 @@ macro_rules! vec3_impl {
};
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, McBuf)]
pub struct Vec3 {
pub x: f64,
pub y: f64,

View file

@ -4,11 +4,8 @@ pub mod collision;
use azalea_block::{Block, BlockState};
use azalea_core::{BlockPos, Vec3};
use azalea_world::{
entity::{Entity, EntityData},
WeakWorld,
};
use collision::{MovableEntity, MoverType};
use azalea_world::WeakWorld;
use collision::MoverType;
use std::ops::Deref;
pub trait HasPhysics {
@ -210,11 +207,11 @@ fn block_jump_factor<D: Deref<Target = WeakWorld>>(entity: &Entity<D>) -> f32 {
// public double getJumpBoostPower() {
// return this.hasEffect(MobEffects.JUMP) ? (double)(0.1F *
// (float)(this.getEffect(MobEffects.JUMP).getAmplifier() + 1)) : 0.0D; }
fn jump_power<D: Deref<Target = WeakWorld>>(entity: &Entity<D>) -> f32 {
fn jump_power<D: Deref<Target = WeakWorld>>() -> f32 {
0.42 * block_jump_factor(entity)
}
fn jump_boost_power<D: Deref<Target = WeakWorld>>(_entity: &Entity<D>) -> f64 {
fn jump_boost_power<D: Deref<Target = WeakWorld>>() -> f64 {
// TODO: potion effects
// if let Some(effects) = entity.effects() {
// if let Some(jump_effect) = effects.get(&Effect::Jump) {

View file

@ -22,6 +22,7 @@ azalea-nbt = {path = "../azalea-nbt", version = "^0.5.0" }
azalea-protocol-macros = {path = "./azalea-protocol-macros", version = "^0.5.0" }
azalea-registry = {path = "../azalea-registry", version = "^0.5.0" }
azalea-world = {path = "../azalea-world", version = "^0.5.0" }
bevy_ecs = { version = "0.9.1", default-features = false }
byteorder = "^1.4.3"
bytes = "^1.1.0"
flate2 = "1.0.23"

View file

@ -1,7 +1,10 @@
use azalea_buf::McBuf;
use azalea_core::Vec3;
use azalea_protocol_macros::ClientboundGamePacket;
use azalea_world::entity::{EntityData, EntityMetadata};
use azalea_world::entity::{
metadata::{apply_default_metadata, PlayerMetadataBundle, UpdateMetadataError},
EntityBundle,
};
use uuid::Uuid;
#[derive(Clone, Debug, McBuf, ClientboundGamePacket)]
@ -11,9 +14,7 @@ pub struct ClientboundAddEntityPacket {
pub id: u32,
pub uuid: Uuid,
pub entity_type: azalea_registry::EntityKind,
pub x: f64,
pub y: f64,
pub z: f64,
pub position: Vec3,
pub x_rot: i8,
pub y_rot: i8,
pub y_head_rot: i8,
@ -24,17 +25,28 @@ pub struct ClientboundAddEntityPacket {
pub z_vel: i16,
}
impl From<&ClientboundAddEntityPacket> for EntityData {
fn from(p: &ClientboundAddEntityPacket) -> Self {
Self::new(
p.uuid,
Vec3 {
x: p.x,
y: p.y,
z: p.z,
},
// default metadata for the entity type
EntityMetadata::from(p.entity_type),
)
// impl From<&ClientboundAddEntityPacket> for EntityData {
// fn from(p: &ClientboundAddEntityPacket) -> Self {
// Self::new(
// p.uuid,
// Vec3 {
// x: p.x,
// y: p.y,
// z: p.z,
// },
// // default metadata for the entity type
// EntityMetadata::from(p.entity_type),
// )
// }
// }
impl ClientboundAddEntityPacket {
fn as_bundle(&self) -> EntityBundle {
EntityBundle::new(self.uuid, self.position, self.entity_type)
}
pub fn apply_to_entity(&self, entity: &mut bevy_ecs::world::EntityMut) {
apply_default_metadata(entity, self.entity_type);
entity.insert(self.as_bundle());
}
}

View file

@ -1,7 +1,8 @@
use azalea_buf::McBuf;
use azalea_core::Vec3;
use azalea_protocol_macros::ClientboundGamePacket;
use azalea_world::entity::{metadata, EntityData, EntityMetadata};
use azalea_registry::EntityKind;
use azalea_world::entity::{metadata::PlayerMetadataBundle, EntityBundle, PlayerBundle};
use uuid::Uuid;
/// This packet is sent by the server when a player comes into visible range,
@ -11,23 +12,16 @@ pub struct ClientboundAddPlayerPacket {
#[var]
pub id: u32,
pub uuid: Uuid,
pub x: f64,
pub y: f64,
pub z: f64,
pub position: Vec3,
pub x_rot: i8,
pub y_rot: i8,
}
impl From<&ClientboundAddPlayerPacket> for EntityData {
fn from(p: &ClientboundAddPlayerPacket) -> Self {
Self::new(
p.uuid,
Vec3 {
x: p.x,
y: p.y,
z: p.z,
},
EntityMetadata::Player(metadata::Player::default()),
)
impl ClientboundAddPlayerPacket {
fn as_bundle(p: &ClientboundAddPlayerPacket) -> PlayerBundle {
PlayerBundle {
entity: EntityBundle::new(p.uuid, p.position, EntityKind::Player),
metadata: PlayerMetadataBundle::default(),
}
}
}

View file

@ -3,12 +3,12 @@ description = "Use Minecraft's registries."
edition = "2021"
license = "MIT"
name = "azalea-registry"
version = "0.5.0"
repository = "https://github.com/mat-1/azalea/tree/main/azalea-registry"
version = "0.5.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
azalea-buf = {path = "../azalea-buf", version = "^0.5.0" }
azalea-registry-macros = {path = "./azalea-registry-macros", version = "^0.5.0" }
azalea-buf = {path = "../azalea-buf", version = "^0.5.0"}
azalea-registry-macros = {path = "./azalea-registry-macros", version = "^0.5.0"}
enum-as-inner = "0.5.1"

View file

@ -1205,7 +1205,7 @@ registry!(CommandArgumentKind, {
ItemStack => "minecraft:item_stack",
ItemPredicate => "minecraft:item_predicate",
Color => "minecraft:color",
FormattedText => "minecraft:component",
Component => "minecraft:component",
Message => "minecraft:message",
NbtCompoundTag => "minecraft:nbt_compound_tag",
NbtTag => "minecraft:nbt_tag",

File diff suppressed because it is too large Load diff

View file

@ -3,17 +3,21 @@ mod data;
mod dimensions;
pub mod metadata;
use self::metadata::UpdateMetadataError;
use self::{
attributes::{AttributeInstance, AttributeModifiers},
metadata::UpdateMetadataError,
};
use crate::WeakWorld;
use azalea_block::BlockState;
use azalea_core::{BlockPos, ChunkPos, Vec3, AABB};
use bevy_ecs::{
bundle::Bundle,
component::Component,
world::{EntityMut, Mut},
};
pub use data::*;
use derive_more::{Deref, DerefMut};
pub use dimensions::*;
pub use dimensions::EntityDimensions;
use std::{
fmt::{Debug, Display, Formatter},
ops::Deref,
@ -64,19 +68,18 @@ impl nohash_hasher::IsEnabled for EntityId {}
///
/// If you do have access to a [`PartialEntityStorage`] though then just call
/// [`PartialEntityStorage::insert`].
///
/// This doesn't return anything since you should be using the [`EntityId`] to
/// get the entity data.
pub(crate) fn new_entity<'w>(
ecs: &'w mut bevy_ecs::world::World,
id: EntityId,
bundle: impl bevy_ecs::bundle::Bundle,
) {
) -> EntityMut<'w> {
// bevy_ecs only returns None if the entity only exists with a different
// generation, which shouldn't be possible here
let mut entity = ecs
.get_or_spawn(id.into())
.expect("Entities should always be generation 0 if we're manually spawning from ids");
entity.insert(bundle);
entity
}
// impl<'d, D: Deref<Target = WeakWorld>> Entity<'d, D> {
@ -146,12 +149,12 @@ pub fn input_vector(physics: &mut Physics, speed: f32, acceleration: &Vec3) -> V
/// Apply the given metadata items to the entity. Everything that isn't
/// included in items will be left unchanged.
pub fn update_metadatas(
pub fn apply_metadata(
ecs: bevy_ecs::world::World,
entity: bevy_ecs::world::EntityMut,
entity: &mut bevy_ecs::world::EntityMut,
items: Vec<EntityDataItem>,
) -> Result<(), UpdateMetadataError> {
metadata::update_metadatas(entity, items)
metadata::apply_metadata(entity, items)
}
pub fn make_bounding_box(pos: &Position, physics: &Physics) -> AABB {
@ -260,85 +263,73 @@ pub struct Physics {
pub has_impulse: bool,
}
// impl EntityData {
// pub fn new(uuid: Uuid, pos: Vec3, metadata: EntityMetadata) -> Self {
// let dimensions = EntityDimensions {
// width: 0.6,
// height: 1.8,
// };
/// A component NewType for [`azalea_registry::EntityKind`].
#[derive(Component, Clone, Copy, Debug, PartialEq, Deref)]
pub struct EntityKind(azalea_registry::EntityKind);
// Self {
// uuid,
// pos,
// last_pos: pos,
// delta: Vec3::default(),
/// A bundle of components that every entity has. This doesn't contain metadata,
/// that has to be added separately.
#[derive(Bundle)]
pub struct EntityBundle {
pub kind: EntityKind,
pub uuid: EntityUuid,
pub position: Position,
pub physics: Physics,
pub attributes: AttributeModifiers,
}
// xxa: 0.,
// yya: 0.,
// zza: 0.,
impl EntityBundle {
pub fn new(uuid: Uuid, pos: Vec3, kind: azalea_registry::EntityKind) -> Self {
let dimensions = EntityDimensions {
width: 0.6,
height: 1.8,
};
// x_rot: 0.,
// y_rot: 0.,
Self {
kind: EntityKind(kind),
uuid: EntityUuid(uuid),
position: Position(pos),
physics: Physics {
last_pos: pos,
delta: Vec3::default(),
// y_rot_last: 0.,
// x_rot_last: 0.,
xxa: 0.,
yya: 0.,
zza: 0.,
// on_ground: false,
// last_on_ground: false,
x_rot: 0.,
y_rot: 0.,
// // TODO: have this be based on the entity type
// bounding_box: dimensions.make_bounding_box(&pos),
// dimensions,
y_rot_last: 0.,
x_rot_last: 0.,
// has_impulse: false,
on_ground: false,
last_on_ground: false,
// jumping: false,
// TODO: have this be based on the entity type
bounding_box: dimensions.make_bounding_box(&pos),
dimensions,
// metadata,
has_impulse: false,
// attributes: AttributeModifiers {
// // TODO: do the correct defaults for everything, some
// entities have different // defaults
// speed: AttributeInstance::new(0.1),
// },
// }
// }
jumping: false,
},
// /// Get the position of the entity in the world.
// #[inline]
// pub fn pos(&self) -> &Vec3 {
// &self.pos
// }
attributes: AttributeModifiers {
// TODO: do the correct defaults for everything, some
// entities have different defaults
speed: AttributeInstance::new(0.1),
},
}
}
}
// /// Convert this &self into a (mutable) pointer.
// ///
// /// # Safety
// /// The entity MUST exist for at least as long as this pointer exists.
// pub unsafe fn as_ptr(&self) -> NonNull<EntityData> {
// // this is cursed
// NonNull::new_unchecked(self as *const EntityData as *mut EntityData)
// }
// /// Returns the type of entity this is.
// ///
// /// ```rust
// /// let entity = EntityData::new(
// /// Uuid::nil(),
// /// Vec3::default(),
// /// EntityMetadata::Player(metadata::Player::default()),
// /// );
// /// assert_eq!(entity.kind(), EntityKind::Player);
// /// ```
// pub fn kind(&self) -> EntityKind {
// EntityKind::from(&self.metadata)
// }
// }
// impl<W: Deref<Target = WeakWorld>> Debug for Entity<'_, W> {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// f.debug_struct("Entity").field("id", &self.id).finish()
// }
// }
/// A bundle of the components that are always present for a player.
#[derive(Bundle)]
pub struct PlayerBundle {
pub entity: EntityBundle,
pub metadata: metadata::PlayerMetadataBundle,
}
#[cfg(test)]
mod tests {

View file

@ -182,12 +182,12 @@ impl From<EntityDataValue> for UpdateMetadataError {
to_camel_case(parent_id.lstrip("~"))) if parent_id else None
# impl Allay {
# pub fn update_metadata(
# pub fn apply_metadata(
# entity: &mut bevy_ecs::world::EntityMut,
# d: EntityDataItem,
# ) -> Result<(), UpdateMetadataError> {
# match d.index {
# 0..=15 => AbstractCreatureBundle::update_metadata(entity, d)?,
# 0..=15 => AbstractCreatureBundle::apply_metadata(entity, d)?,
# 16 => entity.insert(Dancing(d.value.into_boolean()?)),
# 17 => entity.insert(CanDuplicate(d.value.into_boolean()?)),
# }
@ -196,7 +196,7 @@ impl From<EntityDataValue> for UpdateMetadataError {
# }
code.append(f'impl {struct_name} {{')
code.append(
f' pub fn update_metadata(entity: &mut bevy_ecs::world::EntityMut, d: EntityDataItem) -> Result<(), UpdateMetadataError> {{')
f' pub fn apply_metadata(entity: &mut bevy_ecs::world::EntityMut, d: EntityDataItem) -> Result<(), UpdateMetadataError> {{')
code.append(f' match d.index {{')
parent_last_index = -1
@ -206,7 +206,7 @@ impl From<EntityDataValue> for UpdateMetadataError {
parent_last_index = index
if parent_last_index != -1:
code.append(
f' 0..={parent_last_index} => {parent_struct_name}::update_metadata(entity, d)?,')
f' 0..={parent_last_index} => {parent_struct_name}::apply_metadata(entity, d)?,')
for index, name_or_bitfield in enumerate(all_field_names_or_bitfields):
if index <= parent_last_index:
@ -255,13 +255,15 @@ impl From<EntityDataValue> for UpdateMetadataError {
# dancing: Dancing,
# can_duplicate: CanDuplicate,
# }
bundle_struct_name = f'{struct_name}Bundle'
bundle_struct_name = f'{struct_name}MetadataBundle'
code.append(f'')
code.append(f'#[derive(Bundle)]')
code.append(f'struct {bundle_struct_name} {{')
code.append(f'pub struct {bundle_struct_name} {{')
code.append(
f' _marker: {struct_name},')
if parent_struct_name:
code.append(
f' parent: {parent_struct_name}Bundle,')
f' parent: {parent_struct_name}MetadataBundle,')
for index, name_or_bitfield in get_entity_metadata_names(entity_id, burger_entity_data, mappings).items():
if isinstance(name_or_bitfield, str):
name_or_bitfield = maybe_rename_field(
@ -281,6 +283,7 @@ impl From<EntityDataValue> for UpdateMetadataError {
# impl Default for AllayBundle {
# fn default() -> Self {
# Self {
# _marker: Allay,
# parent: AbstractCreatureBundle {
# on_fire: OnFire(false),
# shift_key_down: ShiftKeyDown(false),
@ -297,7 +300,14 @@ impl From<EntityDataValue> for UpdateMetadataError {
def generate_fields(this_entity_id: str):
# on_fire: OnFire(false),
# shift_key_down: ShiftKeyDown(false),
# if it has a parent, put it (recursion)
# _marker
this_entity_struct_name = upper_first_letter(
to_camel_case(this_entity_id.lstrip('~')))
code.append(
f' _marker: {this_entity_struct_name},')
# if it has a parent, put it (do recursion)
# parent: AbstractCreatureBundle { ... },
this_entity_parent_ids = get_entity_parents(
this_entity_id, burger_entity_data)
@ -305,7 +315,7 @@ impl From<EntityDataValue> for UpdateMetadataError {
this_entity_parent_ids) > 1 else None
if this_entity_parent_id:
bundle_struct_name = upper_first_letter(
to_camel_case(this_entity_parent_id.lstrip('~'))) + 'Bundle'
to_camel_case(this_entity_parent_id.lstrip('~'))) + 'MetadataBundle'
code.append(
f' parent: {bundle_struct_name} {{')
generate_fields(this_entity_parent_id)
@ -388,14 +398,14 @@ impl From<EntityDataValue> for UpdateMetadataError {
for entity_id in burger_entity_data:
new_entity(entity_id)
# and now make the main update_metadatas
# pub fn update_metadatas(
# entity: bevy_ecs::world::EntityMut,
# and now make the main apply_metadata
# pub fn apply_metadata(
# entity: &mut bevy_ecs::world::EntityMut,
# items: Vec<EntityDataItem>,
# ) -> Result<(), UpdateMetadataError> {
# if entity.contains::<Allay>() {
# for d in items {
# Allay::update_metadata(entity, d)?;
# Allay::apply_metadata(entity, d)?;
# }
# return Ok(());
# }
@ -403,24 +413,51 @@ impl From<EntityDataValue> for UpdateMetadataError {
# Ok(())
# }
code.append(
f'pub fn update_metadatas(mut entity: bevy_ecs::world::EntityMut, items: Vec<EntityDataItem>) -> Result<(), UpdateMetadataError> {{')
f'pub fn apply_metadata(entity: &mut bevy_ecs::world::EntityMut, items: Vec<EntityDataItem>) -> Result<(), UpdateMetadataError> {{')
code.append(
' let entity_kind = entity.get::<super::EntityKind>().unwrap();')
code.append(' match **entity_kind {')
for entity_id in burger_entity_data:
if entity_id.startswith('~'):
# not actually an entity
continue
struct_name: str = upper_first_letter(to_camel_case(entity_id))
code.append(
f' if entity.contains::<{struct_name}>() {{')
code.append(' for d in items {')
f' azalea_registry::EntityKind::{struct_name} => {{')
code.append(' for d in items {')
code.append(
f' {struct_name}::update_metadata(&mut entity, d)?;')
code.append(' }')
code.append(f' return Ok(());')
code.append(' }')
f' {struct_name}::apply_metadata(entity, d)?;')
code.append(' }')
code.append(' },')
code.append(' }')
code.append(' Ok(())')
code.append('}')
code.append('')
# pub fn apply_default_metadata(entity: &mut bevy_ecs::world::EntityMut, kind: azalea_registry::EntityKind) {
# match kind {
# azalea_registry::EntityKind::AreaEffectCloud => {
# entity.insert(AreaEffectCloudMetadataBundle::default());
# }
# }
# }
code.append(
'pub fn apply_default_metadata(entity: &mut bevy_ecs::world::EntityMut, kind: azalea_registry::EntityKind) {')
code.append(' match kind {')
for entity_id in burger_entity_data:
if entity_id.startswith('~'):
# not actually an entity
continue
struct_name: str = upper_first_letter(to_camel_case(entity_id))
code.append(
f' azalea_registry::EntityKind::{struct_name} => {{')
code.append(
f' entity.insert({struct_name}MetadataBundle::default());')
code.append(' },')
code.append(' }')
code.append('}')
code.append('')
with open(METADATA_RS_DIR, 'w') as f:
f.write('\n'.join(code))

View file

@ -61,6 +61,7 @@ impl<T: Registry> McBufWritable for OptionalRegistry<T> {
registry_name = registry_name[:-5] + '_kind'
registry_struct_name = to_camel_case(registry_name.split(':')[1])
code.append(f'registry!({registry_struct_name}, {{')
registry_entries = sorted(
registry['entries'].items(), key=lambda x: x[1]['protocol_id'])