diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index 799b588b4..0511ef930 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -43,7 +43,7 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { } writeln!( out, - "{} {} {} {} {} {} {} {:016x} {} {} {} {:08x}", + "{} {} {} {} {} {} {} {:016x} {} {} {} {:08x} {}", player.collision.horizontal, player.collision.vertical, player.collision.below, @@ -55,7 +55,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { position(player.last_climbable), player.needs_sync, player.sync_position, - player.speed.to_bits() + player.speed.to_bits(), + player.no_jump_delay )?; Ok(()) } @@ -90,6 +91,11 @@ fn main() -> Result<()> { }; match op["mode"].as_str().unwrap() { "travel" => world.travel_in_air(vector(&op["value"]))?, + "tick" => { + let v = vector(&op["value"]); + world.movement_tick([v.x as f32, v.y as f32, v.z as f32])?; + } + "delay" => world.player.no_jump_delay = op["value"].as_i64().unwrap() as i32, "move" => world.move_self(vector(&op["value"]))?, "jump" => world.jump_from_ground()?, "sprint" => world.player.set_sprinting(op["value"].as_bool().unwrap())?, diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 6eb7f64f2..8118cca28 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -121,6 +121,7 @@ pub struct PlayerMotion { pub stuck_multiplier: Vec3, pub yaw: f32, pub jumping: bool, + pub no_jump_delay: i32, pub sprinting: bool, pub speed: f32, pub last_climbable: Option, @@ -164,6 +165,7 @@ impl PlayerMotion { stuck_multiplier: Vec3::ZERO, yaw: 0.0, jumping: false, + no_jump_delay: 0, sprinting: false, speed: 0.0, last_climbable: None, @@ -292,6 +294,37 @@ impl MotionWorld<'_, '_, '_> { pub fn travel_in_air(&mut self, input: Vec3) -> Result<()> { living_air::travel_in_air(self, input) } + /// Dry, standing movement phases of LivingEntity.aiStep. Equipment, + /// interpolation, effects, freezing and world/entity effects are not ticked + /// by this binding. Inputs are the native float xxa/yya/zza fields. + pub fn movement_tick(&mut self, input: [f32; 3]) -> Result<()> { + if self.player.no_jump_delay > 0 { + self.player.no_jump_delay -= 1; + } + let mut velocity = self.player.velocity; + if velocity.x * velocity.x + velocity.z * velocity.z < 9.0e-6 { + velocity.x = 0.0; + velocity.z = 0.0; + } + if velocity.y.abs() < 0.003 { + velocity.y = 0.0; + } + self.player.velocity = velocity; + let input = Vec3::new( + f64::from(input[0] * 0.98), + f64::from(input[1]), + f64::from(input[2] * 0.98), + ); + if self.player.jumping { + if self.player.ground.on_ground && self.player.no_jump_delay == 0 { + self.jump_from_ground()?; + self.player.no_jump_delay = 10; + } + } else { + self.player.no_jump_delay = 0; + } + self.travel_in_air(input) + } pub fn jump_from_ground(&mut self) -> Result<()> { living_motion::jump_from_ground(self) } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java index 63fba95f8..0ec051d40 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java @@ -2,6 +2,7 @@ package dev.horizonlab.parity; import com.google.gson.*; import java.io.*; import java.lang.reflect.*; +import java.lang.invoke.*; import java.nio.file.*; import java.util.*; import net.minecraft.core.*; @@ -26,7 +27,8 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*; * actual block scanning, support updates and restitution. Landing and external * sound/event/network consumers are controlled phase boundaries. */ public final class VanillaSceneMotionOracle { - static Field position,history,support,noBlocks,last,stuck; + static Field position,history,support,noBlocks,last,stuck,delay; + static MethodHandle aiStep; static float single(JsonElement v){return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(),16));} static void write(Field f,Object o,Object value){try{f.set(o,value);}catch(Exception e){throw new AssertionError(e);}} static Field field(Class c,String n)throws Exception{var f=c.getDeclaredField(n);f.setAccessible(true);return f;} @@ -41,6 +43,7 @@ public final class VanillaSceneMotionOracle { @Override public BlockState getBlockState(BlockPos p){var c=chunks.get(key(p.getX()>>4,p.getZ()>>4));return c==null?Blocks.AIR.defaultBlockState():c.getBlockState(p);} @Override public FluidState getFluidState(BlockPos p){return getBlockState(p).getFluidState();} @Override public List getEntityCollisions(Entity e,AABB b){return List.of();} + @Override public List getPushableEntities(Entity e,AABB b){return List.of();} @Override public WorldBorder getWorldBorder(){return border;} @Override public void gameEvent(Holder event,Vec3 pos,GameEvent.Context context){} } @@ -79,14 +82,25 @@ public final class VanillaSceneMotionOracle { @Override protected void playStepSound(BlockPos p,BlockState state){} @Override public void causeFoodExhaustion(float v){} @Override public void gameEvent(Holder event,Entity source){} + @Override protected boolean isImmobile(){return false;} + @Override public LivingEntity getControllingPassenger(){return null;} + @Override public double getFluidHeight(net.minecraft.tags.TagKey tag){return 0;} + @Override public double getFluidJumpThreshold(){return .4;} + @Override public int getTicksFrozen(){return 0;} + @Override public void setTicksFrozen(int value){if(value!=0)throw new AssertionError(value);} + @Override protected void applyEffectsFromBlocks(){} + void movementTick(Vec3 input)throws Exception { + xxa=(float)input.x;yya=(float)input.y;zza=(float)input.z; + try{aiStep.invoke((LivingEntity)this);}catch(Throwable t){if(t instanceof Exception e)throw e;throw new AssertionError(t);} + } } static String pos(Object v){var o=(Optional)v;return o.isEmpty()?"none":((BlockPos)o.get()).getX()+","+((BlockPos)o.get()).getY()+","+((BlockPos)o.get()).getZ();} static void snapshot(PrintWriter out,Actor p)throws Exception{ AABB b=p.getBoundingBox(); for(var v:List.of(p.position(),p.getDeltaMovement(),new Vec3(b.minX,b.minY,b.minZ),new Vec3(b.maxX,b.maxY,b.maxZ))) out.printf("%016x %016x %016x ",Double.doubleToLongBits(v.x),Double.doubleToLongBits(v.y),Double.doubleToLongBits(v.z)); - out.printf("%s %s %s %s %s %s %s %016x %s %s %s %08x%n",p.horizontalCollision,p.verticalCollision,p.verticalCollisionBelow,p.minorHorizontalCollision, - p.onGround(),noBlocks.getBoolean(p),pos(support.get(p)),Double.doubleToLongBits(p.fallDistance),pos(last.get(p)),p.needsSync,p.syncPosition,Float.floatToIntBits(p.speed)); + out.printf("%s %s %s %s %s %s %s %016x %s %s %s %08x %d%n",p.horizontalCollision,p.verticalCollision,p.verticalCollisionBelow,p.minorHorizontalCollision, + p.onGround(),noBlocks.getBoolean(p),pos(support.get(p)),Double.doubleToLongBits(p.fallDistance),pos(last.get(p)),p.needsSync,p.syncPosition,Float.floatToIntBits(p.speed),delay.getInt(p)); } public static void main(String[] args)throws Exception{ net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); @@ -94,6 +108,8 @@ public final class VanillaSceneMotionOracle { var u=Class.forName("sun.misc.Unsafe");var f=u.getDeclaredField("theUnsafe");f.setAccessible(true);var unsafe=f.get(null);var allocate=u.getMethod("allocateInstance",Class.class); position=field(Entity.class,"position");history=field(Entity.class,"movementThisTick");support=field(Entity.class,"mainSupportingBlockPos");noBlocks=field(Entity.class,"onGroundNoBlocks");last=field(LivingEntity.class,"lastClimbablePos");stuck=field(Entity.class,"stuckSpeedMultiplier"); var abilities=field(Player.class,"abilities"); + delay=field(LivingEntity.class,"noJumpDelay"); + aiStep=MethodHandles.privateLookupIn(LivingEntity.class,MethodHandles.lookup()).findSpecial(LivingEntity.class,"aiStep",MethodType.methodType(void.class),LivingEntity.class); var description=JsonParser.parseString(Files.readString(dir.resolve("scene.json"))).getAsJsonObject(); var trace=new Trace();trace.out=new PrintWriter(OutputStream.nullOutputStream());trace.fail=-1; var level=(Level)allocate.invoke(unsafe,Level.class);level.chunks=VanillaSceneCollisionOracle.scene(description,trace);level.border=new Border(); @@ -101,12 +117,16 @@ public final class VanillaSceneMotionOracle { for(var line:(Iterable)lines::iterator){ var row=JsonParser.parseString(line).getAsJsonObject();var p=(Actor)allocate.invoke(unsafe,Actor.class);p.configure(level); write(field(Entity.class,"type"),p,EntityTypes.PLAYER); + write(field(Entity.class,"interpolationHandler"),p,InterpolationHandler.NO_OP); + write(field(LivingEntity.class,"equipment"),p,new EntityEquipment()); p.attrs=new AttributeMap(VanillaEntityAttributeOracle.supplier(EntityTypes.PLAYER)); write(history,p,new ArrayDeque<>());write(support,p,Optional.empty());write(last,p,Optional.empty());write(stuck,p,Vec3.ZERO);write(abilities,p,new Abilities()); p.setDeltaMovement(Vec3.ZERO);p.setPos(VanillaSceneCollisionOracle.vector(row.get("position"))); for(var value:row.getAsJsonArray("ops")){ var op=value.getAsJsonObject();switch(op.get("mode").getAsString()){ case "travel"->p.travel(VanillaSceneCollisionOracle.vector(op.get("value"))); + case "tick"->p.movementTick(VanillaSceneCollisionOracle.vector(op.get("value"))); + case "delay"->delay.setInt(p,op.get("value").getAsInt()); case "move"->p.move(MoverType.SELF,VanillaSceneCollisionOracle.vector(op.get("value"))); case "jump"->p.jumpFromGround(); case "sprint"->p.setSprinting(op.get("value").getAsBoolean()); diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index 2b1b44449..7183ce56b 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -20,6 +20,20 @@ def vec(values): return list(map(bits, values)) def op(mode, value=None, **extra): return dict(mode=mode, value=value, **extra) def corpus(): + # Native LivingEntity.aiStep drives repeated held/released jumps and the + # player-specific horizontal velocity threshold, including delay boundaries. + for start in [(25,4,25),(-11,4,0),(-7,4,26),(0,18,0)]: + for delay in [-1,0,1,9,10,11]: + ops=[op('speed',single(.1)),op('delay',delay),op('jumping',True)] + for i in range(180): + if i in [35,120]:ops.append(op('jumping',False)) + if i in [36,140]:ops.append(op('jumping',True)) + ops.append(op('tick',vec((.5 if i<90 else 0,0,0)))) + yield dict(position=vec(start),ops=ops) + for x in [0,-0.0,.002,.0021213203435596424,.0029999999999999996,.003,.004]: + for z in [0,.002,.003,-.002]: + for y in [-.003,-.0029999999999999996,-0.0,0,.0029999999999999996,.003]: + yield dict(position=vec((25,12,25)),ops=[op('velocity',vec((x,y,z))),op('tick',vec((0,0,0))),op('tick',vec((0,0,0)))]) for start in [(25,18,25),(0,18,0),(-15.9,4,-15.9),(-11,4,0),(5,4,14),(-7,4,26)]: for yaw in [0,45,90,180,-135]: for sprint in [False,True]: