Fix player control of coupled carts and copper rail slope overlays
This commit is contained in:
@@ -12,6 +12,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
@Mixin(AbstractMinecart.class)
|
||||
public abstract class TrainCartMixin implements CartFrame {
|
||||
@Unique private Vec3 astra$front=Vec3.ZERO;
|
||||
@Unique private Vec3 astra$beforePlayerPush;
|
||||
@Override public Vec3 astracontent$front(){return astra$front;}
|
||||
@Override public void astracontent$front(Vec3 axis){astra$front=axis;}
|
||||
@Inject(method="addAdditionalSaveData",at=@At("RETURN"))
|
||||
@@ -21,8 +22,17 @@ public abstract class TrainCartMixin implements CartFrame {
|
||||
double x=in.getDoubleOr("AstraTrainFrontX",0),z=in.getDoubleOr("AstraTrainFrontZ",0);
|
||||
astra$front=Double.isFinite(x)&&Double.isFinite(z)?new Vec3(x,0,z).normalize():Vec3.ZERO;
|
||||
}
|
||||
@Inject(method="push",at=@At("HEAD"),cancellable=true)
|
||||
@Inject(method="push(Lnet/minecraft/world/entity/Entity;)V",at=@At("HEAD"),cancellable=true)
|
||||
private void astra$noInternalCollision(Entity other,CallbackInfo ci){
|
||||
if(other instanceof AbstractMinecart cart && Trains.connected((AbstractMinecart)(Object)this,cart))ci.cancel();
|
||||
var self=(AbstractMinecart)(Object)this;
|
||||
astra$beforePlayerPush=other instanceof net.minecraft.world.entity.player.Player?self.getDeltaMovement():null;
|
||||
if(other instanceof AbstractMinecart cart && Trains.connected(self,cart))ci.cancel();
|
||||
}
|
||||
@Inject(method="push(Lnet/minecraft/world/entity/Entity;)V",at=@At("RETURN"))
|
||||
private void astra$playerPush(Entity other,CallbackInfo ci){
|
||||
var self=(AbstractMinecart)(Object)this;
|
||||
if(astra$beforePlayerPush!=null && self.getDeltaMovement().subtract(astra$beforePlayerPush).horizontalDistanceSqr()>1e-12)
|
||||
Trains.playerPush(self);
|
||||
astra$beforePlayerPush=null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,16 +20,13 @@ final class RailDisplay extends Display.ItemDisplay {
|
||||
}
|
||||
void update(RailKind kind, BlockState state) {
|
||||
var shape = state.getValue(PoweredRailBlock.SHAPE);
|
||||
boolean eastWest = shape == net.minecraft.world.level.block.state.properties.RailShape.EAST_WEST
|
||||
|| shape == net.minecraft.world.level.block.state.properties.RailShape.ASCENDING_EAST
|
||||
|| shape == net.minecraft.world.level.block.state.properties.RailShape.ASCENDING_WEST;
|
||||
String model = "rail_display/" + kind.age() + "/" + state.getValue(PoweredRailBlock.SHAPE).getSerializedName()
|
||||
+ (state.getValue(PoweredRailBlock.POWERED) ? "_on" : "");
|
||||
if (model.equals(previous)) return;
|
||||
var stack = new ItemStack(Items.PAPER); stack.set(DataComponents.ITEM_MODEL,Identifier.fromNamespaceAndPath("astracontent",model));
|
||||
getSlot(0).set(stack); previous=model;
|
||||
setTransformation(new com.mojang.math.Transformation(new org.joml.Vector3f(),
|
||||
new org.joml.Quaternionf().rotateY(eastWest ? -(float)Math.PI/2 : 0),new org.joml.Vector3f(1),new org.joml.Quaternionf()));
|
||||
RailDisplayTransform.orientation(shape),new org.joml.Vector3f(1),new org.joml.Quaternionf()));
|
||||
}
|
||||
@Override public boolean shouldBeSaved() { return false; }
|
||||
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
import org.joml.Quaternionf;
|
||||
|
||||
final class RailDisplayTransform {
|
||||
private RailDisplayTransform(){}
|
||||
static Quaternionf orientation(RailShape shape){
|
||||
boolean eastWest=shape==RailShape.EAST_WEST||shape==RailShape.ASCENDING_EAST||shape==RailShape.ASCENDING_WEST;
|
||||
// ItemDisplayRenderer itself applies Y=180 degrees before drawing an item model.
|
||||
// Cancel that turn so the model's raised end matches the actual rail's raised end.
|
||||
return new Quaternionf().rotateY((float)Math.PI+(eastWest?-(float)Math.PI/2:0));
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,12 @@ public final class Trains {
|
||||
private record DisplayKey(ServerLevel level,TrainData.Link link){}
|
||||
private static final Map<DisplayKey,ChainDisplay> DISPLAYS=new HashMap<>();
|
||||
private static final Map<ServerLevel,Set<UUID>> PAUSED=new HashMap<>();
|
||||
private static final Map<ServerLevel,Set<UUID>> PLAYER_PUSHES=new HashMap<>();
|
||||
private Trains(){}
|
||||
public static boolean paused(AbstractMinecart cart){return PAUSED.getOrDefault(cart.level(),Set.of()).contains(cart.getUUID());}
|
||||
public static void playerPush(AbstractMinecart cart){
|
||||
if(cart.level() instanceof ServerLevel level)PLAYER_PUSHES.computeIfAbsent(level,key->new HashSet<>()).add(cart.getUUID());
|
||||
}
|
||||
public static boolean isChain(ItemStack stack){return stack.getItem() instanceof BlockItem item && item.getBlock() instanceof ChainBlock;}
|
||||
public static boolean connected(AbstractMinecart a,AbstractMinecart b){
|
||||
return a.level() instanceof ServerLevel level && b.level()==level
|
||||
@@ -89,6 +93,7 @@ public final class Trains {
|
||||
/** Synchronize momentum along each cart's rail tangent; springs correct chain slack, never teleport carts. */
|
||||
public static void step(ServerLevel level){
|
||||
var pausedCarts=new HashSet<UUID>();PAUSED.put(level,pausedCarts);
|
||||
var playerPushes=PLAYER_PUSHES.remove(level);if(playerPushes==null)playerPushes=Set.of();
|
||||
var data=TrainData.get(level);var links=data.links();var visited=new HashSet<UUID>();
|
||||
for(var seed:links){
|
||||
if(visited.contains(seed.a()))continue;
|
||||
@@ -102,16 +107,23 @@ public final class Trains {
|
||||
}
|
||||
visited.addAll(signs.keySet());var carts=new LinkedHashMap<UUID,AbstractMinecart>();
|
||||
var axes=new HashMap<UUID,Vec3>();boolean paused=false;double momentum=0,limit=Double.MAX_VALUE;
|
||||
double controlledMomentum=0;var controls=new HashSet<UUID>();
|
||||
for(var pair:signs.entrySet()){
|
||||
var cart=cart(level,pair.getKey());if(cart==null){paused=true;continue;}carts.put(pair.getKey(),cart);
|
||||
Vec3 tangent=CouplingGeometry.axis(cart).scale(pair.getValue());axes.put(pair.getKey(),tangent);
|
||||
if(!(level.getBlockState(cart.getCurrentBlockPosOrRailBelow()).getBlock() instanceof BaseRailBlock))paused=true;
|
||||
double scale=travelScale(cart);momentum+=cart.getDeltaMovement().dot(tangent)*scale;
|
||||
if(playerPushes.contains(cart.getUUID()) || cart.getFirstPassenger() instanceof net.minecraft.server.level.ServerPlayer player
|
||||
&& player.getLastClientMoveIntent().horizontalDistanceSqr()>0){
|
||||
controlledMomentum+=alignedSpeed(cart,tangent)*scale;controls.add(cart.getUUID());
|
||||
}
|
||||
limit=Math.min(limit,cart.getMaxSpeed(level));
|
||||
}
|
||||
if(carts.isEmpty())continue;
|
||||
if(paused){pausedCarts.addAll(carts.keySet());carts.values().forEach(c->c.setDeltaMovement(Vec3.ZERO));continue;}
|
||||
double speed=Math.clamp(momentum/carts.size(),-limit,limit);
|
||||
// Player input drives the train as a unit. Averaging it with idle carts diluted
|
||||
// the tiny vanilla rider impulse; a dot product also erased side-on walking pushes.
|
||||
double speed=Math.clamp(!controls.isEmpty()?controlledMomentum/controls.size():momentum/carts.size(),-limit,limit);
|
||||
var corrections=new HashMap<UUID,Double>();
|
||||
for(var link:links)if(carts.containsKey(link.a()) && carts.containsKey(link.b())){
|
||||
var a=carts.get(link.a());var b=carts.get(link.b());double distance=a.position().distanceTo(b.position());
|
||||
@@ -121,13 +133,27 @@ public final class Trains {
|
||||
corrections.merge(link.a(),pull*direction,Double::sum);corrections.merge(link.b(),-pull*direction,Double::sum);
|
||||
}
|
||||
for(var pair:carts.entrySet()){
|
||||
var cart=pair.getValue();double value=Math.clamp(speed+corrections.getOrDefault(pair.getKey(),0.0),-limit,limit);
|
||||
// Followers take up slack; pulling back the driven cart would cancel its 0.001 rider impulse.
|
||||
var cart=pair.getValue();double value=Math.clamp(speed+(controls.contains(pair.getKey())?0:corrections.getOrDefault(pair.getKey(),0.0)),-limit,limit);
|
||||
var velocity=axes.get(pair.getKey()).scale(value/travelScale(cart));
|
||||
cart.setDeltaMovement(velocity.x,cart.getDeltaMovement().y,velocity.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static double travelScale(AbstractMinecart cart){return !AbstractMinecart.useExperimentalMovement(cart.level())&&cart.isVehicle()?.75:1;}
|
||||
private static double alignedSpeed(AbstractMinecart cart,Vec3 tangent){
|
||||
var movement=cart.getDeltaMovement();double along=movement.dot(tangent);
|
||||
if(Math.abs(along)<1e-9){
|
||||
var pos=cart.getCurrentBlockPosOrRailBelow();var state=cart.level().getBlockState(pos);
|
||||
if(state.getBlock() instanceof BaseRailBlock rail){
|
||||
var exits=AbstractMinecart.exits(rail.getRailDirection(state,cart.level(),pos,cart));
|
||||
var nativeAxis=new Vec3(exits.getSecond()).subtract(new Vec3(exits.getFirst())).horizontal();
|
||||
// Vanilla chooses the opposite default exit for a perpendicular input in the new engine.
|
||||
along=nativeAxis.dot(tangent)*(AbstractMinecart.useExperimentalMovement(cart.level())?-1:1);
|
||||
}
|
||||
}
|
||||
return Math.copySign(movement.horizontalDistance(),along);
|
||||
}
|
||||
@SubscribeEvent public static void post(ServerTickEvent.Post event){for(var level:event.getServer().getAllLevels())show(level);}
|
||||
public static void show(ServerLevel level){
|
||||
var keys=new HashSet<DisplayKey>();
|
||||
@@ -154,5 +180,5 @@ public final class Trains {
|
||||
for(var id:ids){var cart=cart(level,id);if(cart!=null){var v=CouplingGeometry.axis(cart).scale(speed*signs.getOrDefault(id,1)/travelScale(cart));cart.setDeltaMovement(v.x,cart.getDeltaMovement().y,v.z);}}
|
||||
}
|
||||
private static void discard(DisplayKey key){var display=DISPLAYS.remove(key);if(display!=null)display.discard();}
|
||||
@SubscribeEvent public static void stop(ServerStoppedEvent event){for(var key:new ArrayList<>(DISPLAYS.keySet()))discard(key);PAUSED.clear();}
|
||||
@SubscribeEvent public static void stop(ServerStoppedEvent event){for(var key:new ArrayList<>(DISPLAYS.keySet()))discard(key);PAUSED.clear();PLAYER_PUSHES.clear();}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user