Add server-only crossbow ammunition and copper rail speed controls
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package online.astradev.content;
|
||||
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import online.astradev.content.rail.Rails;
|
||||
import online.astradev.content.weapon.Ammunition;
|
||||
|
||||
@Mod(value = "astracontent", dist = Dist.DEDICATED_SERVER)
|
||||
public final class AstraContent {
|
||||
public AstraContent(IEventBus bus) {
|
||||
Defaults.install(FMLPaths.GAMEDIR.get());
|
||||
Rails.register(bus);
|
||||
NeoForge.EVENT_BUS.register(Rails.class);
|
||||
NeoForge.EVENT_BUS.register(Ammunition.class);
|
||||
NeoForge.EVENT_BUS.register(online.astradev.content.rail.RailCommands.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package online.astradev.content;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/** Install absent defaults before AstraPlus loads its catalog. Never overwrite administrator edits. */
|
||||
public final class Defaults {
|
||||
private Defaults() {}
|
||||
public static void install(Path root) {
|
||||
try (var index = Defaults.class.getResourceAsStream("/defaults/index.txt")) {
|
||||
if (index == null) throw new IllegalStateException("Missing content index");
|
||||
for (String name : new String(index.readAllBytes(), StandardCharsets.UTF_8).lines().toList()) {
|
||||
if (name.isBlank()) continue;
|
||||
Path target = root.toAbsolutePath().normalize().resolve("astraplus").resolve(name).normalize();
|
||||
if (!target.startsWith(root.toAbsolutePath().normalize().resolve("astraplus"))) throw new IllegalArgumentException(name);
|
||||
for (Path part = target; part != null; part = part.getParent())
|
||||
if (Files.isSymbolicLink(part)) throw new IllegalStateException("Symbolic link: " + part);
|
||||
if (Files.exists(target)) continue;
|
||||
Files.createDirectories(target.getParent());
|
||||
try (var stream = Defaults.class.getResourceAsStream("/defaults/" + name)) {
|
||||
if (stream == null) throw new IllegalStateException("Missing default: " + name);
|
||||
Files.copy(stream, target);
|
||||
}
|
||||
}
|
||||
} catch (java.io.IOException e) { throw new IllegalStateException("Cannot install AstraContent defaults", e); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.projectile.Projectile;
|
||||
import online.astradev.content.weapon.Ammunition;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(CrossbowItem.class)
|
||||
public abstract class CrossbowMixin {
|
||||
@Inject(method = {"getSupportedHeldProjectiles()Ljava/util/function/Predicate;", "getAllSupportedProjectiles()Ljava/util/function/Predicate;"}, at = @At("RETURN"), cancellable = true)
|
||||
private void astra$ammo(CallbackInfoReturnable<Predicate<ItemStack>> cir) { cir.setReturnValue(cir.getReturnValue().or(Ammunition::accepts)); }
|
||||
@Inject(method = "createProjectile", at = @At("HEAD"), cancellable = true)
|
||||
private void astra$create(Level level, LivingEntity owner, ItemStack weapon, ItemStack ammo, boolean critical, CallbackInfoReturnable<Projectile> cir) {
|
||||
if (Ammunition.accepts(ammo)) cir.setReturnValue(Ammunition.create(level, owner, ammo));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.*;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import online.astradev.content.rail.CartSpeed;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(NewMinecartBehavior.class)
|
||||
public abstract class ExperimentalCartMixin extends MinecartBehavior {
|
||||
protected ExperimentalCartMixin(AbstractMinecart cart){super(cart);}
|
||||
@Inject(method="calculateTrackSpeed",at=@At("RETURN"),cancellable=true)
|
||||
private void astra$exactSpeed(CallbackInfoReturnable<Vec3> cir) {
|
||||
if(!(level() instanceof ServerLevel level))return;
|
||||
double limit=((CartSpeed)minecart).astracontent$limit(level);
|
||||
var movement=cir.getReturnValue();
|
||||
if(limit>0 && movement.horizontalDistance()>limit)cir.setReturnValue(movement.scale(limit/movement.horizontalDistance()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package online.astradev.content.mixin;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.MinecartFurnace;
|
||||
import online.astradev.content.rail.CartSpeed;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
@Mixin(MinecartFurnace.class)
|
||||
public abstract class FurnaceCartMixin {
|
||||
@Inject(method="getMaxSpeed",at=@At("RETURN"),cancellable=true)
|
||||
private void astra$furnace(ServerLevel level,CallbackInfoReturnable<Double> cir) {
|
||||
double limit=((CartSpeed)this).astracontent$limit(level);if(limit>0)cir.setReturnValue(limit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.storage.*;
|
||||
import online.astradev.content.rail.RailSpeed;
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.*;
|
||||
|
||||
@Mixin(AbstractMinecart.class)
|
||||
public abstract class MinecartMixin implements online.astradev.content.rail.CartSpeed {
|
||||
@Unique private double astra$speed;
|
||||
@Inject(method="getMaxSpeed",at=@At("RETURN"),cancellable=true)
|
||||
private void astra$limit(ServerLevel level,CallbackInfoReturnable<Double> cir) {
|
||||
double limit=astracontent$limit(level);
|
||||
if(limit>0)cir.setReturnValue(limit);
|
||||
}
|
||||
@Override public double astracontent$limit(ServerLevel level) {
|
||||
var cart=(AbstractMinecart)(Object)this;
|
||||
astra$speed=RailSpeed.target(level,cart.getCurrentBlockPosOrRailBelow(),astra$speed);
|
||||
// Preserve existing experimental gamerules until this cart reaches a regulator.
|
||||
if(astra$speed==0) return 0;
|
||||
double limit=RailSpeed.safeLimit(cart,level,astra$speed/20);
|
||||
return limit*(cart.isInWater()?.5:1);
|
||||
}
|
||||
@Inject(method="addAdditionalSaveData",at=@At("RETURN"))
|
||||
private void astra$save(ValueOutput out,CallbackInfo ci) { if(astra$speed>0)out.putDouble("AstraContentSpeed",astra$speed); }
|
||||
@Inject(method="readAdditionalSaveData",at=@At("RETURN"))
|
||||
private void astra$read(ValueInput in,CallbackInfo ci) {
|
||||
double value=in.getDoubleOr("AstraContentSpeed",0); astra$speed=Double.isFinite(value) && value>0?Math.clamp(value,2,30):0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import net.minecraft.world.entity.projectile.EyeOfEnder;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import online.astradev.content.weapon.PayloadProjectile;
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(EyeOfEnder.class)
|
||||
public abstract class PayloadMixin {
|
||||
@Shadow private boolean surviveAfterDeath;
|
||||
@Inject(method = "signalTo", at = @At("RETURN"))
|
||||
private void astra$noDuplicate(Vec3 target, CallbackInfo ci) {
|
||||
if (((EyeOfEnder)(Object)this).entityTags().contains(PayloadProjectile.NO_EYE_DROP)) surviveAfterDeath = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package online.astradev.content.mixin;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.loot.LootParams;
|
||||
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
|
||||
import online.astradev.content.rail.Rails;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
|
||||
@Mixin(PoweredRailBlock.class)
|
||||
public abstract class RailBlockMixin extends BaseRailBlock {
|
||||
protected RailBlockMixin(boolean straight, Properties properties) { super(straight,properties); }
|
||||
@Override public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
|
||||
super.setPlacedBy(level,pos,state,placer,stack);
|
||||
if (state.is(Blocks.POWERED_RAIL) && level instanceof ServerLevel server) Rails.placed(server,pos,stack);
|
||||
}
|
||||
@Override protected List<ItemStack> getDrops(BlockState state, LootParams.Builder params) {
|
||||
var drops = super.getDrops(state,params); var origin = params.getOptionalParameter(LootContextParams.ORIGIN);
|
||||
if (!state.is(Blocks.POWERED_RAIL) || origin == null) return drops;
|
||||
var kind = Rails.loot(params.getLevel(),BlockPos.containing(origin));
|
||||
return kind == null ? drops : drops.stream().map(stack -> stack.is(asItem()) ? Rails.stack(kind,stack.getCount()) : stack).toList();
|
||||
}
|
||||
@Override protected ItemStack getCloneItemStack(LevelReader level, BlockPos pos, BlockState state, boolean includeData) {
|
||||
if (level instanceof ServerLevel server && state.is(Blocks.POWERED_RAIL)) {
|
||||
var kind=Rails.find(server,pos); if(kind!=null) return Rails.stack(kind,1);
|
||||
}
|
||||
return super.getCloneItemStack(level,pos,state,includeData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package online.astradev.content.mixin;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import online.astradev.content.rail.Rails;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
@Mixin(LevelChunk.class)
|
||||
public abstract class RailChunkMixin {
|
||||
@Inject(method="setBlockState",at=@At("RETURN"))
|
||||
private void astra$changed(BlockPos pos,BlockState state,int flags,CallbackInfoReturnable<BlockState> cir) {
|
||||
if (((LevelChunk)(Object)this).getLevel() instanceof ServerLevel level) Rails.changed(level,pos,cir.getReturnValue(),state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package online.astradev.content.rail;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
public interface CartSpeed {
|
||||
/** Blocks per tick, or zero until the cart encounters a powered speed regulator. */
|
||||
double astracontent$limit(ServerLevel level);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package online.astradev.content.rail;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
public final class RailCommands {
|
||||
private RailCommands() {}
|
||||
@SubscribeEvent public static void register(RegisterCommandsEvent event) {
|
||||
var give=Commands.literal("give");
|
||||
for(int i=0;i<8;i++) {
|
||||
var kind=RailKind.decode(i);
|
||||
give.then(Commands.literal(kind.id().getPath()).executes(ctx->{
|
||||
var player=ctx.getSource().getPlayerOrException();
|
||||
var stack=Rails.stack(kind,64);
|
||||
if(!player.getInventory().add(stack)) player.drop(stack,false);
|
||||
return 1;
|
||||
}));
|
||||
}
|
||||
event.getDispatcher().register(Commands.literal("astracontent").requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS)).then(give));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.Display;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.block.PoweredRailBlock;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.storage.ValueOutput;
|
||||
|
||||
final class RailDisplay extends Display.ItemDisplay {
|
||||
private String previous;
|
||||
RailDisplay(ServerLevel level, BlockPos pos) {
|
||||
super(EntityTypes.ITEM_DISPLAY,level);
|
||||
setPos(pos.getX()+.5,pos.getY()+.5,pos.getZ()+.5);
|
||||
setItemTransform(ItemDisplayContext.NONE); setNoGravity(true); setInvulnerable(true); setSilent(true);
|
||||
}
|
||||
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()));
|
||||
}
|
||||
@Override public boolean shouldBeSaved() { return false; }
|
||||
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.component.CustomData;
|
||||
|
||||
/** Vanilla item, vanilla components: native placement prediction without a client mod. */
|
||||
public final class RailItems {
|
||||
public static final String KEY="astracontent:rail";
|
||||
private RailItems() {}
|
||||
public static RailKind find(ItemStack stack) {
|
||||
if(!stack.is(Items.POWERED_RAIL)) return null;
|
||||
var data=stack.get(DataComponents.CUSTOM_DATA);if(data==null)return null;
|
||||
int value=data.copyTag().getIntOr(KEY,-1);
|
||||
return value>=0 && value<8?RailKind.decode(value):null;
|
||||
}
|
||||
public static ItemStack create(RailKind kind,int count) {
|
||||
var stack=new ItemStack(Items.POWERED_RAIL,count);
|
||||
var tag=new CompoundTag();tag.putInt(KEY,kind.code());stack.set(DataComponents.CUSTOM_DATA,CustomData.of(tag));
|
||||
stack.set(DataComponents.ITEM_MODEL,kind.id());
|
||||
stack.set(DataComponents.ITEM_NAME,Component.translatableWithFallback("item.astracontent."+kind.id().getPath(),name(kind)));
|
||||
return stack;
|
||||
}
|
||||
public static String name(RailKind kind) {
|
||||
return (kind.waxed()?"Вощёные: ":"")+new String[]{"Медные рельсы","Потемневшие медные рельсы","Состаренные медные рельсы","Окисленные медные рельсы"}[kind.age()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
public record RailKind(int age, boolean waxed) {
|
||||
public RailKind { if (age < 0 || age > 3) throw new IllegalArgumentException("Oxidation: " + age); }
|
||||
public int speed() { return 20 - 4 * age; }
|
||||
public int code() { return age + (waxed ? 4 : 0); }
|
||||
public static RailKind decode(int code) { return new RailKind(code & 3, (code & 4) != 0); }
|
||||
public Identifier id() {
|
||||
return Identifier.fromNamespaceAndPath("astracontent", (waxed ? "waxed_" : "")
|
||||
+ new String[]{"", "exposed_", "weathered_", "oxidized_"}[age] + "copper_rail");
|
||||
}
|
||||
public static RailKind fromId(Identifier id) {
|
||||
for (int code = 0; code < 8; code++) if (decode(code).id().equals(id)) return decode(code);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.level.block.WeatheringCopper;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
|
||||
/** Match copper's random-tick selection, age neighborhood and oxidation probability. */
|
||||
final class RailOxidation {
|
||||
private RailOxidation() {}
|
||||
static boolean advance(ServerLevel level,BlockPos pos,RailKind kind) {
|
||||
if(kind.waxed() || kind.age()==3 || !level.isPositionEntityTicking(pos))return false;
|
||||
int rate=level.getGameRules().get(GameRules.RANDOM_TICK_SPEED);
|
||||
double chance=1-Math.pow(1-.05688889/4096,rate);
|
||||
if(level.getRandom().nextDouble()>=chance)return false;
|
||||
int older=0,same=0;
|
||||
for(var other:BlockPos.withinManhattan(pos,4,4,4)) {
|
||||
int distance=other.distManhattan(pos);if(distance>4)break;if(distance==0 || !level.hasChunkAt(other))continue;
|
||||
int age=-1;
|
||||
var rail=Rails.find(level,other);
|
||||
if(rail!=null && !rail.waxed())age=rail.age();
|
||||
else if(level.getBlockState(other).getBlock() instanceof WeatheringCopper copper)age=copper.getAge().ordinal();
|
||||
if(age<0)continue;if(age<kind.age())return false;if(age>kind.age())older++;else same++;
|
||||
}
|
||||
double ratio=(older+1.0)/(older+same+1.0);
|
||||
return level.getRandom().nextDouble()<ratio*ratio*(kind.age()==0?.75:1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import java.util.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.vehicle.minecart.AbstractMinecart;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.block.state.properties.RailShape;
|
||||
|
||||
public final class RailSpeed {
|
||||
private RailSpeed() {}
|
||||
public static int signalSpeed(int signal) { return Math.clamp(signal,0,15)*2; }
|
||||
public static double target(ServerLevel level, BlockPos pos, double previous) {
|
||||
var state=level.getBlockState(pos);
|
||||
if (!state.is(Blocks.POWERED_RAIL) || !state.getValue(PoweredRailBlock.POWERED)) return previous;
|
||||
var kind=Rails.find(level,pos);
|
||||
return kind != null ? kind.speed() : Math.max(2,signalSpeed(signal(level,pos)));
|
||||
}
|
||||
/** Mirror the vanilla eight-rail power reach, preserving bends, slopes and highest input. */
|
||||
public static int signal(ServerLevel level, BlockPos origin) {
|
||||
record Step(BlockPos pos,int distance) {}
|
||||
var queue=new ArrayDeque<Step>(); var seen=new HashSet<BlockPos>(); queue.add(new Step(origin,0));
|
||||
int best=0;
|
||||
while(!queue.isEmpty()) {
|
||||
var step=queue.removeFirst(); if(!seen.add(step.pos) || !level.hasChunkAt(step.pos)) continue;
|
||||
var state=level.getBlockState(step.pos);
|
||||
if (!state.is(Blocks.POWERED_RAIL)) continue;
|
||||
best=Math.max(best,level.getBestNeighborSignal(step.pos)); if(best==15) return best;
|
||||
if(step.distance==8) continue;
|
||||
var shape=state.getValue(PoweredRailBlock.SHAPE);
|
||||
var exits=AbstractMinecart.exits(shape);
|
||||
for(var exit:List.of(exits.getFirst(),exits.getSecond())) {
|
||||
var adjacent=step.pos.offset(exit.getX(),shape.isSlope()?exit.getY()+1:0,exit.getZ());
|
||||
for(var candidate:List.of(adjacent,adjacent.below())) {
|
||||
if(!level.hasChunkAt(candidate)) continue;
|
||||
var other=level.getBlockState(candidate);
|
||||
if(other.is(Blocks.POWERED_RAIL) && connected(step.pos,shape,candidate,other.getValue(PoweredRailBlock.SHAPE)))
|
||||
queue.add(new Step(candidate,step.distance+1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
private static boolean connected(BlockPos a,RailShape sa,BlockPos b,RailShape sb) {
|
||||
var ea=AbstractMinecart.exits(sa); var eb=AbstractMinecart.exits(sb);
|
||||
for(var x:List.of(ea.getFirst(),ea.getSecond())) for(var y:List.of(eb.getFirst(),eb.getSecond()))
|
||||
if(a.getX()+x.getX()==b.getX() && a.getZ()+x.getZ()==b.getZ()
|
||||
&& b.getX()+y.getX()==a.getX() && b.getZ()+y.getZ()==a.getZ()
|
||||
&& a.getY()+(sa.isSlope()?x.getY()+1:0)==b.getY()+(sb.isSlope()?y.getY()+1:0)) return true;
|
||||
return false;
|
||||
}
|
||||
/** Old movement needs vanilla speed when approaching bends, slopes or the end of a track. */
|
||||
public static double safeLimit(AbstractMinecart cart,ServerLevel level,double limit) {
|
||||
if(AbstractMinecart.useExperimentalMovement(level) || limit<=.4) return limit;
|
||||
var pos=cart.getCurrentBlockPosOrRailBelow(); var movement=cart.getDeltaMovement();
|
||||
int dx=(int)Math.signum(movement.x), dz=(int)Math.signum(movement.z);
|
||||
for(int i=0;i<=2;i++) {
|
||||
var check=pos.offset(dx*i,0,dz*i);
|
||||
if(!level.hasChunkAt(check)) return .4;
|
||||
BlockState state=level.getBlockState(check);
|
||||
if(!(state.getBlock() instanceof BaseRailBlock rail)) return .4;
|
||||
RailShape shape=rail.getRailDirection(state,level,check,cart);
|
||||
if(shape!=RailShape.NORTH_SOUTH && shape!=RailShape.EAST_WEST) return .4;
|
||||
if (i>0 && (state.is(Blocks.DETECTOR_RAIL) || state.is(Blocks.ACTIVATOR_RAIL)
|
||||
|| state.is(Blocks.POWERED_RAIL) && !state.getValue(PoweredRailBlock.POWERED))) return .4;
|
||||
// Never jump over a single slower regulator.
|
||||
if (i>0) limit=Math.min(limit,target(level,check,limit*20)/20);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package online.astradev.content.rail;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.neoforged.bus.api.*;
|
||||
import net.neoforged.neoforge.attachment.AttachmentType;
|
||||
import net.neoforged.neoforge.registries.*;
|
||||
import net.neoforged.neoforge.event.level.ChunkEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
|
||||
/** Native powered rails own placement, shape, redstone, collision and destruction. */
|
||||
public final class Rails {
|
||||
private static final DeferredRegister<AttachmentType<?>> TYPES = DeferredRegister.create(NeoForgeRegistries.Keys.ATTACHMENT_TYPES, "astracontent");
|
||||
public static final Supplier<AttachmentType<Map<Long, Integer>>> DATA = TYPES.register("copper_rails", () ->
|
||||
AttachmentType.<Map<Long,Integer>>builder(() -> new HashMap<>()).serialize(
|
||||
Codec.unboundedMap(Codec.STRING.xmap(Long::parseLong, String::valueOf), Codec.intRange(0,7))
|
||||
.xmap(map -> (Map<Long,Integer>)new HashMap<>(map), map -> map).fieldOf("rails"), map -> !map.isEmpty()).build());
|
||||
private record Position(ServerLevel level, BlockPos pos) {}
|
||||
private record Removed(RailKind kind, long tick) {}
|
||||
private static final Map<Position,RailDisplay> ACTIVE = new HashMap<>();
|
||||
private static final Map<Position,Removed> REMOVED = new HashMap<>();
|
||||
private Rails() {}
|
||||
public static void register(IEventBus bus) { TYPES.register(bus); }
|
||||
public static RailKind find(ServerLevel level, BlockPos pos) {
|
||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4, pos.getZ() >> 4);
|
||||
if (chunk == null || !chunk.hasData(DATA)) return null;
|
||||
Integer code = chunk.getData(DATA).get(pos.asLong());
|
||||
return code == null ? null : RailKind.decode(code);
|
||||
}
|
||||
public static RailKind loot(ServerLevel level, BlockPos pos) {
|
||||
var kind = find(level,pos);
|
||||
var removed = REMOVED.get(new Position(level,pos));
|
||||
return kind != null ? kind : removed != null && removed.tick == level.getGameTime() ? removed.kind : null;
|
||||
}
|
||||
public static ItemStack stack(RailKind kind, int count) { return RailItems.create(kind,count); }
|
||||
public static void placed(ServerLevel level, BlockPos pos, ItemStack stack) {
|
||||
clear(level,pos); REMOVED.remove(new Position(level,pos));
|
||||
var kind = RailItems.find(stack);
|
||||
if (kind != null) put(level,pos,kind);
|
||||
}
|
||||
public static void put(ServerLevel level, BlockPos pos, RailKind kind) {
|
||||
var chunk = level.getChunkAt(pos); chunk.getData(DATA).put(pos.asLong(),kind.code()); chunk.markUnsaved();
|
||||
ACTIVE.putIfAbsent(new Position(level,pos.immutable()), null);
|
||||
}
|
||||
public static void changed(ServerLevel level, BlockPos pos, BlockState before, BlockState after) {
|
||||
if (before == null || !before.is(Blocks.POWERED_RAIL) || after.is(Blocks.POWERED_RAIL)) return;
|
||||
var kind = find(level,pos);
|
||||
if (kind != null) { REMOVED.put(new Position(level,pos.immutable()),new Removed(kind,level.getGameTime())); clear(level,pos); }
|
||||
}
|
||||
private static void clear(ServerLevel level, BlockPos pos) {
|
||||
var chunk = level.getChunkSource().getChunkNow(pos.getX() >> 4,pos.getZ() >> 4);
|
||||
if (chunk != null && chunk.hasData(DATA) && chunk.getData(DATA).remove(pos.asLong()) != null) chunk.markUnsaved();
|
||||
var display = ACTIVE.remove(new Position(level,pos)); if (display != null) display.discard();
|
||||
}
|
||||
@SubscribeEvent public static void load(ChunkEvent.Load event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level) || !(event.getChunk() instanceof LevelChunk chunk)) return;
|
||||
level.getServer().execute(() -> {
|
||||
if (level.getChunkSource().getChunkNow(chunk.getPos().x(),chunk.getPos().z()) != chunk || !chunk.hasData(DATA)) return;
|
||||
chunk.getData(DATA).forEach((packed,code) -> {
|
||||
var pos = BlockPos.of(packed);
|
||||
if (pos.getX() >> 4 == chunk.getPos().x() && pos.getZ() >> 4 == chunk.getPos().z())
|
||||
ACTIVE.putIfAbsent(new Position(level,pos),null);
|
||||
});
|
||||
});
|
||||
}
|
||||
@SubscribeEvent public static void unload(ChunkEvent.Unload event) {
|
||||
for (var key : new ArrayList<>(ACTIVE.keySet())) if (key.level == event.getLevel()
|
||||
&& key.pos.getX() >> 4 == event.getChunk().getPos().x() && key.pos.getZ() >> 4 == event.getChunk().getPos().z()) {
|
||||
var display = ACTIVE.remove(key); if (display != null) display.discard();
|
||||
}
|
||||
}
|
||||
@SubscribeEvent public static void stopped(ServerStoppedEvent event) {
|
||||
ACTIVE.values().stream().filter(Objects::nonNull).forEach(RailDisplay::discard); ACTIVE.clear(); REMOVED.clear();
|
||||
}
|
||||
@SubscribeEvent public static void tick(ServerTickEvent.Post event) {
|
||||
for (var key : new ArrayList<>(ACTIVE.keySet())) {
|
||||
var state = key.level.getBlockState(key.pos); var kind = find(key.level,key.pos);
|
||||
if (kind == null || !state.is(Blocks.POWERED_RAIL)) { clear(key.level,key.pos); continue; }
|
||||
if (RailOxidation.advance(key.level,key.pos,kind)) {
|
||||
kind = new RailKind(kind.age()+1,false); put(key.level,key.pos,kind);
|
||||
}
|
||||
var display = ACTIVE.get(key);
|
||||
if (display == null || display.isRemoved()) {
|
||||
display = new RailDisplay(key.level,key.pos); display.update(kind,state);
|
||||
if (key.level.addFreshEntity(display)) ACTIVE.put(key,display);
|
||||
} else display.update(kind,state);
|
||||
}
|
||||
REMOVED.entrySet().removeIf(entry -> entry.getValue().tick < entry.getKey().level.getGameTime());
|
||||
}
|
||||
@SubscribeEvent public static void use(PlayerInteractEvent.RightClickBlock event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level)) return;
|
||||
var kind = find(level,event.getPos()); if (kind == null) return;
|
||||
var item = event.getItemStack(); RailKind next;
|
||||
int effect;
|
||||
if (item.is(Items.HONEYCOMB) && !kind.waxed()) { next = new RailKind(kind.age(),true); effect=3003; }
|
||||
else if (item.getItem() instanceof AxeItem && (kind.waxed() || kind.age()>0)) {
|
||||
next = kind.waxed() ? new RailKind(kind.age(),false) : new RailKind(kind.age()-1,false); effect=kind.waxed()?3004:3005;
|
||||
} else return;
|
||||
if (!event.getEntity().mayBuild()) return;
|
||||
put(level,event.getPos(),next); level.levelEvent(null,effect,event.getPos(),0);
|
||||
if (item.is(Items.HONEYCOMB)) item.consume(1,event.getEntity());
|
||||
else item.hurtAndBreak(1,event.getEntity(),event.getHand().asEquipmentSlot());
|
||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package online.astradev.content.weapon;
|
||||
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.sounds.*;
|
||||
import net.minecraft.stats.Stats;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.projectile.Projectile;
|
||||
import net.minecraft.world.entity.projectile.hurtingprojectile.SmallFireball;
|
||||
import net.minecraft.world.entity.projectile.throwableitemprojectile.*;
|
||||
import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.WindCharge;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
|
||||
public final class Ammunition {
|
||||
private Ammunition() {}
|
||||
public static boolean accepts(ItemStack stack) {
|
||||
return stack.is(Items.ENDER_PEARL) || stack.is(Items.FIRE_CHARGE) || stack.is(Items.ENDER_EYE)
|
||||
|| stack.getItem() instanceof EggItem || stack.is(Items.SNOWBALL) || stack.is(Items.WIND_CHARGE)
|
||||
|| stack.is(Items.EXPERIENCE_BOTTLE) || stack.is(Items.TNT);
|
||||
}
|
||||
public static Projectile create(Level level, LivingEntity owner, ItemStack ammo) {
|
||||
if (ammo.is(Items.ENDER_PEARL)) return new ThrownEnderpearl(level, owner, ammo);
|
||||
if (ammo.getItem() instanceof EggItem) return new ThrownEgg(level, owner, ammo);
|
||||
if (ammo.is(Items.SNOWBALL)) return new Snowball(level, owner, ammo);
|
||||
if (ammo.is(Items.EXPERIENCE_BOTTLE)) return new ThrownExperienceBottle(level, owner, ammo);
|
||||
if (ammo.is(Items.FIRE_CHARGE)) {
|
||||
var fire = new SmallFireball(level, owner, owner.getLookAngle());
|
||||
fire.setPos(owner.getX(), owner.getEyeY() - .15, owner.getZ()); fire.setItem(ammo); return fire;
|
||||
}
|
||||
if (ammo.is(Items.WIND_CHARGE)) {
|
||||
var wind = new WindCharge(level, owner.getX(), owner.getEyeY() - .15, owner.getZ(), owner.getLookAngle());
|
||||
wind.setOwner(owner); return wind;
|
||||
}
|
||||
if (ammo.is(Items.TNT) || ammo.is(Items.ENDER_EYE)) return new PayloadProjectile(level, owner, ammo);
|
||||
return null;
|
||||
}
|
||||
@SubscribeEvent public static void fireCharge(PlayerInteractEvent.RightClickItem event) {
|
||||
if (!(event.getLevel() instanceof ServerLevel level) || !event.getItemStack().is(Items.FIRE_CHARGE)) return;
|
||||
var player = event.getEntity(); var stack = event.getItemStack();
|
||||
if (player.getCooldowns().isOnCooldown(stack)) return;
|
||||
var fire = create(level, player, stack);
|
||||
Projectile.spawnProjectile(fire, level, stack, shot -> shot.shootFromRotation(player, player.getXRot(), player.getYRot(), 0, 1.5f, 1));
|
||||
level.playSound(null, player.blockPosition(), SoundEvents.FIRECHARGE_USE, SoundSource.PLAYERS, 1, 1);
|
||||
player.getCooldowns().addCooldown(stack, 10);
|
||||
player.awardStat(Stats.ITEM_USED.get(stack.getItem()));
|
||||
stack.consume(1, player);
|
||||
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package online.astradev.content.weapon;
|
||||
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.tags.StructureTags;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.item.PrimedTnt;
|
||||
import net.minecraft.world.entity.projectile.EyeOfEnder;
|
||||
import net.minecraft.world.entity.projectile.throwableitemprojectile.Snowball;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/** One-tick shooting adapter; the payload itself is a vanilla entity understood by every client. */
|
||||
public final class PayloadProjectile extends Snowball {
|
||||
public static final String NO_EYE_DROP = "astracontent:no_eye_drop";
|
||||
public PayloadProjectile(Level level, LivingEntity owner, ItemStack stack) { super(level, owner, stack); }
|
||||
@Override public void tick() {
|
||||
if (!(level() instanceof ServerLevel level)) return;
|
||||
if (getItem().is(Items.TNT)) {
|
||||
var tnt = new PrimedTnt(level, getX(), getY(), getZ(), getOwner() instanceof LivingEntity living ? living : null);
|
||||
tnt.setDeltaMovement(getDeltaMovement()); level.addFreshEntity(tnt);
|
||||
} else {
|
||||
var target = level.findNearestMapStructure(StructureTags.EYE_OF_ENDER_LOCATED, blockPosition(), 100, false);
|
||||
if (target != null) {
|
||||
var eye = new EyeOfEnder(level, getX(), getY(), getZ());
|
||||
eye.setItem(getItem());
|
||||
if (getItem().has(DataComponents.INTANGIBLE_PROJECTILE)) eye.addTag(NO_EYE_DROP);
|
||||
eye.signalTo(Vec3.atLowerCornerOf(target)); eye.setDeltaMovement(getDeltaMovement()); level.addFreshEntity(eye);
|
||||
} else if (!getItem().has(DataComponents.INTANGIBLE_PROJECTILE)) spawnAtLocation(level, getItem().copyWithCount(1));
|
||||
}
|
||||
discard();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user