Implement the spear's use action: charge, stab, knockback, dismount
This commit is contained in:
@@ -26,6 +26,13 @@ pub enum ItemPose {
|
||||
Bow {
|
||||
ticks_used: f32,
|
||||
},
|
||||
/// A spear being charged (`ItemUseAnimation.SPEAR`): the time held and
|
||||
/// the ticks since its last hit's feedback.
|
||||
Spear {
|
||||
kinetic: crate::spear::Kinetic,
|
||||
time_held: f32,
|
||||
ticks_since_hit: f32,
|
||||
},
|
||||
Crossbow {
|
||||
ticks_used: Option<f32>,
|
||||
charge_duration: f32,
|
||||
@@ -69,6 +76,16 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -
|
||||
if matches!(pose, ItemPose::Using) {
|
||||
return m;
|
||||
}
|
||||
// The spear's own place in the hand, without the equip height.
|
||||
if let ItemPose::Spear {
|
||||
kinetic,
|
||||
time_held,
|
||||
ticks_since_hit,
|
||||
} = pose
|
||||
{
|
||||
return Mat4::from_translation(Vec3::new(invert * 0.56, -0.52, -0.72))
|
||||
* crate::spear::first_person_use(&kinetic, ticks_since_hit, time_held, !left);
|
||||
}
|
||||
if matches!(pose, ItemPose::SpinAttack) {
|
||||
return m
|
||||
* Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3))
|
||||
|
||||
@@ -165,6 +165,7 @@ mod shield;
|
||||
mod sign_edit;
|
||||
mod sniffers;
|
||||
mod spawner;
|
||||
mod spear;
|
||||
mod spill;
|
||||
mod startup_menu;
|
||||
mod station_control;
|
||||
@@ -1681,6 +1682,18 @@ struct Game<'a> {
|
||||
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
|
||||
/// Successful crits (attacking guest, hit entity), queued while the hub is taken.
|
||||
lan_critical_hits: Vec<(Option<u32>, i32, bool)>,
|
||||
/// Spear stabs that landed (the stabbing guest), queued while the hub is
|
||||
/// taken: `broadcastEntityEvent(player, 2)`.
|
||||
lan_kinetic_hits: Vec<Option<u32>>,
|
||||
/// `LivingEntity.recentKineticEnemies`: when each player (a guest, or the
|
||||
/// window's own) last stabbed each entity this use.
|
||||
stabbed: HashMap<(Option<u32>, u32), i64>,
|
||||
/// The movement a guest's client reported this tick
|
||||
/// (`ServerPlayer.getKnownMovement`), for their turn.
|
||||
known_movement: Vec3,
|
||||
/// `LivingEntity.lastKineticHitFeedbackTime` of the entities that felt a
|
||||
/// spear's hit (`spear::OWN` is this window's player), in game time.
|
||||
kinetic_feedback: HashMap<i32, i64>,
|
||||
/// Global level events for every guest (`ServerLevel.globalLevelEvent`).
|
||||
lan_global_events: Vec<(i32, [i32; 3], i32)>,
|
||||
/// `ContainerOpenersCounter`: how many players (the host and the guests)
|
||||
@@ -3926,6 +3939,7 @@ impl Game<'_> {
|
||||
|| self.use_fishing_rod(&stack)
|
||||
|| self.use_crossbow(&stack)
|
||||
|| self.use_trident(&stack)
|
||||
|| self.use_spear(&stack)
|
||||
|| self.boost_firework(&stack)
|
||||
|| self.use_empty_map(&stack)
|
||||
|| self.use_book(&stack)
|
||||
@@ -4199,6 +4213,12 @@ impl Game<'_> {
|
||||
self.using = Some((slot, ticks + 1));
|
||||
return;
|
||||
}
|
||||
// ItemStack.onUseTick: a spear stabs what its speed allows, until released.
|
||||
if horizon_client::spear::Kinetic::of(&stack.item).is_some() {
|
||||
self.spear_tick(&stack, ticks);
|
||||
self.using = Some((slot, ticks + 1));
|
||||
return;
|
||||
}
|
||||
if &*stack.item == "minecraft:spyglass" {
|
||||
// SpyglassItem.USE_DURATION, then finishUsingItem.
|
||||
if ticks + 1 >= 1200 {
|
||||
@@ -9953,7 +9973,17 @@ impl Game<'_> {
|
||||
let ticks_used =
|
||||
owner.use_duration as f32 - (owner.use_item_remaining_ticks as f32 - a + 1.0);
|
||||
use horizon_client::first_person::ItemPose;
|
||||
// ItemUseAnimation.SPEAR.
|
||||
let spear = using
|
||||
.then(|| horizon_client::spear::Kinetic::of(&stack.item))
|
||||
.flatten()
|
||||
.map(|kinetic| ItemPose::Spear {
|
||||
kinetic,
|
||||
time_held: ticks_used,
|
||||
ticks_since_hit: self.kinetic_hit_ticks(a),
|
||||
});
|
||||
let pose = match &*stack.item {
|
||||
_ if let Some(pose) = spear => pose,
|
||||
"minecraft:bow" if using => ItemPose::Bow { ticks_used },
|
||||
"minecraft:crossbow" => {
|
||||
let charged = stack.data().is_some_and(|d| !d.charged.is_empty());
|
||||
@@ -13096,6 +13126,10 @@ impl<'a> Game<'a> {
|
||||
lan_block_events: Vec::new(),
|
||||
lan_entity_events: Vec::new(),
|
||||
lan_critical_hits: Vec::new(),
|
||||
lan_kinetic_hits: Vec::new(),
|
||||
stabbed: HashMap::new(),
|
||||
known_movement: Vec3::ZERO,
|
||||
kinetic_feedback: HashMap::new(),
|
||||
lan_global_events: Vec::new(),
|
||||
lid_openers: HashMap::new(),
|
||||
lan_acting: None,
|
||||
|
||||
@@ -105,6 +105,7 @@ impl Game<'_> {
|
||||
match ty.trim_start_matches("minecraft:") {
|
||||
"player_attack" => DamageKind::PlayerAttack,
|
||||
"mace_smash" => DamageKind::MaceSmash,
|
||||
"spear" => DamageKind::Spear,
|
||||
"mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack,
|
||||
"arrow" => DamageKind::Arrow,
|
||||
"thrown" | "trident" | "mob_projectile" => DamageKind::Thrown,
|
||||
@@ -1218,7 +1219,7 @@ impl Game<'_> {
|
||||
/// LivingEntity.stopRiding for a mob: off its vehicle
|
||||
/// (Entity.removePassenger), then to where the vehicle lets it out
|
||||
/// (LivingEntity.dismountVehicle).
|
||||
fn dismount_mob(&mut self, rider: u32) {
|
||||
pub(in crate::game) fn dismount_mob(&mut self, rider: u32) {
|
||||
let Some(i) = self.mobs.iter().position(|m| m.id == rider) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -3683,6 +3683,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool)
|
||||
match kind {
|
||||
K::PlayerAttack => "minecraft:player_attack",
|
||||
K::MaceSmash => "minecraft:mace_smash",
|
||||
K::Spear => "minecraft:spear",
|
||||
K::MobAttack => "minecraft:mob_attack",
|
||||
K::Arrow => "minecraft:arrow",
|
||||
K::Thrown => "minecraft:thrown",
|
||||
|
||||
@@ -672,6 +672,7 @@ impl Game<'_> {
|
||||
}
|
||||
let source = match source.kind {
|
||||
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
|
||||
horizon_client::mobs::DamageKind::Spear => "minecraft:spear",
|
||||
_ => "minecraft:player_attack",
|
||||
};
|
||||
out.push(format!(
|
||||
|
||||
@@ -69,7 +69,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// `getEnchantedDamage - base`: damage bonus of the held weapon against a mob type.
|
||||
pub(super) fn enchant_damage_bonus(&mut self, target: &str) -> f32 {
|
||||
let Some(held) = self.inventory[self.selected].clone() else {
|
||||
let Some(held) = self.held().cloned() else {
|
||||
return 0.0;
|
||||
};
|
||||
let ctx = EffectContext {
|
||||
@@ -102,7 +102,7 @@ impl Game<'_> {
|
||||
/// whether the hit is that knockback attack.
|
||||
pub(super) fn extra_knockback(&mut self, target_kind: &str, scale: f32) -> (f32, bool) {
|
||||
let knockback_attack = scale > 0.9 && self.player.as_ref().is_some_and(|p| p.sprinting);
|
||||
let enchanted = match self.inventory[self.selected].clone() {
|
||||
let enchanted = match self.held().cloned() {
|
||||
Some(held) => {
|
||||
let ctx = EffectContext {
|
||||
this: Some(target_kind),
|
||||
@@ -144,7 +144,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// After a successful melee hit: fire aspect and wind burst.
|
||||
pub(super) fn post_attack(&mut self, mob: usize) {
|
||||
let Some(held) = self.inventory[self.selected].clone() else {
|
||||
let Some(held) = self.held().cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(m) = self.mobs.get(mob) else { return };
|
||||
|
||||
@@ -170,6 +170,9 @@ fn use_duration(components: &Components) -> i32 {
|
||||
let seconds = c["consume_seconds"].as_f64().unwrap_or(1.6);
|
||||
return (seconds * 20.0) as i32;
|
||||
}
|
||||
if components.get("minecraft:kinetic_weapon").is_some() {
|
||||
return 72_000;
|
||||
}
|
||||
let item_model = components
|
||||
.get("minecraft:item_model")
|
||||
.and_then(Value::as_str)
|
||||
|
||||
@@ -1330,6 +1330,7 @@ impl Game<'_> {
|
||||
/// Send the tick's level events, sounds and mob animations.
|
||||
fn lan_flush_effects(&mut self, host: &mut LanHost) {
|
||||
let critical_hits = std::mem::take(&mut self.lan_critical_hits);
|
||||
let kinetic_hits = std::mem::take(&mut self.lan_kinetic_hits);
|
||||
for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) {
|
||||
if kind == 2001 {
|
||||
host.broken
|
||||
@@ -1381,7 +1382,12 @@ impl Game<'_> {
|
||||
// A projectile is the direct entity of its hit: not tracked here.
|
||||
let melee = matches!(
|
||||
source.kind,
|
||||
K::PlayerAttack | K::MaceSmash | K::MobAttack | K::Sting | K::SonicBoom
|
||||
K::PlayerAttack
|
||||
| K::MaceSmash
|
||||
| K::Spear
|
||||
| K::MobAttack
|
||||
| K::Sting
|
||||
| K::SonicBoom
|
||||
);
|
||||
let direct = cause.filter(|_| melee);
|
||||
host.hub.damage_event(m.id as i32, kind, cause, direct, at);
|
||||
@@ -1402,6 +1408,19 @@ impl Game<'_> {
|
||||
seen.insert(m.id, (m.hurt_time, dead, swing));
|
||||
}
|
||||
host.mob_state.insert(self.dim, seen);
|
||||
// Level.broadcastEntityEvent(player, 2) of a spear's stab.
|
||||
for attacker in kinetic_hits {
|
||||
let hit = match attacker {
|
||||
None => self
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|p| (host.host_entity, [p.position.x, p.position.y, p.position.z])),
|
||||
Some(conn) => host.hub.guest(conn).map(|g| (g.entity_id, g.position)),
|
||||
};
|
||||
if let Some((id, at)) = hit {
|
||||
host.hub.entity_event(id, 2, at);
|
||||
}
|
||||
}
|
||||
for (attacker, target, magic) in critical_hits {
|
||||
let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| {
|
||||
host.hub.guest(conn).map(|g| g.entity_id)
|
||||
|
||||
@@ -1935,7 +1935,13 @@ impl Game<'_> {
|
||||
let using = play.using.is_some();
|
||||
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
|
||||
if digging.is_some() || using || delayed {
|
||||
// ServerPlayer.getKnownMovement: the move their client just sent.
|
||||
let movement = host.hub.guests[gi]
|
||||
.moves
|
||||
.last()
|
||||
.map_or(Vec3::ZERO, |m| Vec3::new(m.0[0], m.0[1], m.0[2]));
|
||||
self.as_guest(host, conn, |g| {
|
||||
g.known_movement = movement;
|
||||
g.attack_ticks = g.attack_ticks.saturating_add(1);
|
||||
if let Some((pos, face)) = digging {
|
||||
g.forced_hit = Some(Hit {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
enchant::EffectContext,
|
||||
items::ItemStack,
|
||||
mobs::{Damage, Mob, Species},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
@@ -100,7 +101,7 @@ impl Game<'_> {
|
||||
/// `LivingEntity.hurtServer` of the mob at `index` by the player's hit:
|
||||
/// the weapon's `armor_effectiveness` enchantments (Breach) thin its armor.
|
||||
pub(super) fn hurt_by_player(&mut self, index: usize, amount: f32, source: Damage) -> bool {
|
||||
let held = self.inventory[self.selected].clone();
|
||||
let held = self.held().cloned();
|
||||
let kind = self.mobs[index].kind.id.clone();
|
||||
let ctx = EffectContext {
|
||||
this: Some(&kind),
|
||||
@@ -109,6 +110,7 @@ impl Game<'_> {
|
||||
is_direct: true,
|
||||
damage_type: Some(match source.kind {
|
||||
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
|
||||
horizon_client::mobs::DamageKind::Spear => "minecraft:spear",
|
||||
_ => "minecraft:player_attack",
|
||||
}),
|
||||
items: Some(self.res.items()),
|
||||
@@ -138,7 +140,7 @@ impl Game<'_> {
|
||||
/// the post-attack enchantments, then `postHurtEnemy` with the weapon's
|
||||
/// wear.
|
||||
pub(super) fn weapon_hit(&mut self, index: usize) {
|
||||
let Some(stack) = self.inventory[self.selected].clone() else {
|
||||
let Some(stack) = self.held().cloned() else {
|
||||
return;
|
||||
};
|
||||
let weapon = self
|
||||
@@ -158,16 +160,26 @@ impl Game<'_> {
|
||||
if smash && let Some(p) = self.player.as_mut() {
|
||||
p.fall_distance = 0.0;
|
||||
}
|
||||
// ItemStack.postHurtEnemy: hurtAndBreak(weapon.itemDamagePerAttack).
|
||||
self.weapon_wear(&stack);
|
||||
}
|
||||
/// `ItemStack.postHurtEnemy`: `hurtAndBreak(weapon.itemDamagePerAttack)` of
|
||||
/// the weapon in the acting hand.
|
||||
pub(super) fn weapon_wear(&mut self, stack: &ItemStack) {
|
||||
let weapon = self
|
||||
.res
|
||||
.items()
|
||||
.get(&stack.item)
|
||||
.and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage)));
|
||||
if let Some((per_attack, max)) = weapon
|
||||
&& max > 0
|
||||
&& !self.creative
|
||||
{
|
||||
let loss = self.durability_loss(&stack, per_attack);
|
||||
if let Some(held) = self.inventory[self.selected].as_mut() {
|
||||
let loss = self.durability_loss(stack, per_attack);
|
||||
let cell = self.held_mut();
|
||||
if let Some(held) = cell.as_mut() {
|
||||
held.damage += loss;
|
||||
if held.damage >= max {
|
||||
self.inventory[self.selected] = None;
|
||||
*cell = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2123,6 +2123,10 @@ impl Game<'_> {
|
||||
self.remote_firework_explosion(p.id);
|
||||
}
|
||||
self.remote_fangs_event(p.id as u32, p.event);
|
||||
// LivingEntity.handleEntityEvent 2: a spear's hit felt.
|
||||
if p.event == 2 {
|
||||
self.remote_kinetic_hit(p.id);
|
||||
}
|
||||
// LocalPlayer.setPermissions also refreshes an open World Options screen.
|
||||
if (24..=28).contains(&p.event)
|
||||
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
|
||||
@@ -4394,6 +4398,8 @@ impl Game<'_> {
|
||||
}
|
||||
// SpyglassItem.use (its sound is the server's).
|
||||
"minecraft:spyglass" => true,
|
||||
// Item.use: a kinetic weapon starts being used.
|
||||
id if horizon_client::spear::Kinetic::of(id).is_some() => true,
|
||||
// ShieldItem.use: anything that blocks attacks, off cooldown.
|
||||
_ => {
|
||||
self.raise_shield(self.held_slot());
|
||||
@@ -4410,7 +4416,8 @@ impl Game<'_> {
|
||||
matches!(
|
||||
&*stack.item,
|
||||
"minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass"
|
||||
) || self.blocks_attacks(stack).is_some()
|
||||
) || horizon_client::spear::Kinetic::of(&stack.item).is_some()
|
||||
|| self.blocks_attacks(stack).is_some()
|
||||
}
|
||||
|
||||
/// The rest of Minecraft.startUseItem once the main hand's target passed:
|
||||
@@ -5516,7 +5523,8 @@ fn hand_id(hand: Hand) -> i32 {
|
||||
/// server decides; this is the client's guess of whether to go on.
|
||||
fn item_has_use(info: &horizon_client::items::ItemInfo) -> bool {
|
||||
let id = info.id.trim_start_matches("minecraft:");
|
||||
info.consumable.is_some()
|
||||
id.ends_with("_spear")
|
||||
|| info.consumable.is_some()
|
||||
|| info.equip_slot.is_some()
|
||||
|| info.blocks_attacks.is_some()
|
||||
|| horizon_client::items::bucket_contents(&info.id).is_some()
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Spears (`KineticWeapon`): holding the use button charges the spear, and
|
||||
//! from `delay_ticks` on every living entity along the view that the
|
||||
//! player's speed allows is stabbed: the damage grows with the speed
|
||||
//! relative to the target, the knockback and the dismount need the
|
||||
//! attacker's own speed, and each condition runs out after its time
|
||||
//! (`Item.use`, `ItemStack.onUseTick`, `KineticWeapon.damageEntities`,
|
||||
//! `Player.stabAttack`). The hit's feedback (`onKineticHit`) reaches the
|
||||
//! players around as entity event 2.
|
||||
use super::{Game, view_vector};
|
||||
use horizon_client::{
|
||||
collisions::SceneCollisions,
|
||||
items::ItemStack,
|
||||
mobs::Damage,
|
||||
spear::{HIT_FEEDBACK_TICKS, Kinetic, REACH},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, traverse_blocks},
|
||||
position::BlockPos,
|
||||
};
|
||||
|
||||
/// The key of this window's own player in `Game::kinetic_feedback`.
|
||||
pub(super) const OWN: i32 = i32::MIN;
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Item.use` of a kinetic weapon: `startUsingItem` with a new
|
||||
/// `recentKineticEnemies`, and `KineticWeapon.makeSound` at the user.
|
||||
pub(super) fn use_spear(&mut self, stack: &ItemStack) -> bool {
|
||||
let Some(kinetic) = Kinetic::of(&stack.item) else {
|
||||
return false;
|
||||
};
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
let actor = self.lan_acting;
|
||||
self.stabbed.retain(|(who, _), _| *who != actor);
|
||||
if let Some(p) = &self.player {
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
self.audio.play(kinetic.sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `ServerPlayer.getKnownMovement` of the acting player: what they moved
|
||||
/// in the last tick. A guest's comes with their moves.
|
||||
fn known_player_movement(&self) -> Vec3 {
|
||||
if self.lan_acting.is_some() {
|
||||
return self.known_movement;
|
||||
}
|
||||
self.player
|
||||
.as_ref()
|
||||
.map_or(Vec3::ZERO, |p| p.position.subtract(self.previous_position))
|
||||
}
|
||||
|
||||
/// `Entity.getKnownSpeed` of the mob at `index`, per second: its root
|
||||
/// vehicle's (`KineticWeapon.getMotion`).
|
||||
fn mob_speed(&self, index: usize) -> Vec3 {
|
||||
let mut mob = &self.mobs[index];
|
||||
while let Some(vehicle) = mob
|
||||
.extra
|
||||
.mount
|
||||
.and_then(|v| self.mobs.iter().find(|m| m.id == v))
|
||||
{
|
||||
mob = vehicle;
|
||||
}
|
||||
mob.position.subtract(mob.previous).scale(20.0)
|
||||
}
|
||||
|
||||
/// `Level.clip` with COLLIDER shapes and no fluids: where the segment
|
||||
/// first meets a block, if it does (tall grass lets a stab through).
|
||||
fn clip_collider(&self, from: Vec3, to: Vec3) -> Option<Vec3> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
traverse_blocks(from, to, 512, |p: BlockPos| {
|
||||
let state = self.world.block(p.x, p.y, p.z);
|
||||
if self.res.facts().is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p).map(|hit| hit.location)
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// `ProjectileUtil.getHitEntitiesAlong` for the mobs: those whose box the
|
||||
/// segment `from`..`to` meets, or comes within the margin of with no
|
||||
/// block between.
|
||||
fn mobs_along(&self, from: Vec3, to: Vec3, margin: f64) -> Vec<usize> {
|
||||
let grow = Vec3::new(margin, margin, margin);
|
||||
let mut hits = Vec::new();
|
||||
for (i, m) in self.mobs.iter().enumerate() {
|
||||
// PiercingWeapon.canHitEntity: alive, and not the vehicle ridden.
|
||||
if !m.alive() || m.removed || self.riding == Some(m.id) {
|
||||
continue;
|
||||
}
|
||||
let bounds: Aabb = m.bounds();
|
||||
let hit = bounds.contains(from)
|
||||
|| bounds.clip(from, to).is_some()
|
||||
|| (margin > 0.0
|
||||
&& bounds.inflate(grow).clip(from, to).is_some_and(|outside| {
|
||||
let centre = bounds.center();
|
||||
let toward = self.clip_collider(outside, centre).unwrap_or(centre);
|
||||
bounds.clip(outside, toward).is_some()
|
||||
}));
|
||||
if hit {
|
||||
hits.push(i);
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// `KineticWeapon.damageEntities`: one tick of the spear in use, `ticks`
|
||||
/// ticks into the use.
|
||||
pub(super) fn spear_tick(&mut self, stack: &ItemStack, ticks: u32) {
|
||||
let Some(kinetic) = Kinetic::of(&stack.item) else {
|
||||
return;
|
||||
};
|
||||
let used = ticks as i32 - kinetic.delay_ticks;
|
||||
let (Some(eye), Some(feet)) = (
|
||||
self.eye_position(),
|
||||
self.player.as_ref().map(|p| p.position),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
if used < 0 || self.spectator() {
|
||||
return;
|
||||
}
|
||||
let eye = Vec3::new(eye[0], eye[1], eye[2]);
|
||||
let look = view_vector(self.yaw, self.pitch);
|
||||
let look = Vec3::new(look[0], look[1], look[2]);
|
||||
let movement = self.known_player_movement();
|
||||
let attacker_speed = look.dot(movement.scale(20.0));
|
||||
// AttackRange.effectiveMinRange and effectiveMaxRange for a player.
|
||||
let (min, max) = if self.creative {
|
||||
(REACH.min_creative, REACH.max_creative)
|
||||
} else {
|
||||
(REACH.min, REACH.max)
|
||||
};
|
||||
let from = eye.add_vector(look.scale(f64::from(min)));
|
||||
let mut to = eye.add_vector(look.scale(f64::from(max) + movement.dot(look).max(0.0)));
|
||||
// A block closer than the minimum reach takes the whole stab.
|
||||
if let Some(block) = self.clip_collider(eye, to) {
|
||||
to = block;
|
||||
if eye.distance_squared(to) < eye.distance_squared(from) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let now = self.world.game_time;
|
||||
let actor = self.lan_acting;
|
||||
let mut affected = false;
|
||||
for i in self.mobs_along(from, to, f64::from(REACH.hitbox_margin)) {
|
||||
let key = (actor, self.mobs[i].id);
|
||||
let recent = self
|
||||
.stabbed
|
||||
.get(&key)
|
||||
.is_some_and(|&t| now - t < i64::from(kinetic.contact_cooldown_ticks));
|
||||
if recent {
|
||||
continue;
|
||||
}
|
||||
self.stabbed.insert(key, now);
|
||||
let target_speed = look.dot(self.mob_speed(i));
|
||||
let relative = (attacker_speed - target_speed).max(0.0);
|
||||
// An entity factor of 1 for a player.
|
||||
let dismounts = kinetic.dismount.test(used, attacker_speed, relative, 1.0);
|
||||
let pushes = kinetic.knockback.test(used, attacker_speed, relative, 1.0);
|
||||
let damages = kinetic.damage.test(used, attacker_speed, relative, 1.0);
|
||||
if dismounts || pushes || damages {
|
||||
// The attack damage attribute's base value (1) and the speed.
|
||||
let amount = 1.0 + (relative * f64::from(kinetic.damage_multiplier)).floor() as f32;
|
||||
affected |= self.stab_mob(i, amount, damages, pushes, dismounts);
|
||||
}
|
||||
}
|
||||
if affected {
|
||||
// Level.broadcastEntityEvent(player, 2), felt by the player too.
|
||||
if self.audio.capture.is_some() {
|
||||
self.lan_kinetic_hits.push(actor);
|
||||
}
|
||||
let who = actor.map_or(OWN, |conn| conn as i32);
|
||||
self.kinetic_hit_feedback(who, &kinetic, [feet.x, feet.y, feet.z]);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Player.stabAttack` on the mob at `index`: whether it was affected.
|
||||
fn stab_mob(
|
||||
&mut self,
|
||||
index: usize,
|
||||
base_damage: f32,
|
||||
deals_damage: bool,
|
||||
deals_knockback: bool,
|
||||
dismounts: bool,
|
||||
) -> bool {
|
||||
let kind = format!(
|
||||
"minecraft:{}",
|
||||
self.mobs[index].kind.id.trim_start_matches("minecraft:")
|
||||
);
|
||||
let id = self.mobs[index].id;
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let from = [p.position.x, p.position.y, p.position.z];
|
||||
// The enchantments' share, with no attack strength scaling for a
|
||||
// weapon in use.
|
||||
let magic_boost = self.enchant_damage_bonus(&kind);
|
||||
let total = if deals_damage {
|
||||
base_damage + magic_boost
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let old_health = self.mobs[index].health;
|
||||
let hurt = deals_damage && self.hurt_by_player(index, total, Damage::spear(from));
|
||||
// causeExtraKnockback: a push of 0.4, then the weapon's Knockback.
|
||||
if deals_knockback {
|
||||
let (xd, zd) = self.extra_knockback_direction();
|
||||
self.mobs[index].knockback(0.4, xd, zd);
|
||||
let (strength, _) = self.extra_knockback(&kind, 0.0);
|
||||
self.mobs[index].knockback(f64::from(strength), xd, zd);
|
||||
}
|
||||
let dismounted = dismounts && self.mobs[index].extra.mount.is_some();
|
||||
if dismounted {
|
||||
self.dismount_mob(id);
|
||||
}
|
||||
if !hurt && !deals_knockback && !dismounted {
|
||||
return false;
|
||||
}
|
||||
let mob = &self.mobs[index];
|
||||
let (feet, width, height) = (
|
||||
[mob.position.x, mob.position.y, mob.position.z],
|
||||
mob.kind.width,
|
||||
mob.kind.height,
|
||||
);
|
||||
// attackVisualEffects: no attack sound, the enchantments' magic crit.
|
||||
if magic_boost > 0.0 {
|
||||
self.critical_hit(self.lan_acting, id as i32, feet, width, height, true);
|
||||
}
|
||||
self.combat.last_hurt_mob = Some((id, self.world.game_time));
|
||||
// itemAttackInteraction: hurtEnemy (statistic, wear), and the
|
||||
// post-attack enchantments when the target was hurt.
|
||||
if let Some(stack) = self.held().cloned() {
|
||||
self.stats.add("used", &stack.item, 1);
|
||||
if hurt {
|
||||
self.post_attack(index);
|
||||
}
|
||||
self.weapon_wear(&stack);
|
||||
}
|
||||
// damageStatsAndHearts.
|
||||
let actual = old_health - self.mobs[index].health;
|
||||
self.stats
|
||||
.custom("damage_dealt", (actual * 10.0).round() as i32);
|
||||
if actual > 2.0 {
|
||||
let indicator = horizon_client::particles::ParticleOptions::simple(
|
||||
horizon_client::particles::ParticleType::DamageIndicator,
|
||||
);
|
||||
self.particles.send_particles(
|
||||
&indicator,
|
||||
[feet[0], feet[1] + height * 0.5, feet[2]],
|
||||
[0.1, 0.0, 0.1],
|
||||
0.2,
|
||||
(actual * 0.5) as u32,
|
||||
);
|
||||
}
|
||||
if hurt {
|
||||
self.last_hurt_by_player.insert(id, self.lan_acting);
|
||||
}
|
||||
if let Some(p) = self.player.as_mut()
|
||||
&& !self.creative
|
||||
{
|
||||
p.cause_food_exhaustion(0.1);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `LivingEntity.onKineticHit` for `entity`: the hit feels (the spear
|
||||
/// moves back, `kinetic_hit_ticks`) and sounds, at most once every ten
|
||||
/// ticks.
|
||||
pub(super) fn kinetic_hit_feedback(&mut self, entity: i32, kinetic: &Kinetic, at: [f64; 3]) {
|
||||
let now = self.world.game_time;
|
||||
if self
|
||||
.kinetic_feedback
|
||||
.get(&entity)
|
||||
.is_none_or(|&t| now - t > HIT_FEEDBACK_TICKS)
|
||||
{
|
||||
self.kinetic_feedback.insert(entity, now);
|
||||
self.audio
|
||||
.play_unshared(kinetic.hit_sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `getTicksSinceLastKineticHitFeedback` of this window's player.
|
||||
pub(super) fn kinetic_hit_ticks(&self, partial: f32) -> f32 {
|
||||
self.kinetic_feedback
|
||||
.get(&OWN)
|
||||
.map_or(0.0, |&t| (self.world.game_time - t) as f32 + partial)
|
||||
}
|
||||
|
||||
/// `LivingEntity.handleEntityEvent(2)` on a server's client: the
|
||||
/// player `id` (this one, or another) was hit by the spear it uses.
|
||||
pub(super) fn remote_kinetic_hit(&mut self, id: i32) {
|
||||
let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id);
|
||||
let (item, at) = if own {
|
||||
let item = self
|
||||
.using
|
||||
.and_then(|(slot, _)| self.stack_in(slot))
|
||||
.map(|s| s.item.clone());
|
||||
let at = self.player.as_ref().map(|p| p.position);
|
||||
(item, at)
|
||||
} else {
|
||||
let mob = self
|
||||
.mobs
|
||||
.iter()
|
||||
.find(|m| m.id == id as u32 && m.extra.using_item > 0);
|
||||
let item = mob.and_then(|m| {
|
||||
if m.extra.using_off_hand {
|
||||
m.extra.off_hand.clone()
|
||||
} else {
|
||||
m.extra.main_hand.clone()
|
||||
}
|
||||
});
|
||||
(item, mob.map(|m| m.position))
|
||||
};
|
||||
if let (Some(kinetic), Some(at)) = (item.as_deref().and_then(Kinetic::of), at) {
|
||||
self.kinetic_hit_feedback(if own { OWN } else { id }, &kinetic, [at.x, at.y, at.z]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,7 @@ pub mod skins;
|
||||
pub mod sound_engine;
|
||||
pub mod sound_events;
|
||||
pub mod spans;
|
||||
pub mod spear;
|
||||
pub mod sprint;
|
||||
pub mod sprites;
|
||||
pub mod stations;
|
||||
|
||||
@@ -507,6 +507,8 @@ pub enum DamageKind {
|
||||
PlayerAttack,
|
||||
/// `mace_smash`: a mace hit after a fall (the player attack tags too).
|
||||
MaceSmash,
|
||||
/// `spear`: a stab of a spear (the player attack tags too).
|
||||
Spear,
|
||||
MobAttack,
|
||||
Arrow,
|
||||
Thrown,
|
||||
@@ -567,6 +569,14 @@ impl Damage {
|
||||
from: Some(from),
|
||||
}
|
||||
}
|
||||
/// `DamageSources.spear`: a player's stab with a spear.
|
||||
pub fn spear(from: [f64; 3]) -> Self {
|
||||
Self {
|
||||
kind: DamageKind::Spear,
|
||||
attacker: Some(Who::Player),
|
||||
from: Some(from),
|
||||
}
|
||||
}
|
||||
pub fn mob(id: u32, from: [f64; 3]) -> Self {
|
||||
Self {
|
||||
kind: DamageKind::MobAttack,
|
||||
|
||||
@@ -244,6 +244,8 @@ pub enum ArmPose {
|
||||
CrossbowCharge,
|
||||
/// Raising a trident to throw it (or to launch with Riptide).
|
||||
ThrowTrident,
|
||||
/// A spear held out (`HumanoidModel.ArmPose.SPEAR`), at rest or charging.
|
||||
Spear,
|
||||
}
|
||||
/// HumanoidModel.setupAnim with empty hands (endermen).
|
||||
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
|
||||
@@ -295,6 +297,10 @@ pub struct Hum {
|
||||
pub swing_right_arm: Option<bool>,
|
||||
/// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it.
|
||||
pub left_main: bool,
|
||||
/// The spear each arm (right, left) holds, and how long that arm has
|
||||
/// been using it (`ticksUsingItem(arm)`, 0 when it is not).
|
||||
pub spear: [Option<crate::spear::Kinetic>; 2],
|
||||
pub spear_ticks: [f32; 2],
|
||||
}
|
||||
impl Hum {
|
||||
pub fn new(right: ArmPose, left: ArmPose) -> Self {
|
||||
@@ -313,6 +319,8 @@ impl Hum {
|
||||
using_item: false,
|
||||
swing_right_arm: None,
|
||||
left_main: false,
|
||||
spear: [None; 2],
|
||||
spear_ticks: [0.0; 2],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -388,6 +396,23 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
|
||||
}
|
||||
ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right),
|
||||
ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right),
|
||||
// SpearAnimations.thirdPersonHandUse.
|
||||
ArmPose::Spear => {
|
||||
let side = usize::from(!right);
|
||||
let Some(kinetic) = h.spear[side] else {
|
||||
return;
|
||||
};
|
||||
let (x, y, z) = crate::spear::third_person_arm(
|
||||
&kinetic,
|
||||
h.spear_ticks[side],
|
||||
right,
|
||||
(hx, hy),
|
||||
h.fall_flying || h.swim > 0.0,
|
||||
);
|
||||
p.xrot(arm, x);
|
||||
p.yrot(arm, y);
|
||||
p.get(arm)[5] += z;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`).
|
||||
@@ -687,6 +712,14 @@ pub fn setup(
|
||||
ArmPose::Empty
|
||||
};
|
||||
let using_main = m.extra.using_item > 0 && !m.extra.using_off_hand;
|
||||
// AvatarRenderer.getArmPose: an arm holding a spear (at rest too).
|
||||
let spear_in = |hand: &Option<std::sync::Arc<str>>| {
|
||||
hand.as_deref()
|
||||
.filter(|_| player)
|
||||
.and_then(crate::spear::Kinetic::of)
|
||||
};
|
||||
let (main_spear, off_spear) =
|
||||
(spear_in(&m.extra.main_hand), spear_in(&m.extra.off_hand));
|
||||
let pose = if player {
|
||||
match m.extra.main_hand.as_deref() {
|
||||
Some(_) if using_main && m.extra.blocking => ArmPose::Block,
|
||||
@@ -698,6 +731,7 @@ pub fn setup(
|
||||
Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => {
|
||||
ArmPose::CrossbowHold
|
||||
}
|
||||
Some(_) if main_spear.is_some() => ArmPose::Spear,
|
||||
Some(_) => ArmPose::Item,
|
||||
None => ArmPose::Empty,
|
||||
}
|
||||
@@ -705,7 +739,9 @@ pub fn setup(
|
||||
right
|
||||
};
|
||||
let off = if player && m.extra.off_hand.is_some() && !pose.affects_offhand() {
|
||||
if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking {
|
||||
if off_spear.is_some() {
|
||||
ArmPose::Spear
|
||||
} else if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking {
|
||||
ArmPose::Block
|
||||
} else {
|
||||
ArmPose::Item
|
||||
@@ -731,6 +767,17 @@ pub fn setup(
|
||||
h.using_item = m.extra.using_item > 0;
|
||||
h.swing_right_arm = m.extra.swing_right_arm;
|
||||
h.left_main = m.main_arm_left();
|
||||
let main_side = usize::from(m.main_arm_left());
|
||||
h.spear[main_side] = main_spear;
|
||||
h.spear[1 - main_side] = off_spear;
|
||||
if m.extra.using_item > 0 {
|
||||
let using_side = if m.extra.using_off_hand {
|
||||
1 - main_side
|
||||
} else {
|
||||
main_side
|
||||
};
|
||||
h.spear_ticks[using_side] = m.extra.using_item as f32 + s.partial;
|
||||
}
|
||||
humanoid(p, s, &h);
|
||||
if m.ai.aggressive && !bow {
|
||||
// SkeletonModel melee pose.
|
||||
|
||||
@@ -118,6 +118,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
|
||||
source.kind,
|
||||
DamageKind::PlayerAttack
|
||||
| DamageKind::MaceSmash
|
||||
| DamageKind::Spear
|
||||
| DamageKind::MobAttack
|
||||
| DamageKind::Arrow
|
||||
| DamageKind::Thrown
|
||||
|
||||
@@ -294,7 +294,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
&& let Some((d, _)) = m.last_damage
|
||||
&& matches!(
|
||||
d.kind,
|
||||
DamageKind::PlayerAttack | DamageKind::MaceSmash | DamageKind::MobAttack
|
||||
DamageKind::PlayerAttack
|
||||
| DamageKind::MaceSmash
|
||||
| DamageKind::Spear
|
||||
| DamageKind::MobAttack
|
||||
)
|
||||
{
|
||||
let from = [m.position.x, m.position.y, m.position.z];
|
||||
|
||||
@@ -1292,7 +1292,23 @@ pub fn held_item_transform(
|
||||
.unwrap_or_else(|| m.kind.model.clone());
|
||||
let mut poses = Poses::new(&model);
|
||||
anim::setup(m, &s, &mut poses, &data.animations);
|
||||
hand_base(m, &model, base, &poses, left)
|
||||
let mut t = hand_base(m, &model, base, &poses, left)?;
|
||||
// ItemInHandLayer: a spear in use (ArmPose.SPEAR's animateUseItem).
|
||||
let off_hand = left != m.main_arm_left();
|
||||
if m.extra.using_item > 0
|
||||
&& m.extra.using_off_hand == off_hand
|
||||
&& let Some(kinetic) = (if off_hand {
|
||||
&m.extra.off_hand
|
||||
} else {
|
||||
&m.extra.main_hand
|
||||
})
|
||||
.as_deref()
|
||||
.and_then(crate::spear::Kinetic::of)
|
||||
{
|
||||
let time_held = m.extra.using_item as f32 + s.partial;
|
||||
t *= crate::spear::third_person_use_item(&kinetic, time_held, s.swing, 0.0, !left);
|
||||
}
|
||||
Some(t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -290,6 +290,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool {
|
||||
source.kind,
|
||||
DamageKind::PlayerAttack
|
||||
| DamageKind::MaceSmash
|
||||
| DamageKind::Spear
|
||||
| DamageKind::MobAttack
|
||||
| DamageKind::Arrow
|
||||
| DamageKind::Thrown
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
//! Spears: `KineticWeapon` (what holding the use button does: the speed
|
||||
//! conditions of a stab, `Item.Properties.spear`'s numbers) and
|
||||
//! `SpearAnimations` (how the spear is held in first and third person while
|
||||
//! it charges).
|
||||
use glam::{Mat4, Vec3};
|
||||
use horizon_core::{geometry::trig::Mth, jmath::pow};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
/// `KineticWeapon.Condition`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Condition {
|
||||
pub max_duration_ticks: i32,
|
||||
pub min_speed: f32,
|
||||
pub min_relative_speed: f32,
|
||||
}
|
||||
impl Condition {
|
||||
pub fn test(
|
||||
self,
|
||||
ticks_used: i32,
|
||||
attacker_speed: f64,
|
||||
relative_speed: f64,
|
||||
entity_factor: f64,
|
||||
) -> bool {
|
||||
ticks_used <= self.max_duration_ticks
|
||||
&& attacker_speed >= f64::from(self.min_speed) * entity_factor
|
||||
&& relative_speed >= f64::from(self.min_relative_speed) * entity_factor
|
||||
}
|
||||
}
|
||||
|
||||
/// `KineticWeapon`: a spear's charge.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Kinetic {
|
||||
pub contact_cooldown_ticks: i32,
|
||||
pub delay_ticks: i32,
|
||||
pub dismount: Condition,
|
||||
pub knockback: Condition,
|
||||
pub damage: Condition,
|
||||
pub forward_movement: f32,
|
||||
pub damage_multiplier: f32,
|
||||
pub sound: &'static str,
|
||||
pub hit_sound: &'static str,
|
||||
}
|
||||
|
||||
/// `AttackRange` of a spear: the reach of its stabs.
|
||||
pub struct Reach {
|
||||
pub min: f32,
|
||||
pub max: f32,
|
||||
pub min_creative: f32,
|
||||
pub max_creative: f32,
|
||||
pub hitbox_margin: f32,
|
||||
pub mob_factor: f32,
|
||||
}
|
||||
pub const REACH: Reach = Reach {
|
||||
min: 2.0,
|
||||
max: 4.5,
|
||||
min_creative: 2.0,
|
||||
max_creative: 6.5,
|
||||
hitbox_margin: 0.125,
|
||||
mob_factor: 0.5,
|
||||
};
|
||||
|
||||
impl Kinetic {
|
||||
/// The `kinetic_weapon` of a spear item (`Item.Properties.spear`).
|
||||
pub fn of(item: &str) -> Option<Self> {
|
||||
// (damage multiplier, delay, dismount time and speed, knockback time
|
||||
// and speed, damage time and speed): seconds and blocks per second.
|
||||
let (multiplier, delay, dismount, knockback, damage) = match item {
|
||||
"minecraft:wooden_spear" => (0.7, 0.75, (5.0, 14.0), (10.0, 5.1), (15.0, 4.6)),
|
||||
"minecraft:stone_spear" => (0.82, 0.7, (4.5, 13.0), (9.0, 5.1), (13.75, 4.6)),
|
||||
"minecraft:copper_spear" => (0.82, 0.65, (4.0, 12.0), (8.25, 5.1), (12.5, 4.6)),
|
||||
"minecraft:iron_spear" => (0.95, 0.6, (2.5, 11.0), (6.75, 5.1), (11.25, 4.6)),
|
||||
"minecraft:golden_spear" => (0.7, 0.7, (3.5, 13.0), (8.5, 5.1), (13.75, 4.6)),
|
||||
"minecraft:diamond_spear" => (1.075, 0.5, (3.0, 10.0), (6.5, 5.1), (10.0, 4.6)),
|
||||
"minecraft:netherite_spear" => (1.2, 0.4, (2.5, 9.0), (5.5, 5.1), (8.75, 4.6)),
|
||||
_ => return None,
|
||||
};
|
||||
let wood = item == "minecraft:wooden_spear";
|
||||
let ticks = |seconds: f32| (seconds * 20.0) as i32;
|
||||
Some(Self {
|
||||
contact_cooldown_ticks: 10,
|
||||
delay_ticks: ticks(delay),
|
||||
// `Condition.ofAttackerSpeed`, and `ofRelativeSpeed` for the damage.
|
||||
dismount: Condition {
|
||||
max_duration_ticks: ticks(dismount.0),
|
||||
min_speed: dismount.1,
|
||||
min_relative_speed: 0.0,
|
||||
},
|
||||
knockback: Condition {
|
||||
max_duration_ticks: ticks(knockback.0),
|
||||
min_speed: knockback.1,
|
||||
min_relative_speed: 0.0,
|
||||
},
|
||||
damage: Condition {
|
||||
max_duration_ticks: ticks(damage.0),
|
||||
min_speed: 0.0,
|
||||
min_relative_speed: damage.1,
|
||||
},
|
||||
forward_movement: 0.38,
|
||||
damage_multiplier: multiplier,
|
||||
sound: if wood {
|
||||
"minecraft:item.spear_wood.use"
|
||||
} else {
|
||||
"minecraft:item.spear.use"
|
||||
},
|
||||
hit_sound: if wood {
|
||||
"minecraft:item.spear_wood.hit"
|
||||
} else {
|
||||
"minecraft:item.spear.hit"
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `KineticWeapon.HIT_FEEDBACK_TICKS`.
|
||||
pub const HIT_FEEDBACK_TICKS: i64 = 10;
|
||||
|
||||
/// `Mth.clamp` on floats (a NaN stays one).
|
||||
fn clamp(v: f32, lo: f32, hi: f32) -> f32 {
|
||||
if v < lo { lo } else { v.min(hi) }
|
||||
}
|
||||
/// `SpearAnimations.progress`.
|
||||
fn progress(time: f32, start: f32, end: f32) -> f32 {
|
||||
clamp((time - start) / (end - start), 0.0, 1.0)
|
||||
}
|
||||
fn square(x: f32) -> f32 {
|
||||
x * x
|
||||
}
|
||||
fn cube(x: f32) -> f32 {
|
||||
x * x * x
|
||||
}
|
||||
fn p(x: f32, y: f64) -> f64 {
|
||||
pow(f64::from(x), y)
|
||||
}
|
||||
|
||||
// `net.minecraft.util.Ease`.
|
||||
fn in_quad(x: f32) -> f32 {
|
||||
x * x
|
||||
}
|
||||
fn out_quart(x: f32) -> f32 {
|
||||
1.0 - square(square(1.0 - x))
|
||||
}
|
||||
fn out_cubic(x: f32) -> f32 {
|
||||
1.0 - cube(1.0 - x)
|
||||
}
|
||||
fn out_back(x: f32) -> f32 {
|
||||
1.0 + 2.70158 * cube(x - 1.0) + 1.70158 * square(x - 1.0)
|
||||
}
|
||||
fn in_out_sine(x: f32) -> f32 {
|
||||
-((PI * x).mcos() - 1.0) / 2.0
|
||||
}
|
||||
fn in_out_expo(x: f32) -> f32 {
|
||||
if x < 0.5 {
|
||||
if x == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
(p(2.0, f64::from(20.0 * x - 10.0)) / 2.0) as f32
|
||||
}
|
||||
} else if x == 1.0 {
|
||||
1.0
|
||||
} else {
|
||||
((2.0 - p(2.0, f64::from(-20.0 * x + 10.0))) / 2.0) as f32
|
||||
}
|
||||
}
|
||||
fn in_out_back(x: f32) -> f32 {
|
||||
if x < 0.5 {
|
||||
return 4.0 * x * x * (7.189_819 * x - 2.594_909_4) / 2.0;
|
||||
}
|
||||
let dt = 2.0 * x - 2.0;
|
||||
(dt * dt * (3.594_909_4 * dt + 2.594_909_4) + 2.0) / 2.0
|
||||
}
|
||||
fn in_out_elastic(x: f32) -> f32 {
|
||||
if x == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
if x == 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let sin = (f64::from(20.0 * x - 11.125) * f64::from(PI * 4.0 / 9.0)).sin();
|
||||
if x < 0.5 {
|
||||
(-(p(2.0, f64::from(20.0 * x - 10.0)) * sin) / 2.0) as f32
|
||||
} else {
|
||||
(p(2.0, f64::from(-20.0 * x + 10.0)) * sin / 2.0 + 1.0) as f32
|
||||
}
|
||||
}
|
||||
fn out_circ(x: f32) -> f32 {
|
||||
f64::from(1.0 - square(x - 1.0)).sqrt() as f32
|
||||
}
|
||||
fn in_circ(x: f32) -> f32 {
|
||||
(-f64::from(1.0 - x * x).sqrt()) as f32 + 1.0
|
||||
}
|
||||
|
||||
/// `SpearAnimations.UseParams`.
|
||||
struct UseParams {
|
||||
raise: f32,
|
||||
raise_start: f32,
|
||||
raise_middle: f32,
|
||||
raise_end: f32,
|
||||
sway: f32,
|
||||
lower: f32,
|
||||
raise_back: f32,
|
||||
sway_intensity: f32,
|
||||
sway_slow: f32,
|
||||
sway_fast: f32,
|
||||
}
|
||||
impl UseParams {
|
||||
fn of(k: &Kinetic, time: f32) -> Self {
|
||||
let finish_raising = k.delay_ticks;
|
||||
let finish_swaying = k.dismount.max_duration_ticks + finish_raising;
|
||||
let start_swaying = finish_swaying - 20;
|
||||
let finish_lowering = k.knockback.max_duration_ticks + finish_raising;
|
||||
let start_lowering = finish_lowering - 40;
|
||||
let finish_raising_back = k.damage.max_duration_ticks + finish_raising;
|
||||
let raise = progress(time, 0.0, finish_raising as f32);
|
||||
let sway = progress(time, start_swaying as f32, finish_swaying as f32);
|
||||
let lower = out_cubic(in_out_elastic(progress(
|
||||
time - 20.0,
|
||||
start_lowering as f32,
|
||||
finish_lowering as f32,
|
||||
)));
|
||||
let raise_back = progress(
|
||||
time,
|
||||
(finish_raising_back - 5) as f32,
|
||||
finish_raising_back as f32,
|
||||
);
|
||||
let sway_intensity = 2.0 * out_circ(sway) - 2.0 * in_circ(raise_back);
|
||||
let degrees = PI / 180.0;
|
||||
Self {
|
||||
raise,
|
||||
raise_start: progress(raise, 0.0, 0.5),
|
||||
raise_middle: progress(raise, 0.5, 0.8),
|
||||
raise_end: progress(raise, 0.8, 1.0),
|
||||
sway,
|
||||
lower,
|
||||
raise_back,
|
||||
sway_intensity,
|
||||
sway_slow: (time * 19.0 * degrees).msin() * sway_intensity,
|
||||
sway_fast: (time * 30.0 * degrees).msin() * sway_intensity,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `SpearAnimations.hitFeedbackAmount`.
|
||||
fn hit_feedback(ticks_since: f32) -> f32 {
|
||||
0.4 * (out_quart(progress(ticks_since, 1.0, 3.0))
|
||||
- in_out_sine(progress(ticks_since, 3.0, 10.0)))
|
||||
}
|
||||
|
||||
/// `PoseStack.rotateAround`.
|
||||
fn rotate_around(rotation: Mat4, about: Vec3) -> Mat4 {
|
||||
Mat4::from_translation(about) * rotation * Mat4::from_translation(-about)
|
||||
}
|
||||
|
||||
/// `SpearAnimations.firstPersonUse`, after the hand's own
|
||||
/// `translate(invert * 0.56, -0.52, -0.72)`.
|
||||
pub fn first_person_use(k: &Kinetic, ticks_since_hit: f32, time_held: f32, right: bool) -> Mat4 {
|
||||
let u = UseParams::of(k, time_held);
|
||||
let invert = if right { 1.0 } else { -1.0 };
|
||||
let degrees = |d: f32| d.to_radians();
|
||||
let mut m = Mat4::from_translation(Vec3::new(
|
||||
invert * (u.raise * 0.15 + u.raise_end * -0.05 + u.sway * -0.1 + u.sway_slow * 0.005),
|
||||
u.raise * -0.075 + u.raise_middle * 0.075 + u.sway_fast * 0.01,
|
||||
u.raise_start * 0.05 + u.raise_end * -0.05 + u.sway_slow * 0.005,
|
||||
));
|
||||
m *= rotate_around(
|
||||
Mat4::from_rotation_x(degrees(
|
||||
-65.0 * in_out_back(u.raise) - 35.0 * u.lower
|
||||
+ 100.0 * u.raise_back
|
||||
+ -0.5 * u.sway_fast,
|
||||
)),
|
||||
Vec3::new(0.0, 0.1, 0.0),
|
||||
);
|
||||
// Axis.YN: a turn the other way round.
|
||||
m *= rotate_around(
|
||||
Mat4::from_rotation_y(-degrees(
|
||||
invert * (-90.0 * progress(u.raise, 0.5, 0.55) + 90.0 * u.sway + 2.0 * u.sway_slow),
|
||||
)),
|
||||
Vec3::new(invert * 0.15, 0.0, 0.0),
|
||||
);
|
||||
m * Mat4::from_translation(Vec3::new(0.0, -hit_feedback(ticks_since_hit), 0.0))
|
||||
}
|
||||
|
||||
/// `SpearAnimations.thirdPersonHandUse`: the angles (x, y and the z added to
|
||||
/// the arm's own) of the arm holding a spear. `ticks_using` is the time the
|
||||
/// item has been in use by this arm (0 when it is not).
|
||||
pub fn third_person_arm(
|
||||
k: &Kinetic,
|
||||
ticks_using: f32,
|
||||
right: bool,
|
||||
head: (f32, f32),
|
||||
gliding_or_swimming: bool,
|
||||
) -> (f32, f32, f32) {
|
||||
let invert = if right { 1.0 } else { -1.0 };
|
||||
let degrees = PI / 180.0;
|
||||
let mut y = -0.1 * invert + head.1;
|
||||
let mut x = -PI / 2.0 + head.0 + 0.8;
|
||||
if gliding_or_swimming {
|
||||
x -= 0.959_931_1;
|
||||
}
|
||||
y = degrees * clamp(180.0 / PI * y, -60.0, 60.0);
|
||||
x = degrees * clamp(180.0 / PI * x, -120.0, 30.0);
|
||||
let mut z = 0.0;
|
||||
if ticks_using > 0.0 {
|
||||
let u = UseParams::of(k, ticks_using);
|
||||
y += -invert * u.sway_fast * degrees * u.sway_intensity;
|
||||
z = -invert * u.sway_slow * degrees * u.sway_intensity * 0.5;
|
||||
x += degrees
|
||||
* (-40.0 * u.raise_start
|
||||
+ 30.0 * u.raise_middle
|
||||
+ -20.0 * u.raise_end
|
||||
+ 20.0 * u.lower
|
||||
+ 10.0 * u.raise_back
|
||||
+ 0.6 * u.sway_slow * u.sway_intensity);
|
||||
}
|
||||
(x, y, z)
|
||||
}
|
||||
|
||||
/// `SpearAnimations.thirdPersonUseItem`: the spear's own pose in the hand
|
||||
/// held for `time_held` ticks, `swing` into the current swing.
|
||||
pub fn third_person_use_item(
|
||||
k: &Kinetic,
|
||||
time_held: f32,
|
||||
swing: f32,
|
||||
ticks_since_hit: f32,
|
||||
right: bool,
|
||||
) -> Mat4 {
|
||||
if time_held == 0.0 {
|
||||
return Mat4::IDENTITY;
|
||||
}
|
||||
let attack = in_quad(progress(swing, 0.05, 0.2));
|
||||
let retract = in_out_expo(progress(swing, 0.4, 1.0));
|
||||
let u = UseParams::of(k, time_held);
|
||||
let invert = if right { 1.0 } else { -1.0 };
|
||||
let raise_modified = 1.0 - out_back(1.0 - u.raise);
|
||||
let hit = hit_feedback(ticks_since_hit);
|
||||
let degrees = |d: f32| d.to_radians();
|
||||
Mat4::from_translation(Vec3::new(
|
||||
0.0,
|
||||
-hit * 0.4,
|
||||
-k.forward_movement * (raise_modified - u.raise_back) + hit,
|
||||
)) * rotate_around(
|
||||
Mat4::from_rotation_x(-degrees(
|
||||
70.0 * (u.raise - u.raise_back) - 40.0 * (attack - retract),
|
||||
)),
|
||||
Vec3::new(0.0, -0.031_25, 0.125),
|
||||
) * rotate_around(
|
||||
Mat4::from_rotation_y(degrees(
|
||||
invert * 90.0 * (u.raise - u.sway + 3.0 * retract + attack),
|
||||
)),
|
||||
Vec3::new(0.0, 0.0, 0.125),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user