diff --git a/src/main/java/dev/dubhe/anvilcraft/AnvilCraft.java b/src/main/java/dev/dubhe/anvilcraft/AnvilCraft.java index 78697e0d67..713e53e0ff 100644 --- a/src/main/java/dev/dubhe/anvilcraft/AnvilCraft.java +++ b/src/main/java/dev/dubhe/anvilcraft/AnvilCraft.java @@ -49,6 +49,7 @@ import dev.dubhe.anvilcraft.init.recipe.ModRecipeTypes; import dev.dubhe.anvilcraft.init.recipe.ModResultModifierTypes; import dev.dubhe.anvilcraft.init.storage.ModCategoryTypes; +import dev.dubhe.anvilcraft.item.utility.DiskItem; import dev.dubhe.anvilcraft.mixin.invoker.BaseMappedRegistryInvoker; import lombok.Getter; import net.minecraft.core.registries.BuiltInRegistries; @@ -65,6 +66,7 @@ import net.neoforged.neoforge.event.RegisterCommandsEvent; import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; import net.neoforged.neoforge.network.registration.PayloadRegistrar; +import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -72,19 +74,19 @@ public class AnvilCraft { public static final String MOD_ID = "anvilcraft"; public static final String MOD_NAME = "AnvilCraft"; - public static final Logger LOGGER = LoggerFactory.getLogger(MOD_NAME); + public static final Logger LOGGER = LoggerFactory.getLogger(AnvilCraft.MOD_NAME); public static final Gson GSON = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); - public static IEventBus MOD_BUS = null; + public static @Nullable IEventBus MOD_BUS = null; public static final AnvilCraftServerConfig CONFIG = ConfigManager.register(AnvilCraft.MOD_ID, AnvilCraftServerConfig::new); public static final AnvilCraftClientConfig CLIENT_CONFIG = ConfigManager.register(AnvilCraft.MOD_ID, AnvilCraftClientConfig::new); @Getter private static final IntegrationManager INTEGRATION_MANAGER = new IntegrationManager(AnvilCraft.MOD_ID); - public static final Registrum REGISTRUM = Registrum.create(MOD_ID).defaultCreativeTab((ResourceKey) null); + public static final Registrum REGISTRUM = Registrum.create(AnvilCraft.MOD_ID).defaultCreativeTab((ResourceKey) null); public AnvilCraft(IEventBus modEventBus, ModContainer modContainer) { - MOD_BUS = modEventBus; + AnvilCraft.MOD_BUS = modEventBus; NeoForgeMod.enableMilkFluid(); ModAttachments.register(modEventBus); ModItemGroups.register(modEventBus); @@ -123,16 +125,16 @@ public AnvilCraft(IEventBus modEventBus, ModContainer modContainer) { // datagen AnvilCraftDatagen.init(); - registerEvents(modEventBus); + AnvilCraft.registerEvents(modEventBus); StartupNotificationManager.addModMessage("[AnvilCraft] Loading Integrations"); IntegrationHook.setModEventBus(modEventBus); IntegrationHook.setModContainer(modContainer); - INTEGRATION_MANAGER.compileContent(); - INTEGRATION_MANAGER.loadAllIntegrations(); + AnvilCraft.INTEGRATION_MANAGER.compileContent(); + AnvilCraft.INTEGRATION_MANAGER.loadAllIntegrations(); StartupNotificationManager.addModMessage("[AnvilCraft] Ciallo~"); AnvilCraftDfu.constructAndOptimize(); - LOGGER.info("Ciallo~(∠・ω< )⌒★"); - LOGGER.info("let's 0721"); + AnvilCraft.LOGGER.info("Ciallo~(∠・ω< )⌒★"); + AnvilCraft.LOGGER.info("let's 0721"); ModRecipeInits.init(modEventBus); @@ -142,7 +144,7 @@ public AnvilCraft(IEventBus modEventBus, ModContainer modContainer) { private static void registerEvents(IEventBus eventBus) { NeoForge.EVENT_BUS.addListener(AnvilCraft::registerCommand); - NeoForge.EVENT_BUS.addListener(dev.dubhe.anvilcraft.item.utility.DiskItem::onBlockPlaced); + NeoForge.EVENT_BUS.addListener(DiskItem::onBlockPlaced); eventBus.addListener(AnvilCraft::registerPayload); eventBus.addListener(AnvilCraft::loadComplete); @@ -151,15 +153,15 @@ private static void registerEvents(IEventBus eventBus) { } public static Identifier of(String path) { - return Identifier.fromNamespaceAndPath(MOD_ID, path); + return Identifier.fromNamespaceAndPath(AnvilCraft.MOD_ID, path); } public static Identifier advancement(String path) { - return of("anvilcraft/" + path); + return AnvilCraft.of("anvilcraft/" + path); } public static String recipe(String path) { - return MOD_ID + ':' + path; + return AnvilCraft.MOD_ID + ':' + path; } public static void registerCommand(RegisterCommandsEvent event) { @@ -175,13 +177,13 @@ public static void loadComplete(FMLLoadCompleteEvent event) { event.enqueueWork(() -> { ModDispenserBehavior.register(); if (Util.isLoaded("apothic_enchanting")) { - LOGGER.info( + AnvilCraft.LOGGER.info( "Apothic Enchanting found. Set royalAnvilBeyondMaxLevel, " + "emberAnvilBeyondMaxLevel and transcendenceAnvilBeyondMaxLevel to true." ); - CONFIG.royalAnvilBeyondMaxLevel = true; - CONFIG.emberAnvilBeyondMaxLevel = true; - CONFIG.transcendenceAnvilBeyondMaxLevel = true; + AnvilCraft.CONFIG.royalAnvilBeyondMaxLevel = true; + AnvilCraft.CONFIG.emberAnvilBeyondMaxLevel = true; + AnvilCraft.CONFIG.transcendenceAnvilBeyondMaxLevel = true; } Util.cast(BuiltInRegistries.DATA_COMPONENT_PREDICATE_TYPE).invokeSetSync(true); }); diff --git a/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/AnvilHammerHurtEntityTrigger.java b/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/AnvilHammerHurtEntityTrigger.java index fc71190493..1b6e58f676 100644 --- a/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/AnvilHammerHurtEntityTrigger.java +++ b/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/AnvilHammerHurtEntityTrigger.java @@ -40,7 +40,7 @@ public static Criterion hurtEntity(float damage) { } public boolean matches(Float damage) { - if (damage().isPresent()) { + if (this.damage().isPresent()) { return damage >= this.damage.get(); } else { return true; diff --git a/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/DevourerDevourTrigger.java b/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/DevourerDevourTrigger.java index 6a71d68738..54e0229ae6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/DevourerDevourTrigger.java +++ b/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/DevourerDevourTrigger.java @@ -29,7 +29,7 @@ public record TriggerInstance(Optional player, Optional devourBlock(Block block) { - return devourBlock(BlockPredicate.Builder.block().of(block)); + return TriggerInstance.devourBlock(BlockPredicate.Builder.block().of(block)); } public static Criterion devourBlock(BlockPredicate.Builder block) { diff --git a/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/PlacerPlaceTrigger.java b/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/PlacerPlaceTrigger.java index 7a166f249c..31cfd01dc1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/PlacerPlaceTrigger.java +++ b/src/main/java/dev/dubhe/anvilcraft/advancements/criterion/PlacerPlaceTrigger.java @@ -31,7 +31,7 @@ public record TriggerInstance( ).apply(instance, TriggerInstance::new)); public static Criterion placeBlock(Block block) { - return placeBlock(BlockPredicate.Builder.block().of(block)); + return TriggerInstance.placeBlock(BlockPredicate.Builder.block().of(block)); } public static Criterion placeBlock(BlockPredicate.Builder block) { diff --git a/src/main/java/dev/dubhe/anvilcraft/anvil/BeaconConversionBehavior.java b/src/main/java/dev/dubhe/anvilcraft/anvil/BeaconConversionBehavior.java index b26166bb61..ddc14a8997 100644 --- a/src/main/java/dev/dubhe/anvilcraft/anvil/BeaconConversionBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/anvil/BeaconConversionBehavior.java @@ -20,10 +20,10 @@ public class BeaconConversionBehavior implements IAnvilBehavior { private static final Int2DoubleOpenHashMap map = new Int2DoubleOpenHashMap() { { - put(1, 0.02F); - put(2, 0.05F); - put(3, 0.2F); - put(4, 1F); + this.put(1, 0.02F); + this.put(2, 0.05F); + this.put(3, 0.2F); + this.put(4, 1F); } }; @@ -50,7 +50,7 @@ public boolean handle(ServerLevel level, BlockPos hitBlockPos, BlockState hitBlo itemEntity.setItem(stack); for (int i = 1; i <= 4; i++) { if (beaconLevel == i) { - if (level.getRandom().nextDouble() < map.get(i)) { + if (level.getRandom().nextDouble() < BeaconConversionBehavior.map.get(i)) { level.setBlockAndUpdate(hitBlockPos, ModBlocks.CORRUPTED_BEACON.getDefaultState()); return true; } diff --git a/src/main/java/dev/dubhe/anvilcraft/anvil/HitSpawnerBehavior.java b/src/main/java/dev/dubhe/anvilcraft/anvil/HitSpawnerBehavior.java index 4f889426b1..36e21be564 100644 --- a/src/main/java/dev/dubhe/anvilcraft/anvil/HitSpawnerBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/anvil/HitSpawnerBehavior.java @@ -67,7 +67,7 @@ private void spawnEntities( BaseSpawnerAccessor accessor ) { for (int c = 0; c < accessor.getSpawnCount(); c++) { - try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(this::toString, log)) { + try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(this::toString, HitSpawnerBehavior.log)) { ValueInput input = TagValueInput.create(reporter, level.registryAccess(), spawnData.getEntityToSpawn()); Optional> entityType = EntityType.by(input); if (entityType.isEmpty()) return; diff --git a/src/main/java/dev/dubhe/anvilcraft/anvil/TimeWarpPlayerBehavior.java b/src/main/java/dev/dubhe/anvilcraft/anvil/TimeWarpPlayerBehavior.java index f27c7c0c80..37e4490b33 100644 --- a/src/main/java/dev/dubhe/anvilcraft/anvil/TimeWarpPlayerBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/anvil/TimeWarpPlayerBehavior.java @@ -6,6 +6,7 @@ import dev.dubhe.anvilcraft.init.block.ModBlocks; import dev.dubhe.anvilcraft.init.entity.ModDamageTypes; import dev.dubhe.anvilcraft.util.CauldronUtil; +import dev.dubhe.anvilcraft.util.EntityUtil; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; @@ -25,8 +26,7 @@ public boolean handle(ServerLevel level, BlockPos hitBlockPos, BlockState hitBlo ); if (players.isEmpty()) return false; for (ServerPlayer player : players) { - // noinspection deprecation - player.hurtOrSimulate(ModDamageTypes.lostInTime(level), Float.MAX_VALUE); + EntityUtil.hurtOrSimulate(player, ModDamageTypes.lostInTime(level), Float.MAX_VALUE); } return true; } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/BlockPlaceAssist.java b/src/main/java/dev/dubhe/anvilcraft/api/BlockPlaceAssist.java index 7c6d750c17..f25ae7d133 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/BlockPlaceAssist.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/BlockPlaceAssist.java @@ -53,7 +53,7 @@ public static InteractionResult tryPlace( if (player.isShiftKeyDown() || !player.mayBuild()) return InteractionResult.PASS; ItemStack itemInHand = player.getItemInHand(hand); if (itemInHand.is(blockItem)) { - for (Direction direction : orderDirectionByDistance( + for (Direction direction : BlockPlaceAssist.orderDirectionByDistance( pos, hit.getLocation(), dir -> dir.getAxis() == state.getValue(propertyDef) diff --git a/src/main/java/dev/dubhe/anvilcraft/api/RipeningManager.java b/src/main/java/dev/dubhe/anvilcraft/api/RipeningManager.java index 3fb4fe3a09..49caf2ca05 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/RipeningManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/RipeningManager.java @@ -26,7 +26,7 @@ public class RipeningManager { /// 获取或新建一个当前维度催熟实例。 public static RipeningManager from(Level level) { - return INSTANCES.computeIfAbsent(level, RipeningManager::new); + return RipeningManager.INSTANCES.computeIfAbsent(level, RipeningManager::new); } public RipeningManager(Level level) { diff --git a/src/main/java/dev/dubhe/anvilcraft/api/SpawningManager.java b/src/main/java/dev/dubhe/anvilcraft/api/SpawningManager.java index 9c0ed8f0ef..20cedbbdd9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/SpawningManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/SpawningManager.java @@ -63,7 +63,7 @@ public class SpawningManager { /// @return 与指定世界关联的 SpawningManager 实例 /// @see Map#computeIfAbsent(Object, java.util.function.Function) public static SpawningManager getInstance(Level level) { - return INSTANCES.computeIfAbsent(level, SpawningManager::new); + return SpawningManager.INSTANCES.computeIfAbsent(level, SpawningManager::new); } private SpawningManager(Level level) { @@ -169,10 +169,10 @@ private static void blockEntitySummon(MobSpawnEvent.PositionCheck event) { } Entity entity = event.getEntity(); Level level = entity.level(); - SpawningManager spawningManager = getInstance(level); + SpawningManager spawningManager = SpawningManager.getInstance(level); - if (!ignoreSummonMob(level, event, spawningManager.animalLightBlockSet, true)) { - ignoreSummonMob(level, event, spawningManager.nonAnimalLightBlockSet, false); + if (!SpawningManager.ignoreSummonMob(level, event, spawningManager.animalLightBlockSet, true)) { + SpawningManager.ignoreSummonMob(level, event, spawningManager.nonAnimalLightBlockSet, false); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/amulet/AmuletManager.java b/src/main/java/dev/dubhe/anvilcraft/api/amulet/AmuletManager.java index bcf3c53c96..05f782b11a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/amulet/AmuletManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/amulet/AmuletManager.java @@ -28,10 +28,13 @@ public class AmuletManager { private static @Nullable SoftReference INSTANCE; public static AmuletManager get(HolderLookup.Provider registries) { - if (AmuletManager.INSTANCE == null || AmuletManager.INSTANCE.get() == null) { - AmuletManager.INSTANCE = new SoftReference<>(new AmuletManager(AmuletManager.extractDefinitions(registries))); + SoftReference reference = AmuletManager.INSTANCE; + AmuletManager manager = reference == null ? null : reference.get(); + if (manager == null) { + manager = new AmuletManager(AmuletManager.extractDefinitions(registries)); + AmuletManager.INSTANCE = new SoftReference<>(manager); } - return AmuletManager.INSTANCE.get(); + return manager; } public static List> extractDefinitions(HolderLookup.Provider registries) { @@ -144,7 +147,10 @@ public static int getStoredRaffleProbability(Player player, Holder amulets = this.getAmuletsFromInventory(player); - return CollectionUtil.anyMatch(amulets, stack -> stack.get(ModComponents.AMULET).canActAs(amulet)); + return CollectionUtil.anyMatch( + amulets, + stack -> stack.getOrDefault(ModComponents.AMULET, DoNothingAmulet.INSTANCE).canActAs(amulet) + ); } public boolean hasAmuletInInventory(Player player, Holder def) { @@ -169,12 +175,14 @@ public void inventoryTick(ServerPlayer player) { } List now = this.getAmuletsFromInventory(player); for (ItemStack stack : now) { - IAmulet amulet = stack.get(ModComponents.AMULET); - all.removeIf(other -> amulet.canActAs(other.get(ModComponents.AMULET))); - stack.get(ModComponents.AMULET).inventoryTick(player, stack, true); + IAmulet amulet = stack.getOrDefault(ModComponents.AMULET, DoNothingAmulet.INSTANCE); + all.removeIf(other -> amulet.canActAs( + other.getOrDefault(ModComponents.AMULET, DoNothingAmulet.INSTANCE) + )); + amulet.inventoryTick(player, stack, true); } for (ItemStack stack : all) { - IAmulet amulet = stack.get(ModComponents.AMULET); + IAmulet amulet = stack.getOrDefault(ModComponents.AMULET, DoNothingAmulet.INSTANCE); if (amulet instanceof WrappedOthersAmulet) return; amulet.inventoryTick(player, stack, false); } @@ -183,7 +191,7 @@ public void inventoryTick(ServerPlayer player) { public boolean shouldImmune(ServerPlayer player, DamageSource source) { return CollectionUtil.anyMatch( this.getAmuletsFromInventory(player), - stack -> stack.get(ModComponents.AMULET).shouldImmune(player, source) + stack -> stack.getOrDefault(ModComponents.AMULET, DoNothingAmulet.INSTANCE).shouldImmune(player, source) ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/amulet/def/IAmuletDefinition.java b/src/main/java/dev/dubhe/anvilcraft/api/amulet/def/IAmuletDefinition.java index 9e4acb9bd9..75f7b011e5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/amulet/def/IAmuletDefinition.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/amulet/def/IAmuletDefinition.java @@ -16,7 +16,7 @@ public interface IAmuletDefinition { .byNameCodec() .dispatch(IAmuletDefinition::getType, Type::codec); Codec> CODEC = RegistryFileCodec.create(ModRegistryKeys.AMULET_DEF, IAmuletDefinition.DIRECT_CODEC); - Codec HOLDER_HELPER_CODEC = CODEC.xmap( + Codec HOLDER_HELPER_CODEC = IAmuletDefinition.CODEC.xmap( HolderHolder::new, value -> value instanceof HolderHolder(Holder def) ? def : Holder.direct(value) ); diff --git a/src/main/java/dev/dubhe/anvilcraft/api/anvil/IAnvilBehavior.java b/src/main/java/dev/dubhe/anvilcraft/api/anvil/IAnvilBehavior.java index fd80f70688..ccb1527067 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/anvil/IAnvilBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/anvil/IAnvilBehavior.java @@ -31,17 +31,17 @@ default int priority() { } static void registerBehavior(Block matchingBlock, IAnvilBehavior behavior) { - BEHAVIORS.put(it -> it.is(matchingBlock), behavior); + IAnvilBehavior.BEHAVIORS.put(it -> it.is(matchingBlock), behavior); } static void registerBehavior(Predicate pred, IAnvilBehavior behavior) { - BEHAVIORS.put(pred, behavior); + IAnvilBehavior.BEHAVIORS.put(pred, behavior); } static @Unmodifiable List findMatching(BlockState state) { - return BEHAVIORS.keySet().stream() + return IAnvilBehavior.BEHAVIORS.keySet().stream() .filter(it -> it.test(state)) - .map(BEHAVIORS::get) + .map(IAnvilBehavior.BEHAVIORS::get) .toList(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/chargecollector/ChargeCollectorManager.java b/src/main/java/dev/dubhe/anvilcraft/api/chargecollector/ChargeCollectorManager.java index e1ff1a65b3..c7b5bdb0b8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/chargecollector/ChargeCollectorManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/chargecollector/ChargeCollectorManager.java @@ -6,6 +6,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import org.joml.Vector3f; +import org.jspecify.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; @@ -29,10 +30,10 @@ public ChargeCollectorManager(Level level) { /// 获取当前维度的ChargeCollectorManager public static ChargeCollectorManager getInstance(Level level) { - if (!INSTANCES.containsKey(level)) { - INSTANCES.put(level, new ChargeCollectorManager(level)); + if (!ChargeCollectorManager.INSTANCES.containsKey(level)) { + ChargeCollectorManager.INSTANCES.put(level, new ChargeCollectorManager(level)); } - return INSTANCES.get(level); + return ChargeCollectorManager.INSTANCES.get(level); } /// 充电 @@ -54,12 +55,12 @@ public void charge(double chargeNum, BlockPos blockPos) { double surplus = chargeNum; for (Entry entry : chargeCollectorCollection) { if (entry.isInfinite()) { - InfiniteCollectorBlockEntity ic = entry.getInfiniteCollector(); - if (!this.canCollect(ic, blockPos)) continue; + InfiniteCollectorBlockEntity ic = entry.infiniteCollector(); + if (ic == null || !this.canCollect(ic, blockPos)) continue; surplus = ic.incomingCharge(surplus, blockPos); } else { - ChargeCollectorBlockEntity cc = entry.getChargeCollector(); - if (!this.canCollect(cc, blockPos)) continue; + ChargeCollectorBlockEntity cc = entry.chargeCollector(); + if (cc == null || !this.canCollect(cc, blockPos)) continue; surplus = cc.incomingCharge(surplus, blockPos); } if (surplus == 0) return; @@ -112,7 +113,7 @@ public List getNearestChargeCollect(BlockPos blockPos) { distanceList.add(new Entry(distance, null, entry.getValue())); } return distanceList.stream() - .sorted(Comparator.comparing(Entry::getDistance)) + .sorted(Comparator.comparing(Entry::distance)) .collect(Collectors.toList()); } @@ -145,17 +146,11 @@ public boolean canCollect(InfiniteCollectorBlockEntity blockEntity, BlockPos blo && blockEntity.getPos().getZ() + range >= blockPos.getZ(); } - @Getter - public static class Entry { - public final double distance; - public final ChargeCollectorBlockEntity chargeCollector; - public final InfiniteCollectorBlockEntity infiniteCollector; - - public Entry(double distance, ChargeCollectorBlockEntity chargeCollector, InfiniteCollectorBlockEntity infiniteCollector) { - this.distance = distance; - this.chargeCollector = chargeCollector; - this.infiniteCollector = infiniteCollector; - } + public record Entry( + double distance, + @Nullable ChargeCollectorBlockEntity chargeCollector, + @Nullable InfiniteCollectorBlockEntity infiniteCollector + ) { public boolean isInfinite() { return this.infiniteCollector != null; diff --git a/src/main/java/dev/dubhe/anvilcraft/api/component/TranslatableContents.java b/src/main/java/dev/dubhe/anvilcraft/api/component/TranslatableContents.java index 585c988b78..6f18fb4cf4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/component/TranslatableContents.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/component/TranslatableContents.java @@ -18,6 +18,7 @@ import net.minecraft.network.chat.ResolutionContext; import net.minecraft.network.chat.Style; import net.minecraft.util.ExtraCodecs; +import net.neoforged.fml.loading.FMLLoader; import org.jspecify.annotations.Nullable; import java.util.Arrays; @@ -25,7 +26,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; -import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -33,9 +33,14 @@ public class TranslatableContents implements ComponentContents { public static final Object[] NO_ARGS = new Object[0]; private static final Codec PRIMITIVE_ARG_CODEC = ExtraCodecs.JAVA.validate(TranslatableContents::filterAllowedArguments); @SuppressWarnings("NullableProblems") - private static final Codec ARG_CODEC = Codec.either(PRIMITIVE_ARG_CODEC, ComponentSerialization.CODEC).xmap( - e -> e.map(Function.identity(), component -> Objects.requireNonNullElse(component.tryCollapseToString(), component)), - o -> o instanceof Component c ? Either.right(c) : Either.left(o) + private static final Codec ARG_CODEC = Codec.either( + TranslatableContents.PRIMITIVE_ARG_CODEC, + ComponentSerialization.CODEC + ).xmap( + e -> e.map(Objects::requireNonNull, component -> Objects.requireNonNullElse(component.tryCollapseToString(), component)), + o -> o instanceof Component c + ? Either.right(c) + : Either.left(Objects.requireNonNull(o, "Translation argument")) ); public static final MapCodec MAP_CODEC = CodecUtil.mapCodec( Codec.STRING @@ -44,10 +49,10 @@ public class TranslatableContents implements ComponentContents { ComponentSerialization.flatRestrictedCodec(Integer.MAX_VALUE) .lenientOptionalFieldOf("fallback") .forGetter(o -> Optional.ofNullable(o.fallback)), - ARG_CODEC + TranslatableContents.ARG_CODEC .listOf() .optionalFieldOf("with") - .forGetter(o -> adjustArgs(o.args)), + .forGetter(o -> TranslatableContents.adjustArgs(o.args)), TranslatableContents::create ); private static final FormattedText TEXT_PERCENT = FormattedText.of("%"); @@ -63,7 +68,7 @@ public class TranslatableContents implements ComponentContents { private static final Pattern FORMAT_PATTERN = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); private static DataResult filterAllowedArguments(@Nullable Object result) { - return !isAllowedPrimitiveArgument(result) + return !TranslatableContents.isAllowedPrimitiveArgument(result) ? DataResult.error(() -> "This value needs to be parsed as component") : DataResult.success(result); } @@ -79,12 +84,12 @@ private static Optional> adjustArgs(Object[] args) { @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private static Object[] adjustArgs(Optional> args) { - return args.map(a -> a.isEmpty() ? NO_ARGS : a.toArray()).orElse(NO_ARGS); + return args.map(a -> a.isEmpty() ? TranslatableContents.NO_ARGS : a.toArray()).orElse(TranslatableContents.NO_ARGS); } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private static TranslatableContents create(String key, Optional fallback, Optional> args) { - return new TranslatableContents(key, fallback.orElse(null), adjustArgs(args)); + return new TranslatableContents(key, fallback.orElse(null), TranslatableContents.adjustArgs(args)); } public TranslatableContents(String key, @Nullable Component fallback, Object[] args) { @@ -93,10 +98,10 @@ public TranslatableContents(String key, @Nullable Component fallback, Object[] a this.args = args; // Neo: This is transitively called by some static initializers. To allow using Minecraft classes from tests // without fully initializing FML, we disable the validation if FML is not initialized. - var loader = net.neoforged.fml.loading.FMLLoader.getCurrentOrNull(); + var loader = FMLLoader.getCurrentOrNull(); if (loader != null && !loader.isProduction()) { for (Object arg : this.args) { - if (!(arg instanceof Component) && !isAllowedPrimitiveArgument(arg)) { + if (!(arg instanceof Component) && !TranslatableContents.isAllowedPrimitiveArgument(arg)) { throw new IllegalArgumentException( "TranslatableContents' arguments must be either a Component, Number, Boolean, or a String. Was given " + arg + " for " + this.key); @@ -107,7 +112,7 @@ public TranslatableContents(String key, @Nullable Component fallback, Object[] a @Override public MapCodec codec() { - return MAP_CODEC; + return TranslatableContents.MAP_CODEC; } private void decompose() { @@ -142,7 +147,7 @@ private void decompose() { } private void decomposeTemplate(String template, Consumer decomposedParts) { - Matcher matcher = FORMAT_PATTERN.matcher(template); + Matcher matcher = TranslatableContents.FORMAT_PATTERN.matcher(template); try { int replacementIndex = 0; @@ -163,7 +168,7 @@ private void decomposeTemplate(String template, Consumer decompos String formatType = matcher.group(2); String formatString = template.substring(start, end); if ("%".equals(formatType) && "%%".equals(formatString)) { - decomposedParts.accept(TEXT_PERCENT); + decomposedParts.accept(TranslatableContents.TEXT_PERCENT); } else { if (!"s".equals(formatType)) { throw new TranslatableFormatException(this, "Unsupported format: '" + formatString + "'"); @@ -197,7 +202,7 @@ private FormattedText getArgument(int index) { return componentArg; } else { // noinspection ConstantValue - return arg == null ? TEXT_NULL : FormattedText.of(arg.toString()); + return arg == null ? TranslatableContents.TEXT_NULL : FormattedText.of(arg.toString()); } } else { throw new TranslatableFormatException(this, index); diff --git a/src/main/java/dev/dubhe/anvilcraft/api/entity/attribute/EntityReachAttribute.java b/src/main/java/dev/dubhe/anvilcraft/api/entity/attribute/EntityReachAttribute.java index e16a5ddf74..6a4fbe8783 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/entity/attribute/EntityReachAttribute.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/entity/attribute/EntityReachAttribute.java @@ -15,10 +15,14 @@ public class EntityReachAttribute { public static Supplier, AttributeModifier>> getRangeModifierSupplier( AttributeModifier modifier ) { - return Suppliers.memoize(() -> ImmutableMultimap.of( - Attributes.BLOCK_INTERACTION_RANGE, modifier, - Attributes.ENTITY_INTERACTION_RANGE, modifier - )); + @SuppressWarnings("NullableProblems") + Supplier, AttributeModifier>> supplier = Suppliers.memoize( + () -> ImmutableMultimap.of( + Attributes.BLOCK_INTERACTION_RANGE, modifier, + Attributes.ENTITY_INTERACTION_RANGE, modifier + ) + ); + return supplier; } public static Attribute getReachAttribute() { diff --git a/src/main/java/dev/dubhe/anvilcraft/api/fluid/HoneyBottleResourceHandler.java b/src/main/java/dev/dubhe/anvilcraft/api/fluid/HoneyBottleResourceHandler.java index 82419ea706..e3d3f9acec 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/fluid/HoneyBottleResourceHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/fluid/HoneyBottleResourceHandler.java @@ -30,7 +30,7 @@ protected FluidResource getResourceFrom(ItemResource accessResource, int index) @Override protected int getAmountFrom(ItemResource accessResource, int index) { - return accessResource.is(Items.HONEY_BOTTLE) ? HONEY_PER_BOTTLE : 0; + return accessResource.is(Items.HONEY_BOTTLE) ? HoneyBottleResourceHandler.HONEY_PER_BOTTLE : 0; } @Override @@ -38,7 +38,7 @@ protected ItemResource update(ItemResource accessResource, int index, FluidResou if (newAmount == 0) { // 排空:蜂蜜瓶 -> 空玻璃瓶 return ItemResource.of(Items.GLASS_BOTTLE); - } else if (newAmount == HONEY_PER_BOTTLE && newResource.getFluid() instanceof HoneyFluid) { + } else if (newAmount == HoneyBottleResourceHandler.HONEY_PER_BOTTLE && newResource.getFluid() instanceof HoneyFluid) { // 填满:空玻璃瓶 -> 蜂蜜瓶 return ItemResource.of(Items.HONEY_BOTTLE); } @@ -53,6 +53,6 @@ public boolean isValid(int index, FluidResource resource) { @Override protected int getCapacity(int index, FluidResource resource) { - return HONEY_PER_BOTTLE; + return HoneyBottleResourceHandler.HONEY_PER_BOTTLE; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/fluid/LargeCauldronFluidHandler.java b/src/main/java/dev/dubhe/anvilcraft/api/fluid/LargeCauldronFluidHandler.java index ba201cd3c1..43a914a3e6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/fluid/LargeCauldronFluidHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/fluid/LargeCauldronFluidHandler.java @@ -19,11 +19,11 @@ public class LargeCauldronFluidHandler implements ResourceHandler, ValueIOSerializable { public static final int TANK_COUNT = 8; public static final int TANK_CAPACITY = 64 * FluidType.BUCKET_VOLUME; - public static final int TOTAL_CAPACITY = TANK_COUNT * TANK_CAPACITY; + public static final int TOTAL_CAPACITY = LargeCauldronFluidHandler.TANK_COUNT * LargeCauldronFluidHandler.TANK_CAPACITY; private static final Codec> FLUIDS_CODEC = FluidStack.OPTIONAL_CODEC.listOf(); private final Runnable changeListener; - private final List fluids = new ArrayList<>(TANK_COUNT); + private final List fluids = new ArrayList<>(LargeCauldronFluidHandler.TANK_COUNT); private final FluidsJournal snapshotJournal = new FluidsJournal(); public LargeCauldronFluidHandler(Runnable changeListener) { @@ -32,37 +32,37 @@ public LargeCauldronFluidHandler(Runnable changeListener) { @Override public int size() { - return TANK_COUNT; + return LargeCauldronFluidHandler.TANK_COUNT; } @Override public FluidResource getResource(int index) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); return index < this.fluids.size() ? FluidResource.of(this.fluids.get(index)) : FluidResource.EMPTY; } @Override public long getAmountAsLong(int index) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); return index < this.fluids.size() ? this.fluids.get(index).getAmount() : 0; } @Override public long getCapacityAsLong(int index, FluidResource resource) { - Objects.checkIndex(index, TANK_COUNT); - return TANK_CAPACITY; + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); + return LargeCauldronFluidHandler.TANK_CAPACITY; } @Override public boolean isValid(int index, FluidResource resource) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); if (resource.isEmpty()) return false; - return this.findFluid(resource) >= 0 || this.fluids.size() < TANK_COUNT; + return this.findFluid(resource) >= 0 || this.fluids.size() < LargeCauldronFluidHandler.TANK_COUNT; } @Override public int insert(int index, FluidResource resource, int amount, TransactionContext transaction) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); return this.insert(resource, amount, false, transaction); } @@ -79,10 +79,10 @@ private int insert( ) { TransferPreconditions.checkNonEmptyNonNegative(resource, amount); int matching = this.findFluid(resource); - if (matching < 0 && this.fluids.size() >= TANK_COUNT) return 0; + if (matching < 0 && this.fluids.size() >= LargeCauldronFluidHandler.TANK_COUNT) return 0; int stored = matching < 0 ? 0 : this.fluids.get(matching).getAmount(); - int inserted = Math.min(amount, TANK_CAPACITY - stored); + int inserted = Math.min(amount, LargeCauldronFluidHandler.TANK_CAPACITY - stored); if (inserted <= 0) return 0; this.snapshotJournal.updateSnapshots(transaction); @@ -100,7 +100,7 @@ private int insert( @Override public int extract(int index, FluidResource resource, int amount, TransactionContext transaction) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); TransferPreconditions.checkNonEmptyNonNegative(resource, amount); return this.extractLayer(index, resource, amount, transaction); } @@ -137,11 +137,11 @@ private int extractLayer( } public ResourceHandler bottomAccess() { - return new LayeredView(DrainOrder.BOTTOM, TOTAL_CAPACITY, true); + return new LayeredView(DrainOrder.BOTTOM, LargeCauldronFluidHandler.TOTAL_CAPACITY, true); } public ResourceHandler topAccess() { - return new LayeredView(DrainOrder.TOP, TOTAL_CAPACITY, false); + return new LayeredView(DrainOrder.TOP, LargeCauldronFluidHandler.TOTAL_CAPACITY, false); } public ResourceHandler sideAccess(int accessibleAmount) { @@ -154,9 +154,9 @@ public FluidStack getFluidInTank(int tank) { } public List copyFluids() { - List result = new ArrayList<>(TANK_COUNT); + List result = new ArrayList<>(LargeCauldronFluidHandler.TANK_COUNT); for (FluidStack fluid : this.fluids) result.add(fluid.copy()); - while (result.size() < TANK_COUNT) result.add(FluidStack.EMPTY); + while (result.size() < LargeCauldronFluidHandler.TANK_COUNT) result.add(FluidStack.EMPTY); return result; } @@ -164,8 +164,8 @@ public void setFluids(List fluids) { this.fluids.clear(); for (FluidStack fluid : fluids) { if (fluid.isEmpty()) continue; - this.fluids.add(fluid.copyWithAmount(Math.min(fluid.getAmount(), TANK_CAPACITY))); - if (this.fluids.size() == TANK_COUNT) break; + this.fluids.add(fluid.copyWithAmount(Math.min(fluid.getAmount(), LargeCauldronFluidHandler.TANK_CAPACITY))); + if (this.fluids.size() == LargeCauldronFluidHandler.TANK_COUNT) break; } this.changeListener.run(); } @@ -178,12 +178,12 @@ public int getTotalAmount() { @Override public void serialize(ValueOutput output) { - output.store("Fluids", FLUIDS_CODEC, this.fluids); + output.store("Fluids", LargeCauldronFluidHandler.FLUIDS_CODEC, this.fluids); } @Override public void deserialize(ValueInput input) { - this.setFluids(input.read("Fluids", FLUIDS_CODEC).orElse(List.of())); + this.setFluids(input.read("Fluids", LargeCauldronFluidHandler.FLUIDS_CODEC).orElse(List.of())); } private int findFluid(FluidResource resource) { @@ -254,12 +254,12 @@ private LayeredView(DrainOrder drainOrder, int accessibleAmount, boolean fillAtB @Override public int size() { - return TANK_COUNT; + return LargeCauldronFluidHandler.TANK_COUNT; } @Override public FluidResource getResource(int index) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); List order = LargeCauldronFluidHandler.this.layerOrder(this.drainOrder, this.accessibleAmount); return index < order.size() ? LargeCauldronFluidHandler.this.getResource(order.get(index)) @@ -268,26 +268,26 @@ public FluidResource getResource(int index) { @Override public long getAmountAsLong(int index) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); List order = LargeCauldronFluidHandler.this.layerOrder(this.drainOrder, this.accessibleAmount); return index < order.size() ? LargeCauldronFluidHandler.this.getAmountAsLong(order.get(index)) : 0; } @Override public long getCapacityAsLong(int index, FluidResource resource) { - Objects.checkIndex(index, TANK_COUNT); - return TANK_CAPACITY; + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); + return LargeCauldronFluidHandler.TANK_CAPACITY; } @Override public boolean isValid(int index, FluidResource resource) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); return LargeCauldronFluidHandler.this.isValid(index, resource); } @Override public int insert(int index, FluidResource resource, int amount, TransactionContext transaction) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); return this.insert(resource, amount, transaction); } @@ -298,7 +298,7 @@ public int insert(FluidResource resource, int amount, TransactionContext transac @Override public int extract(int index, FluidResource resource, int amount, TransactionContext transaction) { - Objects.checkIndex(index, TANK_COUNT); + Objects.checkIndex(index, LargeCauldronFluidHandler.TANK_COUNT); List order = LargeCauldronFluidHandler.this.layerOrder(this.drainOrder, this.accessibleAmount); return index < order.size() ? LargeCauldronFluidHandler.this.extractLayer(order.get(index), resource, amount, transaction) diff --git a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidContainerLookup.java b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidContainerLookup.java index 5bb76b4d77..cf6874ba70 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidContainerLookup.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidContainerLookup.java @@ -75,7 +75,7 @@ public static boolean isEntityConnectedToPipe( if (!level.isLoaded(pipePos)) { return false; } - Vec3 towardPipe = Vec3.atLowerCornerOf(sideToPipe.getUnitVec3i()).scale(ENTITY_PIPE_CONTACT_TOLERANCE); + Vec3 towardPipe = Vec3.atLowerCornerOf(sideToPipe.getUnitVec3i()).scale(FluidContainerLookup.ENTITY_PIPE_CONTACT_TOLERANCE); AABB contactBox = entity.getBoundingBox().expandTowards(towardPipe); return level.getBlockState(pipePos).getCollisionShape(level, pipePos).toAabbs().stream() .map(box -> box.move(pipePos.getX(), pipePos.getY(), pipePos.getZ())) diff --git a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkManager.java b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkManager.java index 149571aa36..b9cfb30d37 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkManager.java @@ -142,7 +142,7 @@ private void tickLevel(Level level, LevelData d) { long gameTime = level.getGameTime(); for (FluidPipeNetwork network : d.networks) { // #4 空闲降频:连续 IDLE_THRESHOLD tick 无转移后,每 IDLE_INTERVAL tick 才分配一次 - if (network.getIdleTicks() >= IDLE_THRESHOLD && gameTime % IDLE_INTERVAL != 0) { + if (network.getIdleTicks() >= FluidNetworkManager.IDLE_THRESHOLD && gameTime % FluidNetworkManager.IDLE_INTERVAL != 0) { continue; } network.tick(); @@ -168,7 +168,7 @@ private void rebuild(Level level, LevelData d) { d.containers.remove(containerPos); // 已失效 → 注销 continue; } - BlockPos seed = findUnindexedAdjacentPipe(level, containerPos, d.partIndex); + BlockPos seed = FluidNetworkManager.findUnindexedAdjacentPipe(level, containerPos, d.partIndex); if (seed == null) { continue; // 无相邻管道,或相邻管道所属网络已在本次重建中建好 } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkScanner.java b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkScanner.java index c8ff3fc4c2..3687465c9c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkScanner.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidNetworkScanner.java @@ -53,7 +53,7 @@ public static boolean isPipePart(BlockState state) { * 判断某位置是否为流体容器(提供 ResourceHandler 且非管道部件)。供管理器剔除失效容器用。 */ public static boolean isContainer(Level level, BlockPos pos) { - return !isPipePart(level.getBlockState(pos)) && FluidContainerLookup.find(level, pos, null) != null; + return !FluidNetworkScanner.isPipePart(level.getBlockState(pos)) && FluidContainerLookup.find(level, pos, null) != null; } /** @@ -80,11 +80,11 @@ private static boolean isConnectablePump(BlockState state, Direction faceToPump) * (此时泵仍是二极管单向连通,只是不主动提供扬程)。 */ private static int pumpHalfLift(Level level, BlockPos pumpPos) { - return level.getBlockEntity(pumpPos) instanceof PumpBlockEntity pbe && pbe.canPump() ? PUMP_HALF_LIFT : 0; + return level.getBlockEntity(pumpPos) instanceof PumpBlockEntity pbe && pbe.canPump() ? FluidNetworkScanner.PUMP_HALF_LIFT : 0; } private static FluidContainerLookup.Result container(Level level, BlockPos pos, Direction sideToPipe) { - if (isPipePart(level.getBlockState(pos))) { + if (FluidNetworkScanner.isPipePart(level.getBlockState(pos))) { return null; } return FluidContainerLookup.find(level, pos, sideToPipe); @@ -96,7 +96,7 @@ private static FluidContainerLookup.Result container(Level level, BlockPos pos, * @return 网络对象;种子非管道部件时返回 {@code null} */ public static FluidPipeNetwork scan(Level level, BlockPos seed) { - if (!isPipePart(level.getBlockState(seed))) { + if (!FluidNetworkScanner.isPipePart(level.getBlockState(seed))) { return null; } @@ -119,7 +119,7 @@ public static FluidPipeNetwork scan(Level level, BlockPos seed) { if (state.getBlock() instanceof ControlValveBlock && level.getBlockEntity(pos) instanceof ControlValveBlockEntity valveBe) { valves.putIfAbsent(pos, new ValveState(valveBe)); - expandAxial( + FluidNetworkScanner.expandAxial( level, pos, state.getValue(ControlValveBlock.AXIS), @@ -134,7 +134,7 @@ public static FluidPipeNetwork scan(Level level, BlockPos seed) { } else if (state.getBlock() instanceof PumpBlock) { // 记录泵的进液侧(二极管:仅允许 进液侧→另一侧 通过流体) diodes.put(pos.immutable(), state.getValue(PumpBlock.ORIENTATION).getDirection()); - expandPump(level, pos, state, phi, potential, adjacency, queue, endpoints, seenHandlers); + FluidNetworkScanner.expandPump(level, pos, state, phi, potential, adjacency, queue, endpoints, seenHandlers); } else if (state.getBlock() instanceof PipeBlock) { // 管道面止逆阀(HAS_CHECK_VALVE 属性需后续添加到 PipeBlock) // TODO: re-enable when PipeBlock gets HAS_CHECK_VALVE property @@ -145,7 +145,7 @@ public static FluidPipeNetwork scan(Level level, BlockPos seed) { faceFlow.put(pos.immutable(), new EnumMap<>(flows)); } } - expandPipe(level, pos, state, phi, potential, adjacency, queue, endpoints, seenHandlers); + FluidNetworkScanner.expandPipe(level, pos, state, phi, potential, adjacency, queue, endpoints, seenHandlers); } } @@ -179,10 +179,10 @@ private static void expandPipe( Map, Boolean> seenHandlers ) { for (Direction dir : Direction.values()) { - if (!hasAnyConnectionToward(state, dir)) { + if (!FluidNetworkScanner.hasAnyConnectionToward(state, dir)) { continue; } - visitNeighbor(level, pos, dir, phi, potential, adjacency, queue, endpoints, seenHandlers); + FluidNetworkScanner.visitNeighbor(level, pos, dir, phi, potential, adjacency, queue, endpoints, seenHandlers); } } @@ -201,13 +201,13 @@ private static void expandPump( Map, Boolean> seenHandlers ) { Direction outputDir = state.getValue(PumpBlock.ORIENTATION).getDirection(); - int lift = pumpHalfLift(level, pos); + int lift = FluidNetworkScanner.pumpHalfLift(level, pos); for (Direction side : new Direction[]{ outputDir, outputDir.getOpposite() }) { int neighborPhi = phi + (side == outputDir ? lift : -lift); - visitNeighborWithPhi(level, pos, side, neighborPhi, potential, adjacency, queue, endpoints, seenHandlers); + FluidNetworkScanner.visitNeighborWithPhi(level, pos, side, neighborPhi, potential, adjacency, queue, endpoints, seenHandlers); } } @@ -230,7 +230,7 @@ private static void expandAxial( Direction.get(Direction.AxisDirection.POSITIVE, axis), Direction.get(Direction.AxisDirection.NEGATIVE, axis) }) { - visitNeighbor(level, pos, side, phi, potential, adjacency, queue, endpoints, seenHandlers); + FluidNetworkScanner.visitNeighbor(level, pos, side, phi, potential, adjacency, queue, endpoints, seenHandlers); } } @@ -248,7 +248,7 @@ private static void visitNeighbor( List endpoints, Map, Boolean> seenHandlers ) { - visitNeighborWithPhi(level, pos, dir, phi, potential, adjacency, queue, endpoints, seenHandlers); + FluidNetworkScanner.visitNeighborWithPhi(level, pos, dir, phi, potential, adjacency, queue, endpoints, seenHandlers); } /** @@ -273,26 +273,26 @@ private static void visitNeighborWithPhi( Direction faceBack = dir.getOpposite(); // 可连接泵(无论通/断电)→ 穿过(二极管;扬程由 enqueuePump 按通电状态决定) - if (isConnectablePump(neighborState, faceBack)) { - link(adjacency, pos, neighborPos); - enqueuePump(level, neighborPos, neighborState, pos, potential, queue); + if (FluidNetworkScanner.isConnectablePump(neighborState, faceBack)) { + FluidNetworkScanner.link(adjacency, pos, neighborPos); + FluidNetworkScanner.enqueuePump(level, neighborPos, neighborState, pos, potential, queue); return; } // 控制阀:连接面正对本部件 → 门控透传 if (neighborState.getBlock() instanceof ControlValveBlock && ControlValveBlock.isConnectableFace(neighborState, faceBack)) { - link(adjacency, pos, neighborPos); - enqueuePart(neighborPos, neighborPhi, potential, queue); + FluidNetworkScanner.link(adjacency, pos, neighborPos); + FluidNetworkScanner.enqueuePart(neighborPos, neighborPhi, potential, queue); return; } // 对准本部件的另一管道 → 同势场(用 hasAnyConnectionToward:节点认 PIPE+END, // 否则节点朝泵/容器的 END 方向会被漏读,导致泵紧邻节点时抽不到液体) - if (neighborState.getBlock() instanceof PipeBlock && hasAnyConnectionToward(neighborState, faceBack)) { - link(adjacency, pos, neighborPos); - enqueuePart(neighborPos, neighborPhi, potential, queue); + if (neighborState.getBlock() instanceof PipeBlock && FluidNetworkScanner.hasAnyConnectionToward(neighborState, faceBack)) { + FluidNetworkScanner.link(adjacency, pos, neighborPos); + FluidNetworkScanner.enqueuePart(neighborPos, neighborPhi, potential, queue); return; } // 容器 → 端点 - addEndpointIfContainer(level, neighborPos, faceBack, neighborPhi, pos, endpoints, seenHandlers); + FluidNetworkScanner.addEndpointIfContainer(level, neighborPos, faceBack, neighborPhi, pos, endpoints, seenHandlers); } private static void enqueuePart(BlockPos pos, int phi, Map potential, Deque queue) { @@ -317,7 +317,7 @@ private static void enqueuePump( ) { Direction outputDir = pumpState.getValue(PumpBlock.ORIENTATION).getDirection(); int fromPhi = potential.get(fromPos); - int lift = pumpHalfLift(level, pumpPos); + int lift = FluidNetworkScanner.pumpHalfLift(level, pumpPos); int pumpPhi; if (fromPos.equals(pumpPos.relative(outputDir))) { pumpPhi = fromPhi - lift; // fromPos 在输出侧:fromPhi = pumpPhi + lift @@ -351,7 +351,7 @@ private static void addEndpointIfContainer( } BlockPos immutablePos = containerPos.immutable(); if (endpoints.stream().anyMatch(endpoint -> endpoint.containerPos().equals(immutablePos))) return; - FluidContainerLookup.Result container = container(level, containerPos, sideToPipe); + FluidContainerLookup.Result container = FluidNetworkScanner.container(level, containerPos, sideToPipe); if (container == null) { return; } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidPipeNetwork.java b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidPipeNetwork.java index 683835b310..b0da04837a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidPipeNetwork.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/fluid/network/FluidPipeNetwork.java @@ -4,6 +4,7 @@ import lombok.Getter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; import net.neoforged.neoforge.transfer.ResourceHandler; import net.neoforged.neoforge.transfer.fluid.FluidResource; @@ -28,11 +29,11 @@ public class FluidPipeNetwork { public static final int HEIGHT_RATE = 50; public static final int MAX_SPEED = 2000; - public static final int FULL_SPEED_HEIGHT = MAX_SPEED / HEIGHT_RATE; + public static final int FULL_SPEED_HEIGHT = FluidPipeNetwork.MAX_SPEED / FluidPipeNetwork.HEIGHT_RATE; public static int speedForHeightDiff(int heightDiff) { if (heightDiff <= 0) return 0; - return Math.min(heightDiff * HEIGHT_RATE, MAX_SPEED); + return Math.min(heightDiff * FluidPipeNetwork.HEIGHT_RATE, FluidPipeNetwork.MAX_SPEED); } private final Level level; @@ -159,7 +160,7 @@ private void distributeFromSource(FluidEndpoint source) { int groupHeight = entry.getKey(); List group = entry.getValue(); int heightDiff = source.effectiveHeight() - groupHeight; - int groupSpeed = speedForHeightDiff(heightDiff); + int groupSpeed = FluidPipeNetwork.speedForHeightDiff(heightDiff); boolean groupFull = this.fillGroup(source, tankIdx, stored, group, groupSpeed, pathValves); if (srcHandler.getAmountAsInt(tankIdx) <= 0) break; if (!groupFull) break; @@ -177,7 +178,8 @@ private boolean fillGroup( Map> pathValves ) { BlockPos src = source.containerPos(); - group.sort(Comparator.comparingInt((FluidEndpoint e) -> Math.abs(sumXZ(e.containerPos()) - sumXZ(src))) + group.sort(Comparator.comparingInt((FluidEndpoint e) -> Math.abs( + FluidPipeNetwork.sumXZ(e.containerPos()) - FluidPipeNetwork.sumXZ(src))) .thenComparingInt(e -> Math.abs(e.containerPos().getX() - src.getX())) .thenComparingInt(e -> Math.abs(e.containerPos().getZ() - src.getZ()))); @@ -185,10 +187,10 @@ private boolean fillGroup( ResourceHandler srcHandler = source.handler(); if (source.cauldron()) { this.fillFromFullCauldron(source, tankIdx, group, pathValves); - return isGroupCapacityFull(group); + return FluidPipeNetwork.isGroupCapacityFull(group); } if (this.fillFirstWholeCauldronTarget(source, tankIdx, group, pathValves)) { - return isGroupCapacityFull(group); + return FluidPipeNetwork.isGroupCapacityFull(group); } group = group.stream().filter(target -> !target.cauldron()).toList(); if (group.isEmpty()) return false; @@ -200,9 +202,9 @@ private boolean fillGroup( List active = new ArrayList<>(); for (FluidEndpoint target : group) { - if (minValveRemaining(pathValves.get(target.fromPipePos())) <= 0) continue; - if (canInsert(target.handler(), fluidType)) { - active.add(new ActiveTarget(target, currentAmount(target))); + if (FluidPipeNetwork.minValveRemaining(pathValves.get(target.fromPipePos())) <= 0) continue; + if (FluidPipeNetwork.canInsert(target.handler(), fluidType)) { + active.add(new ActiveTarget(target, FluidPipeNetwork.currentAmount(target))); } } if (active.isEmpty()) break; @@ -223,7 +225,7 @@ private boolean fillGroup( if (srcAmount <= 0) break; List valvePath = pathValves.get(target.fromPipePos()); - int valveLimit = minValveRemaining(valvePath); + int valveLimit = FluidPipeNetwork.minValveRemaining(valvePath); want = Math.min(want, Math.min(budget, Math.min(valveLimit, srcAmount))); if (want <= 0) continue; @@ -239,14 +241,14 @@ private boolean fillGroup( } tx.commit(); budget -= inserted; - deductValves(valvePath, inserted); + FluidPipeNetwork.deductValves(valvePath, inserted); progressed = true; this.onTransferred(source); } } if (!progressed) break; } - return isGroupCapacityFull(allTargets); + return FluidPipeNetwork.isGroupCapacityFull(allTargets); } private TreeMap> collectTargetsByHeight( @@ -275,7 +277,7 @@ private boolean canTarget( if (target.handler().equals(source.handler())) return false; if (source.cauldron() || target.cauldron()) { if (this.wholeCauldronTransferAmount(source, tankIdx, target, stored) <= 0) return false; - } else if (!canInsert(target.handler(), stored)) { + } else if (!FluidPipeNetwork.canInsert(target.handler(), stored)) { return false; } return reach == null || this.isEndpointReachable(reach, target); @@ -317,9 +319,9 @@ private void fillFromFullCauldron( for (FluidEndpoint target : group) { int amount = this.wholeCauldronTransferAmount(source, tankIdx, target, stored); List valvePath = pathValves.get(target.fromPipePos()); - if (amount <= 0 || minValveRemaining(valvePath) < amount) continue; + if (amount <= 0 || FluidPipeNetwork.minValveRemaining(valvePath) < amount) continue; if (this.moveWholeCauldron(source, tankIdx, target, stored, amount) == amount) { - deductValves(valvePath, amount); + FluidPipeNetwork.deductValves(valvePath, amount); this.onTransferred(source); return; } @@ -337,9 +339,9 @@ private boolean fillFirstWholeCauldronTarget( FluidResource stored = source.handler().getResource(tankIdx); int amount = this.wholeCauldronTransferAmount(source, tankIdx, target, stored); List valvePath = pathValves.get(target.fromPipePos()); - if (amount <= 0 || minValveRemaining(valvePath) < amount) continue; + if (amount <= 0 || FluidPipeNetwork.minValveRemaining(valvePath) < amount) continue; if (this.moveWholeCauldron(source, tankIdx, target, stored, amount) != amount) continue; - deductValves(valvePath, amount); + FluidPipeNetwork.deductValves(valvePath, amount); this.onTransferred(source); return true; } @@ -358,10 +360,10 @@ private int wholeCauldronTransferAmount( amount = source.handler().getCapacityAsInt(tankIdx, stored); if (amount <= 0 || source.handler().getAmountAsInt(tankIdx) != amount) return 0; } else { - amount = capacityFor(target.handler(), stored); + amount = FluidPipeNetwork.capacityFor(target.handler(), stored); if (amount <= 0 || source.handler().getAmountAsInt(tankIdx) < amount) return 0; } - if (target.cauldron() && currentAmount(target) != 0) return 0; + if (target.cauldron() && FluidPipeNetwork.currentAmount(target) != 0) return 0; try (Transaction transaction = Transaction.openRoot()) { int extracted = source.handler().extract(tankIdx, stored, amount, transaction); if (extracted != amount) return 0; @@ -390,12 +392,13 @@ private int moveWholeCauldron( private boolean canTickEndpoints() { this.disconnectedEntityEndpoints.clear(); for (FluidEndpoint endpoint : this.entityEndpoints) { - if (!FluidContainerLookup.isEntityConnectedToPipe( - this.level, - endpoint.containerPos(), - endpoint.sideToPipe(), - endpoint.entity() - )) { + Entity entity = endpoint.entity(); + if (entity == null || !FluidContainerLookup.isEntityConnectedToPipe( + this.level, + endpoint.containerPos(), + endpoint.sideToPipe(), + entity + )) { this.disconnectedEntityEndpoints.add(endpoint); } } @@ -464,8 +467,8 @@ private static boolean isGroupCapacityFull(List group) { } private static int minValveRemaining(List valvePath) { - if (valvePath == null || valvePath.isEmpty()) return MAX_SPEED; - int min = MAX_SPEED; + if (valvePath == null || valvePath.isEmpty()) return FluidPipeNetwork.MAX_SPEED; + int min = FluidPipeNetwork.MAX_SPEED; for (ValveState v : valvePath) { min = Math.min(min, v.remaining()); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockAnvilBehavior.java b/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockAnvilBehavior.java index 50e4a699af..0ed2bb7f0f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockAnvilBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockAnvilBehavior.java @@ -1,6 +1,7 @@ package dev.dubhe.anvilcraft.api.giantanvil; import dev.dubhe.anvilcraft.util.BlockMiningEffect; +import org.jspecify.annotations.Nullable; import java.util.Objects; @@ -19,12 +20,12 @@ public ShockAnvilBehavior(BlockMiningEffect miningEffect) { /** 将本体方块铁砧的挖掘效果转换为默认掉落行为。 */ public static ShockAnvilBehavior fromMiningEffect(BlockMiningEffect effect) { - if (effect.equals(BlockMiningEffect.NORMAL)) return NORMAL; + if (effect.equals(BlockMiningEffect.NORMAL)) return ShockAnvilBehavior.NORMAL; return new ShockAnvilBehavior(effect); } /** 判断两个边框位置是否可以组成同一套撼地破坏结构。 */ - public boolean isCompatibleWith(ShockAnvilBehavior other) { + public boolean isCompatibleWith(@Nullable ShockAnvilBehavior other) { return other != null && this.miningEffect.equals(other.miningEffect) && this.dropBehavior.id().equals(other.dropBehavior.id()); diff --git a/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockDropBehavior.java b/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockDropBehavior.java index d0403d7150..8f35392958 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockDropBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/giantanvil/ShockDropBehavior.java @@ -18,7 +18,7 @@ public interface ShockDropBehavior { * 返回行为标识。四个边框位置只有标识一致时才会组成同一种撼地配方;自定义处理器应覆盖此方法。 */ default Identifier id() { - return DEFAULT_ID; + return ShockDropBehavior.DEFAULT_ID; } void drop(ShockContext context, BlockPos pos, ItemStack stack); diff --git a/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerManager.java b/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerManager.java index 0792eb918f..79713c195c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerManager.java @@ -31,7 +31,7 @@ public static IHammerChangeable getChange(Block block) { /// 注册铁砧锤处理器 public static void register() { - for (Map.Entry, IHammerChangeable> entry : INIT_CHANGE.entrySet()) { + for (Map.Entry, IHammerChangeable> entry : HammerManager.INIT_CHANGE.entrySet()) { HammerManager.CHANGE.put(entry.getKey().get(), entry.getValue()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerRotateBehavior.java b/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerRotateBehavior.java index 50d77aee4e..dd10f713bc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerRotateBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/hammer/HammerRotateBehavior.java @@ -9,6 +9,7 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.block.state.properties.Property; +import org.jspecify.annotations.Nullable; /// 可被锤子改变的方块 @SuppressWarnings("unused") @@ -25,41 +26,41 @@ public boolean change(Player player, BlockPos blockPos, Level level, ItemStack a }; private static BlockState rotate(BlockState state) { - Direction direction = state.getValue(FACING); + Direction direction = state.getValue(HammerRotateBehavior.FACING); return switch (direction) { - case WEST -> state.setValue(FACING, Direction.UP); - case UP -> state.setValue(FACING, Direction.DOWN); - case DOWN -> state.setValue(FACING, Direction.NORTH); - default -> state.setValue(FACING, direction.getClockWise()); + case WEST -> state.setValue(HammerRotateBehavior.FACING, Direction.UP); + case UP -> state.setValue(HammerRotateBehavior.FACING, Direction.DOWN); + case DOWN -> state.setValue(HammerRotateBehavior.FACING, Direction.NORTH); + default -> state.setValue(HammerRotateBehavior.FACING, direction.getClockWise()); }; } private static BlockState hopperRotate(BlockState state) { - Direction direction = state.getValue(FACING_HOPPER); + Direction direction = state.getValue(HammerRotateBehavior.FACING_HOPPER); return switch (direction) { - case WEST -> state.setValue(FACING_HOPPER, Direction.DOWN); - case DOWN -> state.setValue(FACING_HOPPER, Direction.NORTH); - default -> state.setValue(FACING_HOPPER, direction.getClockWise()); + case WEST -> state.setValue(HammerRotateBehavior.FACING_HOPPER, Direction.DOWN); + case DOWN -> state.setValue(HammerRotateBehavior.FACING_HOPPER, Direction.NORTH); + default -> state.setValue(HammerRotateBehavior.FACING_HOPPER, direction.getClockWise()); }; } private static BlockState horizontalRotate(BlockState state) { return state.setValue( - HORIZONTAL_FACING, - state.getValue(HORIZONTAL_FACING).getClockWise() + HammerRotateBehavior.HORIZONTAL_FACING, + state.getValue(HammerRotateBehavior.HORIZONTAL_FACING).getClockWise() ); } @Override default boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState state = level.getBlockState(blockPos); - if (state.hasProperty(FACING)) { + if (state.hasProperty(HammerRotateBehavior.FACING)) { state = HammerRotateBehavior.rotate(state); } else { - if (state.hasProperty(FACING_HOPPER)) { + if (state.hasProperty(HammerRotateBehavior.FACING_HOPPER)) { state = HammerRotateBehavior.hopperRotate(state); } else { - if (state.hasProperty(HORIZONTAL_FACING)) { + if (state.hasProperty(HammerRotateBehavior.HORIZONTAL_FACING)) { state = HammerRotateBehavior.horizontalRotate(state); } } @@ -69,13 +70,13 @@ default boolean change(Player player, BlockPos blockPos, Level level, ItemStack } @Override - default Property getChangeableProperty(BlockState state) { - if (state.hasProperty(FACING)) { - return FACING; - } else if (state.hasProperty(FACING_HOPPER)) { - return FACING_HOPPER; - } else if (state.hasProperty(HORIZONTAL_FACING)) { - return HORIZONTAL_FACING; + default @Nullable Property getChangeableProperty(BlockState state) { + if (state.hasProperty(HammerRotateBehavior.FACING)) { + return HammerRotateBehavior.FACING; + } else if (state.hasProperty(HammerRotateBehavior.FACING_HOPPER)) { + return HammerRotateBehavior.FACING_HOPPER; + } else if (state.hasProperty(HammerRotateBehavior.HORIZONTAL_FACING)) { + return HammerRotateBehavior.HORIZONTAL_FACING; } return null; } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/heat/HeatRecorder.java b/src/main/java/dev/dubhe/anvilcraft/api/heat/HeatRecorder.java index b492e2c6bf..1a771ecefc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/heat/HeatRecorder.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/heat/HeatRecorder.java @@ -38,7 +38,7 @@ public static RegisterHelper registerHeatables(Identifier id) { } public static HeaterInfo registerProducerInfo(HeaterInfo info) { - PRODUCER_INFOS.add(info); + HeatRecorder.PRODUCER_INFOS.add(info); return info; } @@ -152,53 +152,53 @@ public RegisterHelper overheated( public RegisterHelper customTier(HeatTier tier, Block heatable) { HeatableBlockEntry entry = HeatableBlockEntry.simple(tier, heatable); - ENTRY_TO_ID.put(entry, this.id); - ENTRIES.computeIfAbsent(this.id, o -> new ArrayList<>()).add(entry); - ENTRIES.get(this.id).sort(HeatableBlockEntry::compareTo); + HeatRecorder.ENTRY_TO_ID.put(entry, this.id); + HeatRecorder.ENTRIES.computeIfAbsent(this.id, o -> new ArrayList<>()).add(entry); + HeatRecorder.ENTRIES.get(this.id).sort(HeatableBlockEntry::compareTo); return this; } public RegisterHelper customTier(HeatTier tier, Block heatable, TriPredicate predicate) { HeatableBlockEntry entry = HeatableBlockEntry.predicate(tier, heatable, predicate); - ENTRY_TO_ID.put(entry, this.id); - ENTRIES.computeIfAbsent(this.id, o -> new ArrayList<>()).add(entry); - ENTRIES.get(this.id).sort(HeatableBlockEntry::compareTo); + HeatRecorder.ENTRY_TO_ID.put(entry, this.id); + HeatRecorder.ENTRIES.computeIfAbsent(this.id, o -> new ArrayList<>()).add(entry); + HeatRecorder.ENTRIES.get(this.id).sort(HeatableBlockEntry::compareTo); return this; } } public static Optional getEntry(Identifier id, HeatTier tier) { - for (HeatableBlockEntry entry : ENTRIES.get(id)) { + for (HeatableBlockEntry entry : HeatRecorder.ENTRIES.get(id)) { if (entry.getTier().equals(tier)) return Optional.of(entry); } return Optional.empty(); } public static Optional getEntry(Identifier id, Level level, BlockPos pos, BlockState state) { - for (HeatableBlockEntry entry : ENTRIES.get(id)) { + for (HeatableBlockEntry entry : HeatRecorder.ENTRIES.get(id)) { if (entry.isValidBlock(level, pos, state)) return Optional.of(entry); } return Optional.empty(); } public static Optional getEntry(HeatTier tier) { - return getIdAndEntry(tier).getSecond(); + return HeatRecorder.getIdAndEntry(tier).getSecond(); } public static Optional getEntry(Level level, BlockPos pos, BlockState state) { - return getIdAndEntry(level, pos, state).getSecond(); + return HeatRecorder.getIdAndEntry(level, pos, state).getSecond(); } public static Optional getEntry(Level level, BlockPos pos, BlockState prevState, HeatTier tier) { - return getId(level, pos, prevState) - .flatMap(id -> Optional.ofNullable(ENTRIES.get(id).get(tier.ordinal()))); + return HeatRecorder.getId(level, pos, prevState) + .flatMap(id -> Optional.of(HeatRecorder.ENTRIES.get(id).get(tier.ordinal()))); } private static Pair, Optional> getIdAndEntry(HeatTier tier) { - for (List entries : ENTRIES.values()) { + for (List entries : HeatRecorder.ENTRIES.values()) { for (HeatableBlockEntry entry : entries) { if (entry.getTier().equals(tier)) { - return new Pair<>(Optional.ofNullable(ENTRY_TO_ID.get(entry)), Optional.of(entry)); + return new Pair<>(Optional.ofNullable(HeatRecorder.ENTRY_TO_ID.get(entry)), Optional.of(entry)); } } } @@ -208,10 +208,10 @@ private static Pair, Optional> getIdAnd private static Pair, Optional> getIdAndEntry( Level level, BlockPos pos, BlockState state ) { - for (List entries : ENTRIES.values()) { + for (List entries : HeatRecorder.ENTRIES.values()) { for (HeatableBlockEntry entry : entries) { if (entry.isValidBlock(level, pos, state)) { - return new Pair<>(Optional.ofNullable(ENTRY_TO_ID.get(entry)), Optional.of(entry)); + return new Pair<>(Optional.ofNullable(HeatRecorder.ENTRY_TO_ID.get(entry)), Optional.of(entry)); } } } @@ -219,73 +219,73 @@ private static Pair, Optional> getIdAnd } public static Optional getId(HeatTier tier) { - return getIdAndEntry(tier).getFirst(); + return HeatRecorder.getIdAndEntry(tier).getFirst(); } public static Optional getId(Level level, BlockPos pos, BlockState state) { - return getIdAndEntry(level, pos, state).getFirst(); + return HeatRecorder.getIdAndEntry(level, pos, state).getFirst(); } public static Optional getTier(Level level, BlockPos pos, BlockState state) { - return getEntry(level, pos, state).map(HeatableBlockEntry::getTier); + return HeatRecorder.getEntry(level, pos, state).map(HeatableBlockEntry::getTier); } public static Optional getHeatableBlock(Level level, BlockPos pos, BlockState prevState, HeatTier tier) { - return getEntry(level, pos, prevState, tier).map(HeatableBlockEntry::getDefaultBlock); + return HeatRecorder.getEntry(level, pos, prevState, tier).map(HeatableBlockEntry::getDefaultBlock); } public static Optional getHeatableBlock(Identifier id, HeatTier tier) { - return getEntry(id, tier).map(HeatableBlockEntry::getDefaultBlock); + return HeatRecorder.getEntry(id, tier).map(HeatableBlockEntry::getDefaultBlock); } public static Optional getPrevTierEntry(Level level, BlockPos pos, BlockState state) { - Pair, Optional> pair = getIdAndEntry(level, pos, state); + Pair, Optional> pair = HeatRecorder.getIdAndEntry(level, pos, state); Optional idOp = pair.getFirst(); Optional entryOp = pair.getSecond(); if (idOp.isEmpty() || entryOp.isEmpty()) return Optional.empty(); - List entries = ENTRIES.get(idOp.get()); + List entries = HeatRecorder.ENTRIES.get(idOp.get()); return ListUtil.safelyGet(entries, entries.indexOf(entryOp.get()) - 1); } public static Optional getPrevTier(Level level, BlockPos pos, BlockState state) { - return getPrevTierEntry(level, pos, state).map(HeatableBlockEntry::getTier); + return HeatRecorder.getPrevTierEntry(level, pos, state).map(HeatableBlockEntry::getTier); } public static Optional getPrevTierHeatableBlock(Level level, BlockPos pos, BlockState state) { - return getPrevTierEntry(level, pos, state).map(HeatableBlockEntry::getDefaultBlock); + return HeatRecorder.getPrevTierEntry(level, pos, state).map(HeatableBlockEntry::getDefaultBlock); } public static Optional getNextTierEntry(Level level, BlockPos pos, BlockState state) { - Pair, Optional> pair = getIdAndEntry(level, pos, state); + Pair, Optional> pair = HeatRecorder.getIdAndEntry(level, pos, state); Optional idOp = pair.getFirst(); Optional entryOp = pair.getSecond(); if (idOp.isEmpty() || entryOp.isEmpty()) return Optional.empty(); - List entries = ENTRIES.get(idOp.get()); + List entries = HeatRecorder.ENTRIES.get(idOp.get()); return ListUtil.safelyGet(entries, entries.indexOf(entryOp.get()) + 1); } public static Optional getNextTier(Level level, BlockPos pos, BlockState state) { - return getNextTierEntry(level, pos, state).map(HeatableBlockEntry::getTier); + return HeatRecorder.getNextTierEntry(level, pos, state).map(HeatableBlockEntry::getTier); } public static Optional getNextTierHeatableBlock(Level level, BlockPos pos, BlockState state) { - return getNextTierEntry(level, pos, state).map(HeatableBlockEntry::getDefaultBlock); + return HeatRecorder.getNextTierEntry(level, pos, state).map(HeatableBlockEntry::getDefaultBlock); } static { - registerHeatables(AnvilCraft.of("netherite")) + HeatRecorder.registerHeatables(AnvilCraft.of("netherite")) .normal(Blocks.NETHERITE_BLOCK, (level, pos, state) -> state.is(Tags.Blocks.STORAGE_BLOCKS_NETHERITE)) .heated(ModBlocks.HEATED_NETHERITE_BLOCK) .redhot(ModBlocks.REDHOT_NETHERITE_BLOCK) .glowing(ModBlocks.GLOWING_NETHERITE_BLOCK) .incandescent(ModBlocks.INCANDESCENT_NETHERITE_BLOCK); - registerHeatables(AnvilCraft.of("tungsten")) + HeatRecorder.registerHeatables(AnvilCraft.of("tungsten")) .normal(ModBlocks.TUNGSTEN_BLOCK, (level, pos, state) -> state.is(ModBlockTags.STORAGE_BLOCKS_TUNGSTEN)) .heated(ModBlocks.HEATED_TUNGSTEN_BLOCK) .redhot(ModBlocks.REDHOT_TUNGSTEN_BLOCK) .glowing(ModBlocks.GLOWING_TUNGSTEN_BLOCK) .incandescent(ModBlocks.INCANDESCENT_TUNGSTEN_BLOCK); - registerHeatables(AnvilCraft.of("ember_metal")) + HeatRecorder.registerHeatables(AnvilCraft.of("ember_metal")) .normal(ModBlocks.EMBER_METAL_BLOCK) .overheated(ModBlocks.OVERHEATED_EMBER_METAL_BLOCK); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/heat/HeaterManager.java b/src/main/java/dev/dubhe/anvilcraft/api/heat/HeaterManager.java index 21b039620c..c3002f54a7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/heat/HeaterManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/heat/HeaterManager.java @@ -37,14 +37,17 @@ public class HeaterManager { private final Level level; private final Set heatableBlocks = Collections.synchronizedSet(new HashSet<>()); - private final Multimap, BlockPos> producers = Multimaps.synchronizedSetMultimap(HashMultimap.create()); + @SuppressWarnings("NullableProblems") + private final Multimap, BlockPos> producers = Multimaps.synchronizedSetMultimap( + HashMultimap.create() + ); public static HeaterManager getInstance(Level level) { if (level.isClientSide()) return new HeaterManager(level); - if (!INSTANCES.containsKey(level)) { - INSTANCES.put(level, new HeaterManager(level)); + if (!HeaterManager.INSTANCES.containsKey(level)) { + HeaterManager.INSTANCES.put(level, new HeaterManager(level)); } - return INSTANCES.get(level); + return HeaterManager.INSTANCES.get(level); } public HeaterManager(Level level) { @@ -68,7 +71,7 @@ public static void removeProducer(BlockPos pos, Level level, HeaterInfo info) } public static void tickAll() { - INSTANCES.forEach((level, manager) -> { + HeaterManager.INSTANCES.forEach((level, manager) -> { if (level.getGameTime() % PowerGrid.GRID_TICK != 0) return; if (level.tickRateManager().isFrozen() && !level.tickRateManager().isSteppingForward()) return; manager.tick(); @@ -76,10 +79,7 @@ public static void tickAll() { } public void tick() { - Multimap, BlockPos> producers; - synchronized (this.producers) { - producers = MultimapBuilder.hashKeys().arrayListValues().build(this.producers); - } + Multimap, BlockPos> producers = this.copyProducers(); Map heatableBlocks = new HashMap<>(); for (HeaterInfo info : producers.keySet()) { List removals = new ArrayList<>(); @@ -97,6 +97,15 @@ public void tick() { } } + @SuppressWarnings("NullableProblems") + private Multimap, BlockPos> copyProducers() { + synchronized (this.producers) { + return MultimapBuilder.hashKeys() + .arrayListValues() + .build(this.producers); + } + } + private void tickProducers( HeaterInfo info, Map heatableBlocks, diff --git a/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatCollectorManager.java b/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatCollectorManager.java index 03afc6c4d9..61fe18973c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatCollectorManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatCollectorManager.java @@ -37,29 +37,32 @@ public class HeatCollectorManager { private static final List SOURCE_ENTRIES = new ArrayList<>(); static { - registerEntry(HeatSourceEntry.predicateAlways(4, state -> state.is(ModBlockTags.HEATED_BLOCKS))); - registerEntry(HeatSourceEntry.predicateAlways(16, state -> state.is(ModBlockTags.REDHOT_BLOCKS))); - registerEntry(HeatSourceEntry.predicateAlways(64, state -> state.is(ModBlockTags.GLOWING_BLOCKS))); - registerEntry(HeatSourceEntry.predicateAlways(256, state -> state.is(ModBlockTags.INCANDESCENT_BLOCKS))); - registerEntry(HeatSourceEntry.predicateAlways(2048, state -> state.is(ModBlocks.OVERHEATED_EMBER_METAL_BLOCK.get()))); - registerEntry(HeatSourceEntry.predicateAlways(1024, state -> state.is(ModBlockTags.OVERHEATED_BLOCKS))); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways(4, state -> state.is(ModBlockTags.HEATED_BLOCKS))); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways(16, state -> state.is(ModBlockTags.REDHOT_BLOCKS))); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways(64, state -> state.is(ModBlockTags.GLOWING_BLOCKS))); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways(256, state -> state.is(ModBlockTags.INCANDESCENT_BLOCKS))); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways( + 2048, + state -> state.is(ModBlocks.OVERHEATED_EMBER_METAL_BLOCK.get()) + )); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways(1024, state -> state.is(ModBlockTags.OVERHEATED_BLOCKS))); - registerEntry(HeatSourceEntry.simple(2, Blocks.MAGMA_BLOCK, Blocks.NETHERRACK)); - registerEntry(HeatSourceEntry.predicate( + HeatCollectorManager.registerEntry(HeatSourceEntry.simple(2, Blocks.MAGMA_BLOCK, Blocks.NETHERRACK)); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicate( 4, CampfireBlock::isLitCampfire, it -> it.setValue(CampfireBlock.LIT, false) )); - registerEntry(HeatSourceEntry.predicate( + HeatCollectorManager.registerEntry(HeatSourceEntry.predicate( 4, state -> state.getFluidState().isSourceOfType(Fluids.LAVA), _ -> Blocks.OBSIDIAN.defaultBlockState() )); - registerEntry(HeatSourceEntry.simple(4, Blocks.LAVA_CAULDRON, ModBlocks.OBSIDIAN_CAULDRON.get())); + HeatCollectorManager.registerEntry(HeatSourceEntry.simple(4, Blocks.LAVA_CAULDRON, ModBlocks.OBSIDIAN_CAULDRON.get())); - registerEntry(HeatSourceEntry.predicateAlways(2, state -> state.is(ModBlockTags.STORAGE_BLOCKS_URANIUM))); - registerEntry(HeatSourceEntry.forever(4, ModBlocks.EMBER_METAL_BLOCK.get())); - registerEntry(HeatSourceEntry.predicateAlways(8, state -> state.is(ModBlockTags.STORAGE_BLOCKS_PLUTONIUM))); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways(2, state -> state.is(ModBlockTags.STORAGE_BLOCKS_URANIUM))); + HeatCollectorManager.registerEntry(HeatSourceEntry.forever(4, ModBlocks.EMBER_METAL_BLOCK.get())); + HeatCollectorManager.registerEntry(HeatSourceEntry.predicateAlways(8, state -> state.is(ModBlockTags.STORAGE_BLOCKS_PLUTONIUM))); } private final Level level; @@ -67,31 +70,31 @@ public class HeatCollectorManager { private final Set infiniteCollectors = Collections.synchronizedSet(new HashSet<>()); public static void clear() { - synchronized (INSTANCES) { - INSTANCES.clear(); + synchronized (HeatCollectorManager.INSTANCES) { + HeatCollectorManager.INSTANCES.clear(); } } /// 获取当前维度的HeatCollectorManager public static HeatCollectorManager getInstance(Level level) { if (level.isClientSide()) return new HeatCollectorManager(level); - synchronized (INSTANCES) { - return INSTANCES.computeIfAbsent(level, HeatCollectorManager::new); + synchronized (HeatCollectorManager.INSTANCES) { + return HeatCollectorManager.INSTANCES.computeIfAbsent(level, HeatCollectorManager::new); } } private static Optional getExistingInstance(Level level) { - synchronized (INSTANCES) { - return Optional.ofNullable(INSTANCES.get(level)); + synchronized (HeatCollectorManager.INSTANCES) { + return Optional.ofNullable(HeatCollectorManager.INSTANCES.get(level)); } } public static void remove(Level level) { - INSTANCES.remove(level); + HeatCollectorManager.INSTANCES.remove(level); } public static void registerEntry(HeatSourceEntry entry) { - SOURCE_ENTRIES.add(entry); + HeatCollectorManager.SOURCE_ENTRIES.add(entry); } public static Optional getEntry(BlockState state) { @@ -103,24 +106,24 @@ public static Optional getEntry(BlockState state) { public static void addHeatCollector(BlockPos pos, Level level) { if (level.isClientSide()) return; - getInstance(level).heatCollectors.add(pos); + HeatCollectorManager.getInstance(level).heatCollectors.add(pos); } public static void removeHeatCollector(BlockPos pos, Level level) { - getExistingInstance(level).ifPresent(manager -> manager.heatCollectors.remove(pos)); + HeatCollectorManager.getExistingInstance(level).ifPresent(manager -> manager.heatCollectors.remove(pos)); } public static void addInfiniteCollector(BlockPos pos, Level level) { if (level.isClientSide()) return; - getInstance(level).infiniteCollectors.add(pos); + HeatCollectorManager.getInstance(level).infiniteCollectors.add(pos); } public static void removeInfiniteCollector(BlockPos pos, Level level) { - getExistingInstance(level).ifPresent(manager -> manager.infiniteCollectors.remove(pos)); + HeatCollectorManager.getExistingInstance(level).ifPresent(manager -> manager.infiniteCollectors.remove(pos)); } public static void checkWhenPlaceCollector(BlockPlaceContext ctx, BlockPos pos, Level level) { - HeatCollectorManager manager = getInstance(level); + HeatCollectorManager manager = HeatCollectorManager.getInstance(level); AABB validRange = AABB.ofSize(pos.getCenter(), 9, 9, 9); for (BlockPos checkedPos : manager.heatCollectors) { if (validRange.contains(checkedPos.getCenter())) { @@ -146,7 +149,7 @@ public static void checkWhenPlaceCollector(BlockPlaceContext ctx, BlockPos pos, } public static void checkWhenPlaceInfiniteCollector(BlockPlaceContext ctx, BlockPos pos, Level level) { - HeatCollectorManager manager = getInstance(level); + HeatCollectorManager manager = HeatCollectorManager.getInstance(level); AABB validRange = AABB.ofSize(pos.getCenter(), 9, 9, 9); for (BlockPos checkedPos : manager.heatCollectors) { if (validRange.contains(checkedPos.getCenter())) { @@ -177,8 +180,8 @@ public static void checkWhenPlaceInfiniteCollector(BlockPlaceContext ctx, BlockP public static void tickAll() { List managers; - synchronized (INSTANCES) { - managers = List.copyOf(INSTANCES.values()); + synchronized (HeatCollectorManager.INSTANCES) { + managers = List.copyOf(HeatCollectorManager.INSTANCES.values()); } managers.forEach(HeatCollectorManager::tick); } @@ -229,7 +232,7 @@ private void collectSources(IHeatCollector collector, Map { heatSourcesCache.computeIfAbsent(new Entry(finalPos, state, entry), _ -> new Double2ObjectAVLTreeMap<>()) .put( @@ -270,11 +273,11 @@ private int getCollectorRange(BlockState state) { private List getCollectorsFromNWToSE() { List collectors = new ArrayList<>(); // 先复制一份位置集合再遍历,避免遍历过程中移除失效收集器触发并发修改 - for (BlockPos pos : copyPositions(this.heatCollectors)) { + for (BlockPos pos : HeatCollectorManager.copyPositions(this.heatCollectors)) { Util.castSafely(this.level.getBlockEntity(pos), HeatCollectorBlockEntity.class) .ifPresentOrElse(collectors::add, () -> this.heatCollectors.remove(pos)); } - for (BlockPos pos : copyPositions(this.infiniteCollectors)) { + for (BlockPos pos : HeatCollectorManager.copyPositions(this.infiniteCollectors)) { Util.castSafely(this.level.getBlockEntity(pos), InfiniteCollectorBlockEntity.class) .ifPresentOrElse(collectors::add, () -> this.infiniteCollectors.remove(pos)); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatSourceEntry.java b/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatSourceEntry.java index 97f314e1b9..d91cb3785e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatSourceEntry.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/heat/collector/HeatSourceEntry.java @@ -84,7 +84,7 @@ public Simple(int charge, Block input, Block output) { @Override public int accepts(BlockState state) { - return state.is(this.input) ? getCharge() : 0; + return state.is(this.input) ? this.getCharge() : 0; } @Override @@ -103,7 +103,7 @@ public Always(int charge, Block input) { @Override public int accepts(BlockState state) { - return state.is(this.input) ? getCharge() : 0; + return state.is(this.input) ? this.getCharge() : 0; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/api/item/IDiskCloneable.java b/src/main/java/dev/dubhe/anvilcraft/api/item/IDiskCloneable.java index 889147927d..7298221468 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/item/IDiskCloneable.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/item/IDiskCloneable.java @@ -14,6 +14,7 @@ import net.minecraft.world.phys.BlockHitResult; import java.util.List; +import java.util.Objects; /// 可用磁盘复制的方块 public interface IDiskCloneable { @@ -23,7 +24,10 @@ public interface IDiskCloneable { void applyDiskData(ValueInput input); default List getDiskCompatibleGroups() { - return List.of(BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(((BlockEntity) this).getType()).toString()); + return List.of(Objects.requireNonNull( + BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(((BlockEntity) this).getType()), + "Unregistered block entity type" + ).toString()); } /// 使用磁盘物品与方块进行交互 diff --git a/src/main/java/dev/dubhe/anvilcraft/api/item/InfinityItemStackHandler.java b/src/main/java/dev/dubhe/anvilcraft/api/item/InfinityItemStackHandler.java index 4384c3fff4..59c716b406 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/item/InfinityItemStackHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/item/InfinityItemStackHandler.java @@ -30,7 +30,6 @@ public long getAmountAsLong(int index) { @Override public long getCapacityAsLong(int index, ItemResource resource) { - if (resource == null) return 0; return Integer.MAX_VALUE; } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/FilteredItemStackHandler.java b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/FilteredItemStackHandler.java index 7fa587715d..fb49ac7021 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/FilteredItemStackHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/FilteredItemStackHandler.java @@ -49,7 +49,7 @@ public class FilteredItemStackHandler extends ItemStacksResourceHandler { private NonNullList slotLimits; public NonNullList getStacks() { - return stacks; + return this.stacks; } public FilteredItemStackHandler( @@ -57,9 +57,9 @@ public FilteredItemStackHandler( super(filteredItems.size()); this.filterEnabled = filterEnabled; this.filteredItems = NonNullList.create(); - this.filteredItems.addAll(filteredItems.stream() - .map(it -> it.orElse(ItemStack.EMPTY)).toList() - ); + for (Optional filteredItem : filteredItems) { + this.filteredItems.add(filteredItem.orElse(ItemStack.EMPTY)); + } this.disabled = NonNullList.create(); this.disabled.addAll(disabled); this.slotLimits = NonNullList.create(); @@ -178,7 +178,7 @@ public boolean isEnabled(int slot) { } public boolean isEmpty() { - for (ItemStack stack : stacks) { + for (ItemStack stack : this.stacks) { if (!stack.isEmpty()) { return false; } @@ -267,12 +267,12 @@ public void deserialize(ValueInput input) { } public void serializeFiltering(ValueOutput output) { - output.store((CompoundTag) CODEC.codec().encodeStart(NbtOps.INSTANCE, this).getOrThrow()); + output.store((CompoundTag) FilteredItemStackHandler.CODEC.codec().encodeStart(NbtOps.INSTANCE, this).getOrThrow()); } public void deserializeFiltering(ValueInput input) { @SuppressWarnings("deprecation") - Optional handlerOp = input.read(CODEC); + Optional handlerOp = input.read(FilteredItemStackHandler.CODEC); if (handlerOp.isEmpty()) return; FilteredItemStackHandler handler = handlerOp.get(); if (this.size() != handler.size()) throw new IllegalArgumentException("Depository size mismatch"); diff --git a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/ItemHandlerUtil.java b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/ItemHandlerUtil.java index 09476df632..caf408b999 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/ItemHandlerUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/ItemHandlerUtil.java @@ -190,7 +190,7 @@ public static void dropAllToPos(ResourceHandler source, Level leve if (cauldron != null) { return List.of(cauldron.getInputHandler()); } - return getTargetItemHandlerList(inputBlockPos, context, level); + return ItemHandlerUtil.getTargetItemHandlerList(inputBlockPos, context, level); } public static int countItemsInHandler(ResourceHandler handler) { @@ -219,7 +219,7 @@ public static ResourceHandler getSourceItemHandlerRecursive( i++; inputPos = inputPos.relative(context.getOpposite()); } else { - return getSourceItemHandler(inputPos, context, level); + return ItemHandlerUtil.getSourceItemHandler(inputPos, context, level); } } while (i < AnvilCraft.CONFIG.blockPlacerRecursiveRetrievalDistanceMax); return null; diff --git a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/LargeCauldronInputHandler.java b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/LargeCauldronInputHandler.java index c6b241c9d8..21c24a092c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/LargeCauldronInputHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/LargeCauldronInputHandler.java @@ -24,46 +24,49 @@ public class LargeCauldronInputHandler implements ResourceHandler, private static final Codec> STACKS_CODEC = UnlimitedItemStack.OPTIONAL_CODEC.listOf(); private final Runnable changeListener; - private final NonNullList stacks = NonNullList.withSize(SLOT_COUNT, UnlimitedItemStack.EMPTY); - private final List snapshotJournals = new ArrayList<>(SLOT_COUNT); + private final NonNullList stacks = NonNullList.withSize( + LargeCauldronInputHandler.SLOT_COUNT, + UnlimitedItemStack.EMPTY + ); + private final List snapshotJournals = new ArrayList<>(LargeCauldronInputHandler.SLOT_COUNT); public LargeCauldronInputHandler(Runnable changeListener) { this.changeListener = changeListener; - for (int slot = 0; slot < SLOT_COUNT; slot++) { + for (int slot = 0; slot < LargeCauldronInputHandler.SLOT_COUNT; slot++) { this.snapshotJournals.add(new StackJournal(slot)); } } @Override public int size() { - return SLOT_COUNT; + return LargeCauldronInputHandler.SLOT_COUNT; } @Override public ItemResource getResource(int index) { - Objects.checkIndex(index, SLOT_COUNT); + Objects.checkIndex(index, LargeCauldronInputHandler.SLOT_COUNT); return ItemResource.of(this.stacks.get(index).getStack()); } @Override public long getAmountAsLong(int index) { - Objects.checkIndex(index, SLOT_COUNT); + Objects.checkIndex(index, LargeCauldronInputHandler.SLOT_COUNT); return this.stacks.get(index).count(); } @Override public long getCapacityAsLong(int index, ItemResource resource) { - Objects.checkIndex(index, SLOT_COUNT); - return resource.isEmpty() ? 0 : resource.getMaxStackSize() * STACK_MULTIPLIER; + Objects.checkIndex(index, LargeCauldronInputHandler.SLOT_COUNT); + return resource.isEmpty() ? 0 : (long) resource.getMaxStackSize() * LargeCauldronInputHandler.STACK_MULTIPLIER; } @Override public boolean isValid(int index, ItemResource resource) { - Objects.checkIndex(index, SLOT_COUNT); + Objects.checkIndex(index, LargeCauldronInputHandler.SLOT_COUNT); if (resource.isEmpty()) return false; ItemResource own = this.getResource(index); if (!own.isEmpty() && !own.equals(resource)) return false; - for (int slot = 0; slot < SLOT_COUNT; slot++) { + for (int slot = 0; slot < LargeCauldronInputHandler.SLOT_COUNT; slot++) { if (slot != index && this.getResource(slot).equals(resource)) return false; } return true; @@ -71,7 +74,7 @@ public boolean isValid(int index, ItemResource resource) { @Override public int insert(int index, ItemResource resource, int amount, TransactionContext transaction) { - Objects.checkIndex(index, SLOT_COUNT); + Objects.checkIndex(index, LargeCauldronInputHandler.SLOT_COUNT); TransferPreconditions.checkNonEmptyNonNegative(resource, amount); if (!this.isValid(index, resource)) return 0; @@ -85,7 +88,7 @@ public int insert(int index, ItemResource resource, int amount, TransactionConte @Override public int extract(int index, ItemResource resource, int amount, TransactionContext transaction) { - Objects.checkIndex(index, SLOT_COUNT); + Objects.checkIndex(index, LargeCauldronInputHandler.SLOT_COUNT); TransferPreconditions.checkNonEmptyNonNegative(resource, amount); if (!this.getResource(index).equals(resource)) return 0; @@ -104,7 +107,7 @@ public ItemStack getStackInSlot(int slot) { } public void setStackInSlot(int slot, ItemStack stack) { - Objects.checkIndex(slot, SLOT_COUNT); + Objects.checkIndex(slot, LargeCauldronInputHandler.SLOT_COUNT); ItemResource resource = ItemResource.of(stack); if (!resource.isEmpty() && !this.isValid(slot, resource)) { throw new IllegalArgumentException("Duplicate item in large cauldron input slots"); @@ -132,13 +135,13 @@ public boolean isEmpty() { @Override public void serialize(ValueOutput output) { - output.store("Items", STACKS_CODEC, this.stacks); + output.store("Items", LargeCauldronInputHandler.STACKS_CODEC, this.stacks); } @Override public void deserialize(ValueInput input) { - List loaded = input.read("Items", STACKS_CODEC).orElse(List.of()); - for (int slot = 0; slot < SLOT_COUNT; slot++) { + List loaded = input.read("Items", LargeCauldronInputHandler.STACKS_CODEC).orElse(List.of()); + for (int slot = 0; slot < LargeCauldronInputHandler.SLOT_COUNT; slot++) { UnlimitedItemStack stack = slot < loaded.size() ? loaded.get(slot) : UnlimitedItemStack.EMPTY; this.stacks.set(slot, stack.copy()); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/PollableItemHandler.java b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/PollableItemHandler.java index 0e9f98afea..2e7a7b4485 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/PollableItemHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/PollableItemHandler.java @@ -35,10 +35,10 @@ protected int getCapacityAsIntDirect(int index, ItemResource resource) { } public long getCapacityAsLongDirect(int index, ItemResource resource) { - return !resource.isEmpty() ? getCapacity(index, resource) : 0; + return !resource.isEmpty() ? this.getCapacity(index, resource) : 0; } protected ItemResource getResourceDirect(int index) { - return getResourceFrom(stacks.get(index)); + return this.getResourceFrom(this.stacks.get(index)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/SolidCauldronExtractor.java b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/SolidCauldronExtractor.java index 8b17bf29df..8967c8b453 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/SolidCauldronExtractor.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/SolidCauldronExtractor.java @@ -35,7 +35,7 @@ public BlockState getBlockState() { public static SolidCauldronExtractor get(Level level, BlockPos pos, Predicate validCauldron) { SolidCauldronExtractor.WrapperLocation location = new SolidCauldronExtractor.WrapperLocation(level, pos.immutable()); - return WRAPPERS.computeIfAbsent(location, location1 -> new SolidCauldronExtractor(validCauldron, location1)); + return SolidCauldronExtractor.WRAPPERS.computeIfAbsent(location, location1 -> new SolidCauldronExtractor(validCauldron, location1)); } private final Predicate validCauldron; diff --git a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/unlimited/SpaceSizeItemStacksResourceHandler.java b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/unlimited/SpaceSizeItemStacksResourceHandler.java index 52b65aafa8..7525df029d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/unlimited/SpaceSizeItemStacksResourceHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/itemhandler/unlimited/SpaceSizeItemStacksResourceHandler.java @@ -10,6 +10,8 @@ import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.item.ItemInstance; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; import net.neoforged.neoforge.transfer.TransferPreconditions; import net.neoforged.neoforge.transfer.item.ItemResource; import net.neoforged.neoforge.transfer.transaction.TransactionContext; @@ -47,7 +49,7 @@ public SpaceSizeItemStacksResourceHandler(int spaceSize) { public SpaceSizeItemStacksResourceHandler(int spaceSize, NonNullList stacks) { super(SpaceSizeItemStacksResourceHandler.trim(spaceSize, stacks)); - this.spaceSize = checkSpaceSize(spaceSize); + this.spaceSize = SpaceSizeItemStacksResourceHandler.checkSpaceSize(spaceSize); } public SpaceSizeItemStacksResourceHandler(NonNullList stacks, int spaceSize) { @@ -110,7 +112,7 @@ public void set(int index, ItemResource resource, int amount) { public void addSpaceSize(IntUnaryOperator adder) { int newSpaceSize = adder.applyAsInt(this.spaceSize); if (newSpaceSize >= this.spaceSize) { - this.spaceSize = checkSpaceSize(newSpaceSize); + this.spaceSize = SpaceSizeItemStacksResourceHandler.checkSpaceSize(newSpaceSize); } } @@ -141,7 +143,7 @@ public void sync(UnlimitedItemStacksResourceHandler items) { } @Override - public void serialize(net.minecraft.world.level.storage.ValueOutput output) { + public void serialize(ValueOutput output) { output.store( UnlimitedItemStacksResourceHandler.STACKS_KEY, UnlimitedItemStacksResourceHandler.STACKS_CODEC, @@ -151,15 +153,15 @@ public void serialize(net.minecraft.world.level.storage.ValueOutput output) { } @Override - public void deserialize(net.minecraft.world.level.storage.ValueInput input) { + public void deserialize(ValueInput input) { super.deserialize(input); input.getInt(SpaceSizeItemStacksResourceHandler.SPACE_SIZE_KEY) - .ifPresent(size -> this.spaceSize = checkSpaceSize(size)); + .ifPresent(size -> this.spaceSize = SpaceSizeItemStacksResourceHandler.checkSpaceSize(size)); this.setStacks(SpaceSizeItemStacksResourceHandler.trim(this.spaceSize, this.copyToList())); } private static NonNullList trim(int spaceSize, List stacks) { - checkSpaceSize(spaceSize); + SpaceSizeItemStacksResourceHandler.checkSpaceSize(spaceSize); NonNullList result = new NonNullList<>(new ArrayList<>(), UnlimitedItemStack.EMPTY); int usedSpace = 0; for (UnlimitedItemStack input : stacks) { @@ -195,11 +197,11 @@ private static NonNullList trim(int spaceSize, List= this.spaceSize) { - this.spaceSize = checkSpaceSize(newSpaceSize); + this.spaceSize = TypeLimitItemStacksResourceHandler.checkSpaceSize(newSpaceSize); } } @@ -197,7 +197,7 @@ public void serialize(ValueOutput output) { @Override public void deserialize(ValueInput input) { input.getInt(TypeLimitItemStacksResourceHandler.SPACE_SIZE_KEY) - .ifPresent(size -> this.spaceSize = Math.max(this.spaceSize, checkSpaceSize(size))); + .ifPresent(size -> this.spaceSize = Math.max(this.spaceSize, TypeLimitItemStacksResourceHandler.checkSpaceSize(size))); input.read(UnlimitedItemStacksResourceHandler.STACKS_KEY, UnlimitedItemStacksResourceHandler.STACKS_CODEC) .ifPresent(stacks -> this.setStacks( TypeLimitItemStacksResourceHandler.trim(this.typeLimit, this.spaceSize, stacks) @@ -251,15 +251,15 @@ private static NonNullList trim( int spaceSize, List stacks ) { - checkTypeLimit(typeLimit); - checkSpaceSize(spaceSize); + TypeLimitItemStacksResourceHandler.checkTypeLimit(typeLimit); + TypeLimitItemStacksResourceHandler.checkSpaceSize(spaceSize); NonNullList result = new NonNullList<>(new ArrayList<>(), UnlimitedItemStack.EMPTY); for (UnlimitedItemStack input : stacks) { if (input.isEmpty()) { continue; } - int existingIndex = findMatchingSlot(result, input); + int existingIndex = TypeLimitItemStacksResourceHandler.findMatchingSlot(result, input); if (existingIndex < 0 && result.size() >= typeLimit) { continue; } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/ConnectivityChecker.java b/src/main/java/dev/dubhe/anvilcraft/api/power/ConnectivityChecker.java index 0d489b99ef..7eac23530a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/ConnectivityChecker.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/ConnectivityChecker.java @@ -9,11 +9,11 @@ public abstract class ConnectivityChecker { private static final List instances = ObjectLists.synchronize(new ObjectArrayList<>()); public static void register(ConnectivityChecker instance) { - instances.add(instance); + ConnectivityChecker.instances.add(instance); } public static boolean check(PowerGrid powerGrid, IPowerComponent component) { - for (ConnectivityChecker it : instances) { + for (ConnectivityChecker it : ConnectivityChecker.instances) { if (it.checkInRange(powerGrid, component)) { return true; } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/DynamicPowerComponent.java b/src/main/java/dev/dubhe/anvilcraft/api/power/DynamicPowerComponent.java index 2651c38e9c..830f8cdcc2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/DynamicPowerComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/DynamicPowerComponent.java @@ -67,8 +67,14 @@ public MutableComponent getCommandDescription() { double x = this.owner.getX(); double y = this.owner.getY(); double z = this.owner.getZ(); - return Component.translatable("command.anvilcraft.powergrid.info.dynamic_consumer", - this.owner.getName(), formatDouble(x), formatDouble(y), formatDouble(z), this.getPowerConsumption()) + return Component.translatable( + "command.anvilcraft.powergrid.info.dynamic_consumer", + this.owner.getName(), + DynamicPowerComponent.formatDouble(x), + DynamicPowerComponent.formatDouble(y), + DynamicPowerComponent.formatDouble(z), + this.getPowerConsumption() + ) .withStyle(ChatFormatting.YELLOW); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerComponent.java b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerComponent.java index 967e7821b3..e52714da0d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerComponent.java @@ -71,17 +71,17 @@ public String getSerializedName() { default void flushState(Level level, BlockPos pos) { BlockState state = level.getBlockState(pos); - if (!state.hasProperty(OVERLOAD)) return; + if (!state.hasProperty(IPowerComponent.OVERLOAD)) return; if (this.getGrid() == null) { - if (!state.getValue(OVERLOAD)) { - level.setBlockAndUpdate(pos, state.setValue(OVERLOAD, true)); + if (!state.getValue(IPowerComponent.OVERLOAD)) { + level.setBlockAndUpdate(pos, state.setValue(IPowerComponent.OVERLOAD, true)); } return; } - if (this.getGrid().isWorking() && state.getValue(OVERLOAD)) { - level.setBlockAndUpdate(pos, state.setValue(OVERLOAD, false)); - } else if (!this.getGrid().isWorking() && !state.getValue(OVERLOAD)) { - level.setBlockAndUpdate(pos, state.setValue(OVERLOAD, true)); + if (this.getGrid().isWorking() && state.getValue(IPowerComponent.OVERLOAD)) { + level.setBlockAndUpdate(pos, state.setValue(IPowerComponent.OVERLOAD, false)); + } else if (!this.getGrid().isWorking() && !state.getValue(IPowerComponent.OVERLOAD)) { + level.setBlockAndUpdate(pos, state.setValue(IPowerComponent.OVERLOAD, true)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerConsumer.java b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerConsumer.java index 5e3e72c2c7..6502f056fb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerConsumer.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerConsumer.java @@ -14,13 +14,13 @@ default PowerComponentType getComponentType() { @Override default PowerComponentInfo toPowerComponentInfo() { return new PowerComponentInfo( - getPos(), + this.getPos(), this.getInputPower(), 0, 0, 0, - getRange(), - getShape(), + this.getRange(), + this.getShape(), PowerComponentType.CONSUMER ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerProducer.java b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerProducer.java index aa44961d7c..dd06bf5a3f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerProducer.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerProducer.java @@ -25,13 +25,13 @@ default PowerComponentType getComponentType() { @Override default PowerComponentInfo toPowerComponentInfo() { return new PowerComponentInfo( - getPos(), + this.getPos(), 0, this.getOutputPower(), 0, 0, - getRange(), - getShape(), + this.getRange(), + this.getShape(), PowerComponentType.PRODUCER ); } @@ -39,12 +39,12 @@ default PowerComponentInfo toPowerComponentInfo() { /// 实际电量 // @OnlyIn(Dist.CLIENT) default int getServerPower() { - Optional s = SimplePowerGrid.findPowerGrid(getPos()); + Optional s = SimplePowerGrid.findPowerGrid(this.getPos()); if (s.isPresent()) { if (s.get().getConsume() > s.get().getGenerate()) { return 0; } - Optional info = s.get().getInfoForPos(getPos()); + Optional info = s.get().getInfoForPos(this.getPos()); return info.map(powerComponentInfo -> powerComponentInfo.type() == PowerComponentType.PRODUCER ? powerComponentInfo.produces() : powerComponentInfo.consumes()) diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerStorage.java b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerStorage.java index 575879fbb8..fd29321c69 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerStorage.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerStorage.java @@ -32,13 +32,13 @@ default PowerComponentType getComponentType() { @Override default PowerComponentInfo toPowerComponentInfo() { return new PowerComponentInfo( - getPos(), + this.getPos(), 0, 0, this.getPowerAmount(), this.getCapacity(), - getRange(), - getShape(), + this.getRange(), + this.getShape(), PowerComponentType.STORAGE ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerTransmitter.java b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerTransmitter.java index 07bcfa93e5..7120c6b986 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerTransmitter.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/IPowerTransmitter.java @@ -17,13 +17,13 @@ default PowerComponentType getComponentType() { @Override default PowerComponentInfo toPowerComponentInfo() { return new PowerComponentInfo( - getPos(), + this.getPos(), 0, 0, 0, 0, this.getRange(), - getShape(), + this.getShape(), PowerComponentType.TRANSMITTER ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/PowerComponentType.java b/src/main/java/dev/dubhe/anvilcraft/api/power/PowerComponentType.java index eff97d4d25..42f17b5703 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/PowerComponentType.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/PowerComponentType.java @@ -14,6 +14,6 @@ public enum PowerComponentType implements StringRepresentable { @Override public String getSerializedName() { - return name(); + return this.name(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/PowerGrid.java b/src/main/java/dev/dubhe/anvilcraft/api/power/PowerGrid.java index 55b2b0ee39..3d847eb015 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/PowerGrid.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/PowerGrid.java @@ -105,12 +105,12 @@ public void markChanged() { /// 总电力刻 public static void tickGrid() { - MANAGER.tick(); + PowerGrid.MANAGER.tick(); } /// 电力刻 protected void tick() { - if (this.level.getGameTime() % GRID_TICK != 0) return; + if (this.level.getGameTime() % PowerGrid.GRID_TICK != 0) return; if (this.markedRemoval) return; if (this.flush()) return; if (this.isWorking()) { @@ -316,7 +316,7 @@ public void remove(IPowerComponent... components) { } PowerGrid powerGrid = new PowerGrid(this.level); powerGrid.add(group.toArray(IPowerComponent[]::new)); - MANAGER.addGrid(powerGrid); + PowerGrid.MANAGER.addGrid(powerGrid); affectedGrids.add(powerGrid); } } @@ -440,7 +440,7 @@ public boolean isInRange(IPowerComponent component) { /// @param components 元件 public static void addComponent(IPowerComponent... components) { for (IPowerComponent component : components) { - MANAGER.addComponent(component); + PowerGrid.MANAGER.addComponent(component); } } @@ -450,7 +450,7 @@ void syncToPlayer(ServerPlayer player) { public static Optional findPowerGridContains(Level level, Vec3 vec3) { Optional powerGrid = Optional.empty(); - for (PowerGrid it : MANAGER.getGridSet(level)) { + for (PowerGrid it : PowerGrid.MANAGER.getGridSet(level)) { if (it.inRangeFast(vec3)) { return Optional.of(it); } @@ -460,7 +460,7 @@ public static Optional findPowerGridContains(Level level, Vec3 vec3) public static Optional findPowerGridContains(Level level, AABB vec3) { Optional powerGrid = Optional.empty(); - for (PowerGrid it : MANAGER.getGridSet(level)) { + for (PowerGrid it : PowerGrid.MANAGER.getGridSet(level)) { if (it.collideFast(vec3)) { return Optional.of(it); } @@ -470,7 +470,7 @@ public static Optional findPowerGridContains(Level level, AABB vec3) /// 清空电网 public static void clear() { - MANAGER.clear(); + PowerGrid.MANAGER.clear(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/power/SimplePowerGrid.java b/src/main/java/dev/dubhe/anvilcraft/api/power/SimplePowerGrid.java index d6d9f2663a..650d1525a8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/power/SimplePowerGrid.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/power/SimplePowerGrid.java @@ -53,7 +53,7 @@ public class SimplePowerGrid { ); static { - recreateExecutorLimitedParallelism(); + SimplePowerGrid.recreateExecutorLimitedParallelism(); } private final Random random = new Random(); @@ -125,10 +125,10 @@ public static Optional findPowerGrid(BlockPos pos) { } public static void recreateExecutorLimitedParallelism() { - if (EXECUTOR != null) { - EXECUTOR.shutdownNow(); + if (SimplePowerGrid.EXECUTOR != null) { + SimplePowerGrid.EXECUTOR.shutdownNow(); } - EXECUTOR = Executors.newFixedThreadPool( + SimplePowerGrid.EXECUTOR = Executors.newFixedThreadPool( Math.max( Runtime.getRuntime().availableProcessors() / 4, 4 @@ -137,11 +137,14 @@ public static void recreateExecutorLimitedParallelism() { } public static SimplePowerGrid decode(FriendlyByteBuf buf) { - return CODEC.decode(NbtOps.INSTANCE, buf.readNbt().get("data")).getOrThrow().getFirst(); + CompoundTag tag = Objects.requireNonNull(buf.readNbt()); + return SimplePowerGrid.CODEC.decode(NbtOps.INSTANCE, Objects.requireNonNull(tag.get("data"))) + .getOrThrow() + .getFirst(); } public static void encode(FriendlyByteBuf buf, SimplePowerGrid grid) { - Tag tag = CODEC.encodeStart(NbtOps.INSTANCE, grid).getOrThrow(); + Tag tag = SimplePowerGrid.CODEC.encodeStart(NbtOps.INSTANCE, grid).getOrThrow(); CompoundTag data = new CompoundTag(); data.put("data", tag); buf.writeNbt(data); diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/ItemEnchantmentsData.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/ItemEnchantmentsData.java index 1cda4bca8f..86383da498 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/ItemEnchantmentsData.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/ItemEnchantmentsData.java @@ -17,6 +17,8 @@ import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.ItemEnchantments; +import java.util.Objects; + @Getter @EqualsAndHashCode public class ItemEnchantmentsData implements ICustomDataComponent { @@ -76,7 +78,7 @@ public Type getType() { @Override public ItemEnchantments make(ResultContext ctx) { - return ctx.getInput(this.input).get(this.type); + return Objects.requireNonNull(ctx.getInput(this.input).get(this.type)); } @Override @@ -107,12 +109,12 @@ public static class Type implements ICustomDataComponent.Type codec() { - return CODEC; + return Type.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return Type.STREAM_CODEC; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/MultiphaseData.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/MultiphaseData.java index 739ff5fcd9..c7cf041817 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/MultiphaseData.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/MultiphaseData.java @@ -29,7 +29,7 @@ public static MultiphaseData two() { } private static MultiphaseData fromType(String type) { - if (!TYPE.equals(type)) { + if (!MultiphaseData.TYPE.equals(type)) { throw new IllegalArgumentException("Invalid multiphase input type: " + type); } return new MultiphaseData(); @@ -71,7 +71,7 @@ public Multiphase merge(Multiphase oldData, Multiphase newData) { } private String type() { - return TYPE; + return MultiphaseData.TYPE; } public static class Type implements ICustomDataComponent.Type { @@ -84,12 +84,12 @@ public static class Type implements ICustomDataComponent.Type { @Override public MapCodec codec() { - return CODEC; + return Type.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return Type.STREAM_CODEC; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/NormalDataComponent.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/NormalDataComponent.java index 19fb5363c9..063395f697 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/NormalDataComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/data/NormalDataComponent.java @@ -12,6 +12,8 @@ import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; +import java.util.Objects; + @Getter @EqualsAndHashCode public class NormalDataComponent implements ICustomDataComponent { @@ -43,7 +45,7 @@ public Type getType() { @Override public T make(ResultContext ctx) { - return ctx.getInput(this.input).get(this.type); + return Objects.requireNonNull(ctx.getInput(this.input).get(this.type)); } @Override @@ -69,12 +71,12 @@ public static class Type implements ICustomDataComponent.Type> codec() { - return CODEC; + return Type.CODEC; } @Override public StreamCodec> streamCodec() { - return STREAM_CODEC; + return Type.STREAM_CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/BinomialDistributionGenerator.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/BinomialDistributionGenerator.java index 172c3a7809..b7e84d152d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/BinomialDistributionGenerator.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/BinomialDistributionGenerator.java @@ -51,12 +51,12 @@ public Type type() { public static class Type implements INumberProvider.Type { @Override public MapCodec codec() { - return CODEC; + return BinomialDistributionGenerator.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC.cast(); + return BinomialDistributionGenerator.STREAM_CODEC.cast(); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/ConstantValue.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/ConstantValue.java index e31cc43b2c..cbffabd1d3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/ConstantValue.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/ConstantValue.java @@ -50,12 +50,12 @@ public Type type() { public static class Type implements INumberProvider.Type { @Override public MapCodec codec() { - return CODEC; + return ConstantValue.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC.cast(); + return ConstantValue.STREAM_CODEC.cast(); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/EnchantmentLevelProvider.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/EnchantmentLevelProvider.java index 9d14e00e65..3b1225e3ce 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/EnchantmentLevelProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/EnchantmentLevelProvider.java @@ -55,12 +55,12 @@ public Type type() { public static class Type implements INumberProvider.Type { @Override public MapCodec codec() { - return CODEC; + return EnchantmentLevelProvider.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return EnchantmentLevelProvider.STREAM_CODEC; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/UniformGenerator.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/UniformGenerator.java index d184102293..ff2fc668b8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/UniformGenerator.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/number/UniformGenerator.java @@ -47,12 +47,12 @@ public Type type() { public static class Type implements INumberProvider.Type { @Override public MapCodec codec() { - return CODEC; + return UniformGenerator.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC.cast(); + return UniformGenerator.STREAM_CODEC.cast(); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/RecipeResult.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/RecipeResult.java index b84a51c2f5..0291485d96 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/RecipeResult.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/RecipeResult.java @@ -27,8 +27,10 @@ import net.minecraft.world.item.ItemStackTemplate; import net.minecraft.world.level.ItemLike; import org.jetbrains.annotations.Unmodifiable; +import org.jspecify.annotations.Nullable; import java.util.List; +import java.util.Objects; public record RecipeResult(ItemStackTemplate result, @Unmodifiable List modifiers) { public static final MapCodec DIRECT_CODEC = RecordCodecBuilder.mapCodec(ins -> ins.group( @@ -102,7 +104,7 @@ public ItemStack getResult(ResultContext ctx) { public static class Builder { private final ImmutableList.Builder modifiers = ImmutableList.builder(); - private Item result; + private @Nullable Item result; public Builder result(Item result) { this.result = result; @@ -194,7 +196,10 @@ public Builder changeDataType(RecipeInputSlot slot, DataComponentType ori } public RecipeResult build() { - return new RecipeResult(this.result, this.modifiers.build()); + return new RecipeResult( + Objects.requireNonNull(this.result, "Recipe result must be set"), + this.modifiers.build() + ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ApplyData.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ApplyData.java index 2cf109b468..43ce729d7e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ApplyData.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ApplyData.java @@ -37,12 +37,12 @@ public Type type() { public static class Type implements IResultModifier.Type { @Override public MapCodec codec() { - return CODEC; + return ApplyData.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return ApplyData.STREAM_CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ChangeDataType.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ChangeDataType.java index e258108032..6fc071b1e2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ChangeDataType.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ChangeDataType.java @@ -15,6 +15,8 @@ import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.Identifier; +import java.util.Objects; + /// 复制指定输入物品的数据,并将其粘贴到另一个数据组件类型下。 public record ChangeDataType(RecipeInputSlot input, DataComponentType orig, ICustomDataComponent dest) implements IResultModifier { public static final MapCodec> CODEC = RecordCodecBuilder.mapCodec(ins -> ins.group( @@ -40,7 +42,10 @@ public record ChangeDataType(RecipeInputSlot input, DataComponentType orig public ChangeDataType(Identifier origId, ICustomDataComponent dest, RecipeInputSlot slot) { this( slot, - Util.cast(BuiltInRegistries.DATA_COMPONENT_TYPE.getValue(origId)), + Util.cast(Objects.requireNonNull( + BuiltInRegistries.DATA_COMPONENT_TYPE.getValue(origId), + "Unknown data component: " + origId + )), dest ); } @@ -58,9 +63,10 @@ public void modify(ResultContext ctx) { T value = ctx.getInput(this.input).get(this.orig); if (value == null) return; ctx.getResult().set(this.orig, null); + T oldValue = ctx.getResult().get(this.dest.getDataComponentType()); ctx.getResult().set( this.dest.getDataComponentType(), - this.dest.merge(ctx.getResult().get(this.dest.getDataComponentType()), value) + oldValue == null ? value : this.dest.merge(oldValue, value) ); } @@ -70,18 +76,21 @@ public Type type() { } private Identifier origId() { - return BuiltInRegistries.DATA_COMPONENT_TYPE.getKey(this.orig); + return Objects.requireNonNull( + BuiltInRegistries.DATA_COMPONENT_TYPE.getKey(this.orig), + "Unregistered data component: " + this.orig + ); } public static class Type implements IResultModifier.Type> { @Override public MapCodec> codec() { - return CODEC; + return ChangeDataType.CODEC; } @Override public StreamCodec> streamCodec() { - return STREAM_CODEC; + return ChangeDataType.STREAM_CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/CopyData.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/CopyData.java index e34b577cb2..149ab69582 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/CopyData.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/CopyData.java @@ -53,12 +53,12 @@ private static void wrappedMake(ResultContext ctx, ICustomDataComponent t public static class Type implements IResultModifier.Type { @Override public MapCodec codec() { - return CODEC; + return CopyData.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return CopyData.STREAM_CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/MergeData.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/MergeData.java index 4b9b599564..b521979725 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/MergeData.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/MergeData.java @@ -63,12 +63,12 @@ private static void wrappedMake(ResultContext ctx, ICustomDataComponent t public static class Type implements IResultModifier.Type { @Override public MapCodec codec() { - return CODEC; + return MergeData.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return MergeData.STREAM_CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ModifyCount.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ModifyCount.java index 1d30703ada..70bd32245f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ModifyCount.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/ModifyCount.java @@ -8,6 +8,9 @@ import dev.dubhe.anvilcraft.init.recipe.ModResultModifierTypes; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; public record ModifyCount(INumberProvider count) implements IResultModifier { public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(ins -> ins.group( @@ -38,17 +41,17 @@ public Type type() { public static class Type implements IResultModifier.Type { @Override public MapCodec codec() { - return CODEC; + return ModifyCount.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return ModifyCount.STREAM_CODEC; } } public static class Builder { - private INumberProvider count; + private @Nullable INumberProvider count; public Builder() { } @@ -59,8 +62,7 @@ public Builder count(int count) { } public ModifyCount build() { - if (this.count == null) throw new IllegalArgumentException("The count in ModifyCount should not be null!"); - return new ModifyCount(this.count); + return new ModifyCount(Objects.requireNonNull(this.count, "The count in ModifyCount should not be null!")); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveAttribute.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveAttribute.java index 61b56d66b1..15f4b01851 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveAttribute.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveAttribute.java @@ -55,12 +55,12 @@ public Type type() { public static class Type implements IResultModifier.Type { @Override public MapCodec codec() { - return CODEC; + return RemoveAttribute.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return RemoveAttribute.STREAM_CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveData.java b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveData.java index 44aa9b67c9..5009c7a150 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveData.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/recipe/result/modifier/RemoveData.java @@ -51,12 +51,12 @@ public Type type() { public static class Type implements IResultModifier.Type { @Override public MapCodec codec() { - return CODEC; + return RemoveData.CODEC; } @Override public StreamCodec streamCodec() { - return STREAM_CODEC; + return RemoveData.STREAM_CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/rendering/WrappedBlockStateModel.java b/src/main/java/dev/dubhe/anvilcraft/api/rendering/WrappedBlockStateModel.java index 48c6dfa0e2..1b8b37870c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/rendering/WrappedBlockStateModel.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/rendering/WrappedBlockStateModel.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; +import java.util.Objects; @NullMarked public class WrappedBlockStateModel extends Model { @@ -26,7 +27,7 @@ public class WrappedBlockStateModel extends Model key = this.state.key(); ModelBlockRenderer tessellator = this.renderer.getTessellatorNoLighting(); - BlockStateModel model = mc.getModelManager().getStandaloneModel(key); + BlockStateModel model = Objects.requireNonNull( + mc.getModelManager().getStandaloneModel(key), + "Missing standalone block model: " + key + ); tessellator.tesselateBlock( ((_, _, _, bakedQuad, quadInstance) -> { diff --git a/src/main/java/dev/dubhe/anvilcraft/api/rendering/package-info.java b/src/main/java/dev/dubhe/anvilcraft/api/rendering/package-info.java new file mode 100644 index 0000000000..b494ecfbef --- /dev/null +++ b/src/main/java/dev/dubhe/anvilcraft/api/rendering/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package dev.dubhe.anvilcraft.api.rendering; + +import org.jspecify.annotations.NullMarked; diff --git a/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockInfo.java b/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockInfo.java index dd1993bfc0..88ce6e89cd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockInfo.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockInfo.java @@ -31,24 +31,24 @@ public record SlidingBlockInfo(Vec3i offset, BlockState state, @Nullable BlockEntity blockEntity) { public static final MapCodec CODEC = new MapCodec<>() { - private static final MapCodec OFFSET = Vec3i.CODEC.fieldOf("offset"); - private static final MapCodec STATE = BlockState.CODEC.fieldOf("state"); - private static final MapCodec ENTITY_DATA = CompoundTag.CODEC.fieldOf("entity_data"); + private final MapCodec offsetCodec = Vec3i.CODEC.fieldOf("offset"); + private final MapCodec stateCodec = BlockState.CODEC.fieldOf("state"); + private final MapCodec entityDataCodec = CompoundTag.CODEC.fieldOf("entity_data"); @Override public RecordBuilder encode(SlidingBlockInfo input, DynamicOps ops, RecordBuilder prefix) { - OFFSET.encode(input.offset, ops, prefix); - STATE.encode(input.state, ops, prefix); - ENTITY_DATA.encode(input.beTag(), ops, prefix); + this.offsetCodec.encode(input.offset, ops, prefix); + this.stateCodec.encode(input.state, ops, prefix); + this.entityDataCodec.encode(input.beTag(), ops, prefix); return prefix; } @Override public DataResult decode(DynamicOps ops, MapLike input) { - Vec3i offset = OFFSET.decode(ops, input).getOrThrow(); - BlockState state = STATE.decode(ops, input).getOrThrow(); + Vec3i offset = this.offsetCodec.decode(ops, input).getOrThrow(); + BlockState state = this.stateCodec.decode(ops, input).getOrThrow(); - DataResult entityData = ENTITY_DATA.decode(ops, input); + DataResult entityData = this.entityDataCodec.decode(ops, input); if (entityData.isError()) { return DataResult.error(() -> "No valid entity data", new SlidingBlockInfo(offset, state)); } @@ -64,7 +64,9 @@ public DataResult decode(DynamicOps ops, MapLike inp @Override public Stream keys(DynamicOps ops) { - return Streams.concat(OFFSET.keys(ops), STATE.keys(ops), ENTITY_DATA.keys(ops)); + return Streams.concat( + this.offsetCodec.keys(ops), this.stateCodec.keys(ops), this.entityDataCodec.keys(ops) + ); } }; public static final StreamCodec STREAM_CODEC = StreamCodec.of( diff --git a/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockStructureResolver.java b/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockStructureResolver.java index 188a448cef..e23bb0cafe 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockStructureResolver.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/sliding/SlidingBlockStructureResolver.java @@ -81,7 +81,7 @@ private boolean addBlockLine(BlockPos originPos, Direction direction) { } int toPushSize = 1; - if (toPushSize + this.toPush.size() > MAX_PUSH_DEPTH) return false; + if (toPushSize + this.toPush.size() > SlidingBlockStructureResolver.MAX_PUSH_DEPTH) return false; BlockState oldState; while (nowState.isStickyBlock()) { @@ -99,7 +99,7 @@ private boolean addBlockLine(BlockPos originPos, Direction direction) { break; } - if (++toPushSize + this.toPush.size() > MAX_PUSH_DEPTH) return false; + if (++toPushSize + this.toPush.size() > SlidingBlockStructureResolver.MAX_PUSH_DEPTH) return false; } int addedCount = 0; @@ -143,7 +143,7 @@ private boolean addBlockLine(BlockPos originPos, Direction direction) { return true; } - if (this.toPush.size() >= MAX_PUSH_DEPTH) return false; + if (this.toPush.size() >= SlidingBlockStructureResolver.MAX_PUSH_DEPTH) return false; this.toPush.add(addingPos); addedCount++; diff --git a/src/main/java/dev/dubhe/anvilcraft/api/teslatower/IsEntityIdFilter.java b/src/main/java/dev/dubhe/anvilcraft/api/teslatower/IsEntityIdFilter.java index 32abe8cebd..368e19cb4a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/teslatower/IsEntityIdFilter.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/teslatower/IsEntityIdFilter.java @@ -4,7 +4,6 @@ import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.resources.Identifier; -import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.LivingEntity; public class IsEntityIdFilter extends TeslaFilter { @@ -45,4 +44,4 @@ public Component getTitle(String arg) { public String tooltip(String arg) { return Component.translatable("screen.anvilcraft.tesla_tower.filter.is_entity_id").getString(); } -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/api/teslatower/TeslaFilter.java b/src/main/java/dev/dubhe/anvilcraft/api/teslatower/TeslaFilter.java index 9bd1fa7af4..1ed150d305 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/teslatower/TeslaFilter.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/teslatower/TeslaFilter.java @@ -33,15 +33,15 @@ public Component title() { private static final HashMap FILTER_MAP = new HashMap<>(); public static void register(TeslaFilter filter) { - FILTER_MAP.put(filter.getId(), filter); + TeslaFilter.FILTER_MAP.put(filter.getId(), filter); } public static TeslaFilter getFilter(String id) { - return FILTER_MAP.getOrDefault(id, emptyFilter); + return TeslaFilter.FILTER_MAP.getOrDefault(id, TeslaFilter.emptyFilter); } public static Collection all() { - return FILTER_MAP.values(); + return TeslaFilter.FILTER_MAP.values(); } public abstract String getId(); @@ -63,16 +63,16 @@ public String tooltip(String arg) { } public static void init() { - FILTER_MAP.clear(); - register(new IsPlayerFilter()); - register(new IsPlayerIdFilter()); - register(new IsPetFilter()); - register(new IsOnVehicleFilter()); - register(new IsFriendlyFilter()); - register(new IsHostileFilter()); - register(new IsNeutralFilter()); - register(new IsEntityIdFilter()); - register(new IsBabyFriendlyFilter()); - register(new HasCustomNameFilter()); + TeslaFilter.FILTER_MAP.clear(); + TeslaFilter.register(new IsPlayerFilter()); + TeslaFilter.register(new IsPlayerIdFilter()); + TeslaFilter.register(new IsPetFilter()); + TeslaFilter.register(new IsOnVehicleFilter()); + TeslaFilter.register(new IsFriendlyFilter()); + TeslaFilter.register(new IsHostileFilter()); + TeslaFilter.register(new IsNeutralFilter()); + TeslaFilter.register(new IsEntityIdFilter()); + TeslaFilter.register(new IsBabyFriendlyFilter()); + TeslaFilter.register(new HasCustomNameFilter()); } -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/FluidTankItemTooltip.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/FluidTankItemTooltip.java index 3aeb00325f..f8d22071ea 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/FluidTankItemTooltip.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/FluidTankItemTooltip.java @@ -35,9 +35,9 @@ public static void appendFixedTank( Consumer tooltip, int capacity ) { - CompoundTag tankTag = getTankTag(stack); - List fluids = readSingleFluid(tankTag, context.registries(), capacity); - append(tooltip, fluids, totalAmount(fluids), capacity, false); + CompoundTag tankTag = FluidTankItemTooltip.getTankTag(stack); + List fluids = FluidTankItemTooltip.readSingleFluid(tankTag, context.registries(), capacity); + FluidTankItemTooltip.append(tooltip, fluids, FluidTankItemTooltip.totalAmount(fluids), capacity, false); } /// 可被门格海绵扩容的单流体储罐 @@ -48,15 +48,15 @@ public static void appendExpandableTank( int baseCapacity, int enhancedCapacity ) { - CompoundTag tankTag = getTankTag(stack); - boolean enhanced = tankTag.getBooleanOr(TAG_ENHANCED, false); - boolean infinite = enhanced && tankTag.getBooleanOr(TAG_INFINITE, false); + CompoundTag tankTag = FluidTankItemTooltip.getTankTag(stack); + boolean enhanced = tankTag.getBooleanOr(FluidTankItemTooltip.TAG_ENHANCED, false); + boolean infinite = enhanced && tankTag.getBooleanOr(FluidTankItemTooltip.TAG_INFINITE, false); int capacity = enhanced ? enhancedCapacity : baseCapacity; - List fluids = readSingleFluid(tankTag, context.registries(), Integer.MAX_VALUE); + List fluids = FluidTankItemTooltip.readSingleFluid(tankTag, context.registries(), Integer.MAX_VALUE); if (infinite && !fluids.isEmpty()) { fluids.set(0, new TooltipFluid(fluids.getFirst().fluid(), true)); } - append(tooltip, fluids, totalAmount(fluids), capacity, infinite); + FluidTankItemTooltip.append(tooltip, fluids, FluidTankItemTooltip.totalAmount(fluids), capacity, infinite); } /// 可同时存放多种流体的大型储罐 @@ -66,23 +66,29 @@ public static void appendMultiTank( Consumer tooltip, int capacity ) { - CompoundTag tankTag = getTankTag(stack); - List fluids = readMultipleFluids(tankTag, context.registries()); - append(tooltip, fluids, totalAmount(fluids), capacity, tankTag.getBooleanOr(TAG_ENHANCED, false)); + CompoundTag tankTag = FluidTankItemTooltip.getTankTag(stack); + List fluids = FluidTankItemTooltip.readMultipleFluids(tankTag, context.registries()); + FluidTankItemTooltip.append( + tooltip, + fluids, + FluidTankItemTooltip.totalAmount(fluids), + capacity, + tankTag.getBooleanOr(FluidTankItemTooltip.TAG_ENHANCED, false) + ); } /// 读出单罐物品中的流体与是否已扩容,供物品渲染复用 public static @Nullable SingleTankData readSingleTank(ItemStack stack) { - CompoundTag tankTag = getTankTag(stack); - FluidStack fluid = readFluid(tankTag); + CompoundTag tankTag = FluidTankItemTooltip.getTankTag(stack); + FluidStack fluid = FluidTankItemTooltip.readFluid(tankTag); if (fluid.isEmpty()) return null; - return new SingleTankData(fluid, tankTag.getBooleanOr(TAG_ENHANCED, false)); + return new SingleTankData(fluid, tankTag.getBooleanOr(FluidTankItemTooltip.TAG_ENHANCED, false)); } /// 读出大型储罐物品中的所有流体,供物品渲染复用 public static List readMultiTankFluids(ItemStack stack) { List fluids = new ArrayList<>(); - for (TooltipFluid stored : readMultipleFluids(getTankTag(stack), null)) { + for (TooltipFluid stored : FluidTankItemTooltip.readMultipleFluids(FluidTankItemTooltip.getTankTag(stack), null)) { fluids.add(stored.fluid()); } return fluids; @@ -90,17 +96,17 @@ public static List readMultiTankFluids(ItemStack stack) { /// 大型储罐物品是否处于扩容状态 public static boolean isMultiTankEnhanced(ItemStack stack) { - return getTankTag(stack).getBooleanOr(TAG_ENHANCED, false); + return FluidTankItemTooltip.getTankTag(stack).getBooleanOr(FluidTankItemTooltip.TAG_ENHANCED, false); } private static CompoundTag getTankTag(ItemStack stack) { TypedEntityData data = stack.get(DataComponents.BLOCK_ENTITY_DATA); if (data == null) return new CompoundTag(); - return data.copyTagWithoutId().getCompoundOrEmpty(TAG_TANK); + return data.copyTagWithoutId().getCompoundOrEmpty(FluidTankItemTooltip.TAG_TANK); } private static FluidStack readFluid(CompoundTag tag) { - return tag.read(TAG_FLUID, FluidStack.OPTIONAL_CODEC).orElse(FluidStack.EMPTY); + return tag.read(FluidTankItemTooltip.TAG_FLUID, FluidStack.OPTIONAL_CODEC).orElse(FluidStack.EMPTY); } private static List readSingleFluid( @@ -108,7 +114,7 @@ private static List readSingleFluid( HolderLookup.@Nullable Provider registries, int capacity ) { - FluidStack fluid = readFluid(tankTag); + FluidStack fluid = FluidTankItemTooltip.readFluid(tankTag); if (fluid.isEmpty()) return new ArrayList<>(); int amount = Math.min(fluid.getAmount(), capacity); return new ArrayList<>(List.of(new TooltipFluid(fluid.copyWithAmount(amount), false))); @@ -119,16 +125,16 @@ private static List readMultipleFluids( HolderLookup.@Nullable Provider registries ) { List fluids = new ArrayList<>(); - boolean enhanced = tankTag.getBooleanOr(TAG_ENHANCED, false); - ListTag fluidsTag = tankTag.getListOrEmpty(TAG_FLUIDS); + boolean enhanced = tankTag.getBooleanOr(FluidTankItemTooltip.TAG_ENHANCED, false); + ListTag fluidsTag = tankTag.getListOrEmpty(FluidTankItemTooltip.TAG_FLUIDS); for (int i = 0; i < fluidsTag.size(); i++) { CompoundTag storedFluidTag = fluidsTag.getCompound(i).orElse(null); if (storedFluidTag == null) continue; - FluidStack fluid = readFluid(storedFluidTag); + FluidStack fluid = FluidTankItemTooltip.readFluid(storedFluidTag); if (!fluid.isEmpty()) { fluids.add(new TooltipFluid( fluid, - enhanced && storedFluidTag.getBooleanOr(TAG_INFINITE, false) + enhanced && storedFluidTag.getBooleanOr(FluidTankItemTooltip.TAG_INFINITE, false) )); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/HudTooltipManager.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/HudTooltipManager.java index 0375892511..d7c5c3b440 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/HudTooltipManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/HudTooltipManager.java @@ -59,31 +59,31 @@ public class HudTooltipManager { private final List handItemProviders = new ArrayList<>(); static { - INSTANCE.registerBlockEntityTooltip(new ChargerTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new DischargerTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new HeatCollectorTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new PowerComponentTooltipProvider()); - INSTANCE.registerAffectRange(new AffectRangeProviderImpl()); - INSTANCE.registerBlockEntityTooltip(new RubyPrismTooltipProvider()); - INSTANCE.registerHandHeldItemTooltip(new HeliostatsTooltip()); - INSTANCE.registerBlockEntityTooltip(new HeliostatsTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new SpaceOvercompressorTooltipProvider()); - INSTANCE.registerHandHeldItemTooltip(ModItems.STRUCTURE_TOOL.get()); - INSTANCE.registerBlockTooltip(new InjectedBlockTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new InjectedBlockEntityTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new HeatableBlockTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new BurningHeaterTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new DeflectionRingTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new PropelPistonTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new LargeCauldronTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new CfaLogisticsInterfaceTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new CfaLaserInterfaceTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new CfaFluidInterfaceTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new PulseGeneratorTooltipProvider()); - INSTANCE.registerBlockTooltip(new RedstoneWireTooltipProvider()); - INSTANCE.registerBlockTooltip(new CrabTrapTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new LargeCrateTooltipProvider()); - INSTANCE.registerBlockEntityTooltip(new ShulkerContainerTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new ChargerTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new DischargerTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new HeatCollectorTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new PowerComponentTooltipProvider()); + HudTooltipManager.INSTANCE.registerAffectRange(new AffectRangeProviderImpl()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new RubyPrismTooltipProvider()); + HudTooltipManager.INSTANCE.registerHandHeldItemTooltip(new HeliostatsTooltip()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new HeliostatsTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new SpaceOvercompressorTooltipProvider()); + HudTooltipManager.INSTANCE.registerHandHeldItemTooltip(ModItems.STRUCTURE_TOOL.get()); + HudTooltipManager.INSTANCE.registerBlockTooltip(new InjectedBlockTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new InjectedBlockEntityTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new HeatableBlockTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new BurningHeaterTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new DeflectionRingTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new PropelPistonTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new LargeCauldronTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new CfaLogisticsInterfaceTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new CfaLaserInterfaceTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new CfaFluidInterfaceTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new PulseGeneratorTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockTooltip(new RedstoneWireTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockTooltip(new CrabTrapTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new LargeCrateTooltipProvider()); + HudTooltipManager.INSTANCE.registerBlockEntityTooltip(new ShulkerContainerTooltipProvider()); } public void registerAffectRange(AffectRangeProviderImpl affectRangeProvider) { @@ -126,9 +126,9 @@ public void renderTooltip( tooltip, tooltipPosX, tooltipPosY, - BACKGROUND_COLOR, - BORDER_COLOR_TOP, - BORDER_COLOR_BOTTOM + HudTooltipManager.BACKGROUND_COLOR, + HudTooltipManager.BORDER_COLOR_TOP, + HudTooltipManager.BORDER_COLOR_BOTTOM ); } @@ -154,9 +154,9 @@ public void renderTooltip( tooltip, tooltipPosX, tooltipPosY, - BACKGROUND_COLOR, - BORDER_COLOR_TOP, - BORDER_COLOR_BOTTOM + HudTooltipManager.BACKGROUND_COLOR, + HudTooltipManager.BORDER_COLOR_TOP, + HudTooltipManager.BORDER_COLOR_BOTTOM ); } @@ -220,7 +220,7 @@ public void renderAffectRange( private ITooltipProvider.@Nullable BlockEntityTooltipProvider determineBlockEntityTooltipProvider(BlockEntity entity) { return this.blockEntityProviders.stream() .filter(it -> it.accepts(entity)) - .filter(it -> !shouldSuppressForJade(it)) + .filter(it -> !HudTooltipManager.shouldSuppressForJade(it)) .min(Comparator.comparingInt(ITooltipProvider::priority)) .orElse(null); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/ItemTooltipManager.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/ItemTooltipManager.java index ad1d193620..8d936ad4ba 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/ItemTooltipManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/ItemTooltipManager.java @@ -27,358 +27,358 @@ public class ItemTooltipManager { private static final Map SHIFT = Maps.newHashMap(); static { - NORMAL.put(ModItems.MAGNET.get(), "Attract surrounding items when use"); - NORMAL.put(ModItems.GEODE.get(), "Find the surrounding Amethyst Geode when using it"); - NORMAL.put(ModItems.ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); - NORMAL.put(ModItems.ROYAL_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); - NORMAL.put(ModItems.EMBER_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); - NORMAL.put(ModItems.FROST_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); - NORMAL.put(ModItems.TRANSCENDENCE_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); - NORMAL.put(ModBlocks.CURSED_GOLD_BLOCK.asItem(), "Carriers will be cursed"); - NORMAL.put(ModItems.CURSED_GOLD_INGOT.get(), "Carriers will be cursed"); - NORMAL.put(ModItems.CURSED_GOLD_NUGGET.get(), "Carriers will be cursed"); - NORMAL.put(ModItems.TOPAZ.get(), "Containing the power of lightning"); - NORMAL.put(ModItems.RUBY.get(), "Containing the power of fire"); - NORMAL.put(ModItems.SAPPHIRE.get(), "Containing the power of frost"); - NORMAL.put(ModBlocks.RESIN_BLOCK.asItem(), "Use to capture friendly or weak hostile creatures LivingEntity"); - NORMAL.put(ModBlocks.CRAB_TRAP.asItem(), "Placing it in the water to help you catch aquatic products"); - NORMAL.put(ModItems.CRAB_CLAW.get(), "Increase touch length when holding"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModItems.MAGNET.get(), "Attract surrounding items when use"); + ItemTooltipManager.NORMAL.put(ModItems.GEODE.get(), "Find the surrounding Amethyst Geode when using it"); + ItemTooltipManager.NORMAL.put(ModItems.ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); + ItemTooltipManager.NORMAL.put(ModItems.ROYAL_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); + ItemTooltipManager.NORMAL.put(ModItems.EMBER_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); + ItemTooltipManager.NORMAL.put(ModItems.FROST_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); + ItemTooltipManager.NORMAL.put(ModItems.TRANSCENDENCE_ANVIL_HAMMER.get(), "It's a hammer, an anvil, a wrench, goggles, and a mace"); + ItemTooltipManager.NORMAL.put(ModBlocks.CURSED_GOLD_BLOCK.asItem(), "Carriers will be cursed"); + ItemTooltipManager.NORMAL.put(ModItems.CURSED_GOLD_INGOT.get(), "Carriers will be cursed"); + ItemTooltipManager.NORMAL.put(ModItems.CURSED_GOLD_NUGGET.get(), "Carriers will be cursed"); + ItemTooltipManager.NORMAL.put(ModItems.TOPAZ.get(), "Containing the power of lightning"); + ItemTooltipManager.NORMAL.put(ModItems.RUBY.get(), "Containing the power of fire"); + ItemTooltipManager.NORMAL.put(ModItems.SAPPHIRE.get(), "Containing the power of frost"); + ItemTooltipManager.NORMAL.put(ModBlocks.RESIN_BLOCK.asItem(), "Use to capture friendly or weak hostile creatures LivingEntity"); + ItemTooltipManager.NORMAL.put(ModBlocks.CRAB_TRAP.asItem(), "Placing it in the water to help you catch aquatic products"); + ItemTooltipManager.NORMAL.put(ModItems.CRAB_CLAW.get(), "Increase touch length when holding"); + ItemTooltipManager.NORMAL.put( ModBlocks.ROYAL_ANVIL.asItem(), """ Never triggers Too Expensive Explosion proof, does not degrade from falling"""); - NORMAL.put(ModBlocks.ROYAL_GRINDSTONE.asItem(), "Removes curses and enchantment penalties, Explosion proof"); - NORMAL.put(ModBlocks.ROYAL_SMITHING_TABLE.asItem(), "Does not consume Smithing Templates, Explosion proof"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.ROYAL_GRINDSTONE.asItem(), "Removes curses and enchantment penalties, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.ROYAL_SMITHING_TABLE.asItem(), "Does not consume Smithing Templates, Explosion proof"); + ItemTooltipManager.NORMAL.put( ModBlocks.TRANSCENDENCE_SMITHING_TABLE.asItem(), "Performs all smithing operations without physical templates\nExplosion, Wither and Ender Dragon proof" ); - NORMAL.put(ModBlocks.HEATER.asItem(), "Heating the block above, consumes 16 kW"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.HEATER.asItem(), "Heating the block above, consumes 16 kW"); + ItemTooltipManager.NORMAL.put( ModBlocks.BURNING_HEATER.asItem(), """ Consume fuel to heat the block above Each crafting consumes 240 seconds of burn time""" ); - NORMAL.put(ModBlocks.TRANSMISSION_POLE.asItem(), "Build a power grid with a transmission length of 8"); - NORMAL.put(ModBlocks.CHARGE_COLLECTOR.asItem(), "Collecting charges to generate power"); - NORMAL.put(ModBlocks.FE_COLLECTOR.asItem(), "Collecting FE to generate power"); - NORMAL.put(ModBlocks.POWER_CONVERTER_SMALL.asItem(), "Convert power into FE, consumes 1 kW"); - NORMAL.put(ModBlocks.POWER_CONVERTER_MIDDLE.asItem(), "Convert power into FE, consumes 16 kW"); - NORMAL.put(ModBlocks.POWER_CONVERTER_BIG.asItem(), "Convert power into FE, consumes 256 kW"); - NORMAL.put(ModBlocks.PIEZOELECTRIC_CRYSTAL.asItem(), "Charge generated by an anvil fall on it"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.TRANSMISSION_POLE.asItem(), "Build a power grid with a transmission length of 8"); + ItemTooltipManager.NORMAL.put(ModBlocks.CHARGE_COLLECTOR.asItem(), "Collecting charges to generate power"); + ItemTooltipManager.NORMAL.put(ModBlocks.FE_COLLECTOR.asItem(), "Collecting FE to generate power"); + ItemTooltipManager.NORMAL.put(ModBlocks.POWER_CONVERTER_SMALL.asItem(), "Convert power into FE, consumes 1 kW"); + ItemTooltipManager.NORMAL.put(ModBlocks.POWER_CONVERTER_MIDDLE.asItem(), "Convert power into FE, consumes 16 kW"); + ItemTooltipManager.NORMAL.put(ModBlocks.POWER_CONVERTER_BIG.asItem(), "Convert power into FE, consumes 256 kW"); + ItemTooltipManager.NORMAL.put(ModBlocks.PIEZOELECTRIC_CRYSTAL.asItem(), "Charge generated by an anvil fall on it"); + ItemTooltipManager.NORMAL.put( ModBlocks.MAGNET_BLOCK.asItem(), "Attracting the anvil below, when pushed and pulled by the piston, causes adjacent copper blocks to generate charges" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.HOLLOW_MAGNET_BLOCK.asItem(), "Attracting the anvil below, when pushed and pulled by the piston, causes adjacent copper blocks to generate charges" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.FERRITE_CORE_MAGNET_BLOCK.asItem(), "Attracting the anvil below, when pushed and pulled by the piston, causes adjacent copper blocks to generate charges" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.BATCH_CRAFTER.asItem(), "Received a redstone signal and crafted all internal items at once, with a power consumption of 4 kW" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.BATCH_CUTTER.asItem(), "Received a redstone signal and cut all internal items at once, with a power consumption of 4 kW" ); - NORMAL.put(ModItems.ROYAL_STEEL_INGOT.get(), "A piece of iron infused with gem magic"); - NORMAL.put(ModBlocks.ROYAL_STEEL_BLOCK.asItem(), "A large block of iron infused with gem magic, Explosion proof"); - NORMAL.put(ModBlocks.SMOOTH_ROYAL_STEEL_BLOCK.asItem(), "Royal Steel decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_BLOCK.asItem(), "Royal Steel decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_PILLAR.asItem(), "Royal Steel decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_STAIRS.asItem(), "Royal Steel decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_SLAB.asItem(), "Royal Steel decorative block, Explosion proof"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModItems.ROYAL_STEEL_INGOT.get(), "A piece of iron infused with gem magic"); + ItemTooltipManager.NORMAL.put(ModBlocks.ROYAL_STEEL_BLOCK.asItem(), "A large block of iron infused with gem magic, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.SMOOTH_ROYAL_STEEL_BLOCK.asItem(), "Royal Steel decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_BLOCK.asItem(), "Royal Steel decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_PILLAR.asItem(), "Royal Steel decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_STAIRS.asItem(), "Royal Steel decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_ROYAL_STEEL_SLAB.asItem(), "Royal Steel decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put( ModBlocks.TEMPERING_GLASS.asItem(), "Royal Steel glass, Explosion proof, No tools required on collect" ); - NORMAL.put(ModBlocks.REMOTE_TRANSMISSION_POLE.asItem(), "Build a power grid with a transmission length of 16"); - NORMAL.put(ModBlocks.HEAVY_IRON_BLOCK.asItem(), "Heavy Iron block, highly compressed iron, Explosion proof"); - NORMAL.put(ModBlocks.POLISHED_HEAVY_IRON_BLOCK.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.POLISHED_HEAVY_IRON_SLAB.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.POLISHED_HEAVY_IRON_STAIRS.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_HEAVY_IRON_BLOCK.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_HEAVY_IRON_SLAB.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_HEAVY_IRON_STAIRS.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.HEAVY_IRON_PLATE.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.HEAVY_IRON_COLUMN.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.HEAVY_IRON_BEAM.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.HEAVY_IRON_WALL.asItem(), "Heavy Iron decorative block, Explosion proof"); - NORMAL.put(ModBlocks.HEAVY_IRON_DOOR.asItem(), "Heavy Iron door, Explosion proof"); - NORMAL.put(ModBlocks.HEAVY_IRON_TRAPDOOR.asItem(), "Heavy Iron trapdoor, Explosion proof"); - NORMAL.put(ModBlocks.ITEM_COLLECTOR.asItem(), "Adjust power consumption based on range and cooling, from 2kW to 32kW"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.REMOTE_TRANSMISSION_POLE.asItem(), "Build a power grid with a transmission length of 16"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAVY_IRON_BLOCK.asItem(), "Heavy Iron block, highly compressed iron, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.POLISHED_HEAVY_IRON_BLOCK.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.POLISHED_HEAVY_IRON_SLAB.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.POLISHED_HEAVY_IRON_STAIRS.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_HEAVY_IRON_BLOCK.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_HEAVY_IRON_SLAB.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_HEAVY_IRON_STAIRS.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAVY_IRON_PLATE.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAVY_IRON_COLUMN.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAVY_IRON_BEAM.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAVY_IRON_WALL.asItem(), "Heavy Iron decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAVY_IRON_DOOR.asItem(), "Heavy Iron door, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAVY_IRON_TRAPDOOR.asItem(), "Heavy Iron trapdoor, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.ITEM_COLLECTOR.asItem(), "Adjust power consumption based on range and cooling, from 2kW to 32kW"); + ItemTooltipManager.NORMAL.put( ModBlocks.EMBER_ANVIL.asItem(), """ Enhanced compatibility with a soul seemingly hidden deep within Anvil Looting can obtain player-only drops Wither proof, does not degrade from falling"""); - NORMAL.put(ModBlocks.EMBER_GRINDSTONE.asItem(), "Extracts enchantments onto books, Wither proof"); - NORMAL.put(ModBlocks.EMBER_SMITHING_TABLE.asItem(), "All-in-one combination smithing, Wither proof"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.EMBER_GRINDSTONE.asItem(), "Extracts enchantments onto books, Wither proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.EMBER_SMITHING_TABLE.asItem(), "All-in-one combination smithing, Wither proof"); + ItemTooltipManager.NORMAL.put( ModBlocks.EMBER_METAL_BLOCK.asItem(), "A large block of heat-resistant Netherite tempered in fire for eons, Wither proof" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.EMBER_GLASS.asItem(), "Ember Metal glass, Wither proof, No tools required on collect" ); - NORMAL.put(ModBlocks.CUT_EMBER_METAL_BLOCK.asItem(), "Ember Metal decorative block, Wither proof"); - NORMAL.put(ModBlocks.CUT_EMBER_METAL_PILLAR.asItem(), "Ember Metal decorative block, Wither proof"); - NORMAL.put(ModBlocks.CUT_EMBER_METAL_SLAB.asItem(), "Ember Metal decorative block, Wither proof"); - NORMAL.put(ModBlocks.CUT_EMBER_METAL_STAIRS.asItem(), "Ember Metal decorative block, Wither proof"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_EMBER_METAL_BLOCK.asItem(), "Ember Metal decorative block, Wither proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_EMBER_METAL_PILLAR.asItem(), "Ember Metal decorative block, Wither proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_EMBER_METAL_SLAB.asItem(), "Ember Metal decorative block, Wither proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_EMBER_METAL_STAIRS.asItem(), "Ember Metal decorative block, Wither proof"); + ItemTooltipManager.NORMAL.put( ModBlocks.OVERHEATED_EMBER_METAL_BLOCK.asItem(), """ Extreme heat has broken its mass-energy balance; injecting mass will transform it into Transcendium May degrade into Netherite upon cooling"""); - NORMAL.put(ModItems.EMBER_METAL_INGOT.get(), "A piece of heat-resistant Netherite tempered in fire for eons"); - NORMAL.put(ModItems.FROST_METAL_INGOT.get(), "A piece of cold-resistant Royal Steel tempered in extreme cold for eons"); - NORMAL.put(ModItems.MAGNET_INGOT.get(), "A magnetized iron ingot"); - NORMAL.put(ModItems.TUNGSTEN_INGOT.get(), "A heat-resistant and dense metal, material for Ancient Debris"); - NORMAL.put(ModBlocks.TUNGSTEN_BLOCK.asItem(), "A large block of heat-resistant, high-density metal that can be heated to extreme temperatures"); - NORMAL.put(ModItems.TITANIUM_INGOT.get(), "A strong and lightweight metal"); - NORMAL.put(ModBlocks.TITANIUM_BLOCK.asItem(), "A large block of strong, lightweight metal"); - NORMAL.put(ModItems.ZINC_INGOT.get(), "A lightweight metal"); - NORMAL.put(ModBlocks.ZINC_BLOCK.asItem(), "A large block of lightweight metal"); - NORMAL.put(ModItems.TIN_INGOT.get(), "A soft and corrosion-resistant metal"); - NORMAL.put(ModBlocks.TIN_BLOCK.asItem(), "A large block of soft, corrosion-resistant metal"); - NORMAL.put(ModItems.LEAD_INGOT.get(), "A dense and heavy metal"); - NORMAL.put(ModBlocks.LEAD_BLOCK.asItem(), "A large block of dense, heavy metal that absorbs radiation and slows the decay of radioactive blocks"); - NORMAL.put(ModItems.SILVER_INGOT.get(), "A highly reflective metal"); - NORMAL.put(ModBlocks.SILVER_BLOCK.asItem(), "A large block of highly reflective metal"); - NORMAL.put(ModItems.URANIUM_INGOT.get(), "Radioactive - handle with care"); - NORMAL.put(ModBlocks.URANIUM_BLOCK.asItem(), "A large block of radioactive material that continuously releases heat but decays when multiple blocks are adjacent"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModItems.EMBER_METAL_INGOT.get(), "A piece of heat-resistant Netherite tempered in fire for eons"); + ItemTooltipManager.NORMAL.put(ModItems.FROST_METAL_INGOT.get(), "A piece of cold-resistant Royal Steel tempered in extreme cold for eons"); + ItemTooltipManager.NORMAL.put(ModItems.MAGNET_INGOT.get(), "A magnetized iron ingot"); + ItemTooltipManager.NORMAL.put(ModItems.TUNGSTEN_INGOT.get(), "A heat-resistant and dense metal, material for Ancient Debris"); + ItemTooltipManager.NORMAL.put(ModBlocks.TUNGSTEN_BLOCK.asItem(), "A large block of heat-resistant, high-density metal that can be heated to extreme temperatures"); + ItemTooltipManager.NORMAL.put(ModItems.TITANIUM_INGOT.get(), "A strong and lightweight metal"); + ItemTooltipManager.NORMAL.put(ModBlocks.TITANIUM_BLOCK.asItem(), "A large block of strong, lightweight metal"); + ItemTooltipManager.NORMAL.put(ModItems.ZINC_INGOT.get(), "A lightweight metal"); + ItemTooltipManager.NORMAL.put(ModBlocks.ZINC_BLOCK.asItem(), "A large block of lightweight metal"); + ItemTooltipManager.NORMAL.put(ModItems.TIN_INGOT.get(), "A soft and corrosion-resistant metal"); + ItemTooltipManager.NORMAL.put(ModBlocks.TIN_BLOCK.asItem(), "A large block of soft, corrosion-resistant metal"); + ItemTooltipManager.NORMAL.put(ModItems.LEAD_INGOT.get(), "A dense and heavy metal"); + ItemTooltipManager.NORMAL.put(ModBlocks.LEAD_BLOCK.asItem(), "A large block of dense, heavy metal that absorbs radiation and slows the decay of radioactive blocks"); + ItemTooltipManager.NORMAL.put(ModItems.SILVER_INGOT.get(), "A highly reflective metal"); + ItemTooltipManager.NORMAL.put(ModBlocks.SILVER_BLOCK.asItem(), "A large block of highly reflective metal"); + ItemTooltipManager.NORMAL.put(ModItems.URANIUM_INGOT.get(), "Radioactive - handle with care"); + ItemTooltipManager.NORMAL.put(ModBlocks.URANIUM_BLOCK.asItem(), "A large block of radioactive material that continuously releases heat but decays when multiple blocks are adjacent"); + ItemTooltipManager.NORMAL.put( ModItems.PLUTONIUM_INGOT.get(), "Highly radioactive - cannot be mined naturally, obtained from uranium transmutation" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.PLUTONIUM_BLOCK.asItem(), "A large block of highly radioactive material obtained only by transmuting uranium; continuously releases heat but decays when multiple blocks are adjacent" ); - NORMAL.put(ModItems.BRONZE_INGOT.get(), "A durable copper-tin alloy"); - NORMAL.put(ModBlocks.BRONZE_BLOCK.asItem(), "A large block of durable copper-tin alloy"); - NORMAL.put(ModItems.BRASS_INGOT.get(), "A corrosion-resistant copper-zinc alloy"); - NORMAL.put(ModBlocks.BRASS_BLOCK.asItem(), "A large block of corrosion-resistant copper-zinc alloy"); - NORMAL.put(ModBlocks.CUT_BRONZE_BLOCK.asItem(), "Bronze decorative block"); - NORMAL.put(ModBlocks.CUT_BRONZE_STAIRS.asItem(), "Bronze decorative block"); - NORMAL.put(ModBlocks.CUT_BRONZE_SLAB.asItem(), "Bronze decorative block"); - NORMAL.put(ModBlocks.CUT_BRONZE_PILLAR.asItem(), "Bronze decorative block"); - NORMAL.put(ModBlocks.CHISELED_BRONZE_BLOCK.asItem(), "Bronze decorative block"); - NORMAL.put(ModBlocks.CUT_BRASS_BLOCK.asItem(), "Brass decorative block"); - NORMAL.put(ModBlocks.CUT_BRASS_STAIRS.asItem(), "Brass decorative block"); - NORMAL.put(ModBlocks.CUT_BRASS_SLAB.asItem(), "Brass decorative block"); - NORMAL.put(ModBlocks.CUT_BRASS_PILLAR.asItem(), "Brass decorative block"); - NORMAL.put(ModBlocks.CHISELED_BRASS_BLOCK.asItem(), "Brass decorative block"); - NORMAL.put(ModItems.ROYAL_STEEL_NUGGET.get(), "A small piece of iron infused with gem magic"); - NORMAL.put(ModItems.EMBER_METAL_NUGGET.get(), "A small piece of heat-resistant Netherite tempered in fire for eons"); - NORMAL.put(ModItems.FROST_METAL_NUGGET.get(), "A small piece of cold-resistant Royal Steel tempered in extreme cold for eons"); - NORMAL.put(ModItems.TUNGSTEN_NUGGET.get(), "A small piece of heat-resistant, high-density metal"); - NORMAL.put(ModItems.TITANIUM_NUGGET.get(), "A small piece of Titanium"); - NORMAL.put(ModItems.ZINC_NUGGET.get(), "A small piece of Zinc"); - NORMAL.put(ModItems.TIN_NUGGET.get(), "A small piece of Tin"); - NORMAL.put(ModItems.LEAD_NUGGET.get(), "A small piece of Lead"); - NORMAL.put(ModItems.SILVER_NUGGET.get(), "A small piece of Silver"); - NORMAL.put(ModItems.URANIUM_NUGGET.get(), "A small piece of Uranium"); - NORMAL.put(ModItems.PLUTONIUM_NUGGET.get(), "A small piece of highly radioactive material obtained only by transmuting uranium"); - NORMAL.put(ModItems.BRONZE_NUGGET.get(), "A small piece of durable copper-tin alloy"); - NORMAL.put(ModItems.BRASS_NUGGET.get(), "A small piece of corrosion-resistant copper-zinc alloy"); - NORMAL.put(ModItems.TIN_CAN.asItem(), "Tin cans can be combined with any food to obtain canned food"); - NORMAL.put(ModFoodItems.CANNED_FOOD.asItem(), "Stackable instant food"); - NORMAL.put(ModItems.IONOCRAFT.asItem(), "It will float when placed in the power grid"); - NORMAL.put(ModItems.LEVITATION_POWDER.asItem(), "Slight weightlessness"); - NORMAL.put(ModItems.NEGATIVE_MATTER.asItem(), "Negative matter is not antimatter, it is anti gravity matter"); - NORMAL.put(ModItems.NEGATIVE_MATTER_NUGGET.asItem(), "Negative matter is not antimatter, it is anti gravity matter"); - NORMAL.put(ModBlocks.NEGATIVE_MATTER_BLOCK.asItem(), "Negative matter is not antimatter, it is anti gravity matter"); - NORMAL.put(ModItems.NEUTRONIUM_INGOT.asItem(), "Pass through most blocks except end dust, negative matter block, and bedrock"); - NORMAL.put(ModItems.STABLE_NEUTRONIUM_INGOT.asItem(), "No more passing through blocks"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModItems.BRONZE_INGOT.get(), "A durable copper-tin alloy"); + ItemTooltipManager.NORMAL.put(ModBlocks.BRONZE_BLOCK.asItem(), "A large block of durable copper-tin alloy"); + ItemTooltipManager.NORMAL.put(ModItems.BRASS_INGOT.get(), "A corrosion-resistant copper-zinc alloy"); + ItemTooltipManager.NORMAL.put(ModBlocks.BRASS_BLOCK.asItem(), "A large block of corrosion-resistant copper-zinc alloy"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRONZE_BLOCK.asItem(), "Bronze decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRONZE_STAIRS.asItem(), "Bronze decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRONZE_SLAB.asItem(), "Bronze decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRONZE_PILLAR.asItem(), "Bronze decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CHISELED_BRONZE_BLOCK.asItem(), "Bronze decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRASS_BLOCK.asItem(), "Brass decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRASS_STAIRS.asItem(), "Brass decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRASS_SLAB.asItem(), "Brass decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_BRASS_PILLAR.asItem(), "Brass decorative block"); + ItemTooltipManager.NORMAL.put(ModBlocks.CHISELED_BRASS_BLOCK.asItem(), "Brass decorative block"); + ItemTooltipManager.NORMAL.put(ModItems.ROYAL_STEEL_NUGGET.get(), "A small piece of iron infused with gem magic"); + ItemTooltipManager.NORMAL.put(ModItems.EMBER_METAL_NUGGET.get(), "A small piece of heat-resistant Netherite tempered in fire for eons"); + ItemTooltipManager.NORMAL.put(ModItems.FROST_METAL_NUGGET.get(), "A small piece of cold-resistant Royal Steel tempered in extreme cold for eons"); + ItemTooltipManager.NORMAL.put(ModItems.TUNGSTEN_NUGGET.get(), "A small piece of heat-resistant, high-density metal"); + ItemTooltipManager.NORMAL.put(ModItems.TITANIUM_NUGGET.get(), "A small piece of Titanium"); + ItemTooltipManager.NORMAL.put(ModItems.ZINC_NUGGET.get(), "A small piece of Zinc"); + ItemTooltipManager.NORMAL.put(ModItems.TIN_NUGGET.get(), "A small piece of Tin"); + ItemTooltipManager.NORMAL.put(ModItems.LEAD_NUGGET.get(), "A small piece of Lead"); + ItemTooltipManager.NORMAL.put(ModItems.SILVER_NUGGET.get(), "A small piece of Silver"); + ItemTooltipManager.NORMAL.put(ModItems.URANIUM_NUGGET.get(), "A small piece of Uranium"); + ItemTooltipManager.NORMAL.put(ModItems.PLUTONIUM_NUGGET.get(), "A small piece of highly radioactive material obtained only by transmuting uranium"); + ItemTooltipManager.NORMAL.put(ModItems.BRONZE_NUGGET.get(), "A small piece of durable copper-tin alloy"); + ItemTooltipManager.NORMAL.put(ModItems.BRASS_NUGGET.get(), "A small piece of corrosion-resistant copper-zinc alloy"); + ItemTooltipManager.NORMAL.put(ModItems.TIN_CAN.asItem(), "Tin cans can be combined with any food to obtain canned food"); + ItemTooltipManager.NORMAL.put(ModFoodItems.CANNED_FOOD.asItem(), "Stackable instant food"); + ItemTooltipManager.NORMAL.put(ModItems.IONOCRAFT.asItem(), "It will float when placed in the power grid"); + ItemTooltipManager.NORMAL.put(ModItems.LEVITATION_POWDER.asItem(), "Slight weightlessness"); + ItemTooltipManager.NORMAL.put(ModItems.NEGATIVE_MATTER.asItem(), "Negative matter is not antimatter, it is anti gravity matter"); + ItemTooltipManager.NORMAL.put(ModItems.NEGATIVE_MATTER_NUGGET.asItem(), "Negative matter is not antimatter, it is anti gravity matter"); + ItemTooltipManager.NORMAL.put(ModBlocks.NEGATIVE_MATTER_BLOCK.asItem(), "Negative matter is not antimatter, it is anti gravity matter"); + ItemTooltipManager.NORMAL.put(ModItems.NEUTRONIUM_INGOT.asItem(), "Pass through most blocks except end dust, negative matter block, and bedrock"); + ItemTooltipManager.NORMAL.put(ModItems.STABLE_NEUTRONIUM_INGOT.asItem(), "No more passing through blocks"); + ItemTooltipManager.NORMAL.put( ModItems.CHARGED_NEUTRONIUM_INGOT.asItem(), "No longer passing through blocks, storing a large amount of electrical energy" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TESLA_TOWER.asItem(), "Shocks mobs or lightning rods within 8 blocks, consumes 128 kW" ); - NORMAL.put(ModBlocks.ACTIVE_SILENCER.asItem(), "Eliminate selected nearby sounds"); - NORMAL.put(ModBlocks.COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); - NORMAL.put(ModBlocks.EXPOSED_COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); - NORMAL.put(ModBlocks.WEATHERED_COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); - NORMAL.put(ModBlocks.OXIDIZED_COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.ACTIVE_SILENCER.asItem(), "Eliminate selected nearby sounds"); + ItemTooltipManager.NORMAL.put(ModBlocks.COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); + ItemTooltipManager.NORMAL.put(ModBlocks.EXPOSED_COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); + ItemTooltipManager.NORMAL.put(ModBlocks.WEATHERED_COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); + ItemTooltipManager.NORMAL.put(ModBlocks.OXIDIZED_COPPER_PRESSURE_PLATE.asItem(), "Redstone signal increases with pressing time, also a copper plate"); + ItemTooltipManager.NORMAL.put( ModBlocks.ZINC_PRESSURE_PLATE.asItem(), "Output a redstone signal based on the highest percentage of health of the mobs above, also a zinc plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TIN_PRESSURE_PLATE.asItem(), "Output a redstone signal based on the lowest percentage of health of the mobs above, also a tin plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.LEAD_PRESSURE_PLATE.asItem(), "Output redstone signal based on the number of mob species above, also a lead plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.SILVER_PRESSURE_PLATE.asItem(), "Output redstone signal based on the number of undead mobs above, also a silver plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TUNGSTEN_PRESSURE_PLATE.asItem(), "Output redstone signal based on the number of fire-resistant entities above, also a tungsten plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TITANIUM_PRESSURE_PLATE.asItem(), "Output a redstone signal based on the highest durability of the items above, also a titanium plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.URANIUM_PRESSURE_PLATE.asItem(), "Output a redstone signal based on the lowest durability of the items above, also a uranium plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.PLUTONIUM_PRESSURE_PLATE.asItem(), "Output a redstone signal based on the player in hand item durability, also a plutonium plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.BRONZE_PRESSURE_PLATE.asItem(), "Output a redstone signal based on player satiety above, also a bronze plate" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.BRASS_PRESSURE_PLATE.asItem(), "Output a redstone signal based on the inventory's filling degree of player above, also a brass plate" ); - NORMAL.put(ModItems.MULTITOOL_ITEM.get(), "Press [Alt] to switch tool modes"); - NORMAL.put(ModItems.SPECTRAL_SLINGSHOT.get(), "Load a weapon to fire its phantom"); - NORMAL.put(ModItems.RECOVERY_PEARL.get(), "Right-click to teleport to last death point"); - NORMAL.put(ModBlocks.HEAT_COLLECTOR.asItem(), "Generates power from heat"); - NORMAL.put(ModBlocks.VOID_ENERGY_COLLECTOR.asItem(), "Generates power from Void energy"); - NORMAL.put(ModBlocks.RUBY_LASER.asItem(), "Emits a laser beam when powered"); - NORMAL.put(ModBlocks.RUBY_PRISM.asItem(), "Deflects or converges laser beams"); - NORMAL.put(ModBlocks.TRANSPARENT_CRAFTING_TABLE.asItem(), "Aesthetic, connectable Crafting Table"); - NORMAL.put(ModBlocks.MENGER_SPONGE.asItem(), "Absorbs infinite liquid"); - NORMAL.put(ModBlocks.SLIDING_RAIL.asItem(), "Frictionless surface for sliding entities and even blocks"); - NORMAL.put(ModBlocks.POWERED_SLIDING_RAIL.asItem(), "Accelerates items, entities, or blocks when powered"); - NORMAL.put(ModBlocks.DETECTOR_SLIDING_RAIL.asItem(), "Output signal when objects or blocks slide over"); - NORMAL.put(ModBlocks.ACTIVATOR_SLIDING_RAIL.asItem(), "Activates blocks sliding over it"); - NORMAL.put(ModBlocks.SLIDING_RAIL_STOP.asItem(), "Stops sliding items, entities, or blocks"); - NORMAL.put(ModBlocks.PROPEL_PISTON.asItem(), "Integrated piston worm, requires Capacitor or Laser power"); - NORMAL.put(ModBlocks.PULSE_GENERATOR.asItem(), "Customizes pulse delay and duration"); - NORMAL.put(ModBlocks.ADVANCED_COMPARATOR.asItem(), "Supports Hysteresis and Window comparison modes"); - NORMAL.put(ModItems.EMERALD_AMULET.get(), "Grants Hero of the Village"); - NORMAL.put(ModItems.TOPAZ_AMULET.get(), "Grants immunity to lightning damage"); - NORMAL.put(ModItems.RUBY_AMULET.get(), "Grants Fire Resistance"); - NORMAL.put(ModItems.SAPPHIRE_AMULET.get(), "Grants Conduit Power"); - NORMAL.put(ModItems.ANVIL_AMULET.get(), "Grants immunity to anvil damage"); - NORMAL.put(ModItems.FEATHER_AMULET.get(), "Grants immunity to fall damage"); - NORMAL.put(ModItems.CAT_AMULET.get(), "Scares away Creepers and Phantoms"); - NORMAL.put(ModItems.DOG_AMULET.get(), "Scares away Skeletons"); - NORMAL.put(ModItems.SILENCE_AMULET.get(), "Silences the wearer"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModItems.MULTITOOL_ITEM.get(), "Press [Alt] to switch tool modes"); + ItemTooltipManager.NORMAL.put(ModItems.SPECTRAL_SLINGSHOT.get(), "Load a weapon to fire its phantom"); + ItemTooltipManager.NORMAL.put(ModItems.RECOVERY_PEARL.get(), "Right-click to teleport to last death point"); + ItemTooltipManager.NORMAL.put(ModBlocks.HEAT_COLLECTOR.asItem(), "Generates power from heat"); + ItemTooltipManager.NORMAL.put(ModBlocks.VOID_ENERGY_COLLECTOR.asItem(), "Generates power from Void energy"); + ItemTooltipManager.NORMAL.put(ModBlocks.RUBY_LASER.asItem(), "Emits a laser beam when powered"); + ItemTooltipManager.NORMAL.put(ModBlocks.RUBY_PRISM.asItem(), "Deflects or converges laser beams"); + ItemTooltipManager.NORMAL.put(ModBlocks.TRANSPARENT_CRAFTING_TABLE.asItem(), "Aesthetic, connectable Crafting Table"); + ItemTooltipManager.NORMAL.put(ModBlocks.MENGER_SPONGE.asItem(), "Absorbs infinite liquid"); + ItemTooltipManager.NORMAL.put(ModBlocks.SLIDING_RAIL.asItem(), "Frictionless surface for sliding entities and even blocks"); + ItemTooltipManager.NORMAL.put(ModBlocks.POWERED_SLIDING_RAIL.asItem(), "Accelerates items, entities, or blocks when powered"); + ItemTooltipManager.NORMAL.put(ModBlocks.DETECTOR_SLIDING_RAIL.asItem(), "Output signal when objects or blocks slide over"); + ItemTooltipManager.NORMAL.put(ModBlocks.ACTIVATOR_SLIDING_RAIL.asItem(), "Activates blocks sliding over it"); + ItemTooltipManager.NORMAL.put(ModBlocks.SLIDING_RAIL_STOP.asItem(), "Stops sliding items, entities, or blocks"); + ItemTooltipManager.NORMAL.put(ModBlocks.PROPEL_PISTON.asItem(), "Integrated piston worm, requires Capacitor or Laser power"); + ItemTooltipManager.NORMAL.put(ModBlocks.PULSE_GENERATOR.asItem(), "Customizes pulse delay and duration"); + ItemTooltipManager.NORMAL.put(ModBlocks.ADVANCED_COMPARATOR.asItem(), "Supports Hysteresis and Window comparison modes"); + ItemTooltipManager.NORMAL.put(ModItems.EMERALD_AMULET.get(), "Grants Hero of the Village"); + ItemTooltipManager.NORMAL.put(ModItems.TOPAZ_AMULET.get(), "Grants immunity to lightning damage"); + ItemTooltipManager.NORMAL.put(ModItems.RUBY_AMULET.get(), "Grants Fire Resistance"); + ItemTooltipManager.NORMAL.put(ModItems.SAPPHIRE_AMULET.get(), "Grants Conduit Power"); + ItemTooltipManager.NORMAL.put(ModItems.ANVIL_AMULET.get(), "Grants immunity to anvil damage"); + ItemTooltipManager.NORMAL.put(ModItems.FEATHER_AMULET.get(), "Grants immunity to fall damage"); + ItemTooltipManager.NORMAL.put(ModItems.CAT_AMULET.get(), "Scares away Creepers and Phantoms"); + ItemTooltipManager.NORMAL.put(ModItems.DOG_AMULET.get(), "Scares away Skeletons"); + ItemTooltipManager.NORMAL.put(ModItems.SILENCE_AMULET.get(), "Silences the wearer"); + ItemTooltipManager.NORMAL.put( ModItems.ABNORMAL_AMULET.get(), "Prevents damage from carrying Uranium, Plutonium, Floating Powder, Cursed Gold items" ); - NORMAL.put(ModItems.NATURE_AMULET.get(), "Combines Silence, Cat, Dog, and Feather Amulet effects"); - NORMAL.put(ModItems.GEM_AMULET.get(), "Combines effects of all four Gem Amulets"); - NORMAL.put(ModItems.CAPACITOR.asItem(), "8 MFE stored"); - NORMAL.put(ModItems.CAPACITOR_EMPTY.asItem(), "8 MFE capacity"); - NORMAL.put(ModItems.SUPER_CAPACITOR.asItem(), "160 MFE stored"); - NORMAL.put(ModItems.SUPER_CAPACITOR_EMPTY.asItem(), "160 MFE capacity"); - NORMAL.put(ModItems.HEAVY_HALBERD_CORE.get(), "Material for crafting the Heavy Halberd"); - NORMAL.put(ModItems.RESONATOR_CORE.get(), "Material for crafting the Resonator"); - NORMAL.put(ModBlocks.BLACK_HOLE.asItem(), "Dev Block with intense gravitational attraction"); - NORMAL.put(ModBlocks.WHITE_HOLE.asItem(), "Dev Block with intense gravitational repulsion"); - NORMAL.put(ModBlocks.CHARGER.asItem(), "Charges items, supports manual or automated input"); - NORMAL.put(ModBlocks.DISCHARGER.asItem(), "Discharges capacitors, supports manual or automated input"); - NORMAL.put(ModBlocks.LASER_RECEIVER.asItem(), "Receives lasers, generating power and a redstone signal based on the laser level"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModItems.NATURE_AMULET.get(), "Combines Silence, Cat, Dog, and Feather Amulet effects"); + ItemTooltipManager.NORMAL.put(ModItems.GEM_AMULET.get(), "Combines effects of all four Gem Amulets"); + ItemTooltipManager.NORMAL.put(ModItems.CAPACITOR.asItem(), "8 MFE stored"); + ItemTooltipManager.NORMAL.put(ModItems.CAPACITOR_EMPTY.asItem(), "8 MFE capacity"); + ItemTooltipManager.NORMAL.put(ModItems.SUPER_CAPACITOR.asItem(), "160 MFE stored"); + ItemTooltipManager.NORMAL.put(ModItems.SUPER_CAPACITOR_EMPTY.asItem(), "160 MFE capacity"); + ItemTooltipManager.NORMAL.put(ModItems.HEAVY_HALBERD_CORE.get(), "Material for crafting the Heavy Halberd"); + ItemTooltipManager.NORMAL.put(ModItems.RESONATOR_CORE.get(), "Material for crafting the Resonator"); + ItemTooltipManager.NORMAL.put(ModBlocks.BLACK_HOLE.asItem(), "Dev Block with intense gravitational attraction"); + ItemTooltipManager.NORMAL.put(ModBlocks.WHITE_HOLE.asItem(), "Dev Block with intense gravitational repulsion"); + ItemTooltipManager.NORMAL.put(ModBlocks.CHARGER.asItem(), "Charges items, supports manual or automated input"); + ItemTooltipManager.NORMAL.put(ModBlocks.DISCHARGER.asItem(), "Discharges capacitors, supports manual or automated input"); + ItemTooltipManager.NORMAL.put(ModBlocks.LASER_RECEIVER.asItem(), "Receives lasers, generating power and a redstone signal based on the laser level"); + ItemTooltipManager.NORMAL.put( ModBlocks.FROST_ANVIL.asItem(), """ Slower enchantment penalty growth, repairs any item with Frost Metal, free renaming Explosion proof, does not degrade from falling""" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TRANSCENDENCE_ANVIL.asItem(), """ Ignores enchantment level limits, and Anvil Looting produces additional drops Immune to most destruction methods, does not degrade from falling"""); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TRANSCENDENCE_GRINDSTONE.asItem(), """ Removes curses and enchantment penalties, selectively removes or transfers multiple enchantments Immune to most destruction methods""" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TRANSCENDENCE_DECO_BLOCK.asItem(), "Transcendium decorative block; its low Transcendium content means it is not indestructible" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.TRANSCENDENCE_DECO_OUTLINE.asItem(), "Transcendium decorative block; its low Transcendium content means it is not indestructible" ); - NORMAL.put(ModBlocks.FROST_GRINDSTONE.asItem(), "Selectively removes individual enchantments, Explosion proof"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.FROST_GRINDSTONE.asItem(), "Selectively removes individual enchantments, Explosion proof"); + ItemTooltipManager.NORMAL.put( ModBlocks.FROST_SMITHING_TABLE.asItem(), "Works with Permutation and Deformation smithing templates, Explosion proof" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.FROST_METAL_BLOCK.asItem(), "A large block of cold-resistant Royal Steel tempered in extreme cold for eons, Explosion proof" ); - NORMAL.put(ModBlocks.FROST_GLASS.asItem(), "Frost Metal glass, Explosion proof, No tools required on collect"); - NORMAL.put(ModBlocks.CUT_FROST_METAL_BLOCK.asItem(), "Frost Metal decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_FROST_METAL_PILLAR.asItem(), "Frost Metal decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_FROST_METAL_SLAB.asItem(), "Frost Metal decorative block, Explosion proof"); - NORMAL.put(ModBlocks.CUT_FROST_METAL_STAIRS.asItem(), "Frost Metal decorative block, Explosion proof"); - NORMAL.put(ModBlocks.SPECTRAL_ANVIL.asItem(), "Creates phantom shadows when the upper magnet is demagnetized"); - NORMAL.put(ModBlocks.BLOCK_PLACER.asItem(), "Places blocks in front when powered by redstone"); - NORMAL.put(ModItems.STRUCTURE_DISK.get(), "Stores structure data, used in blueprint mode of Smart Block Placer"); - NORMAL.put(ModBlocks.STRUCTURE_SCANNER.asItem(), "Scans and stores structures in Structure Disk"); - NORMAL.put(ModBlocks.SMART_BLOCK_PLACER.asItem(), "Advanced block placer with 5x5x5 configurable placement area"); - NORMAL.put(ModBlocks.FISH_TANK.asItem(), "Used for anvil synthesis and provides underwater breathing when worn"); - NORMAL.put(ModBlocks.BLOCK_DEVOURER.asItem(), "Breaks 3×3 area of blocks in front when powered by redstone"); - NORMAL.put(ModBlocks.INDUCTION_LIGHT.asItem(), "Provides lighting and configurable special modes"); - NORMAL.put(ModBlocks.HELIOSTATS.asItem(), "Heats targeted blocks during the day"); - NORMAL.put(ModItems.IONOCRAFT_BACKPACK.asItem(), "Allows creative flight while equipped, requires power from the energy grid or capacitors in the inventory"); - NORMAL.put(ModBlocks.BLOCK_COMPARATOR.asItem(), "Outputs signal when side blocks are the same, right-click to switch to precise state detection mode"); - NORMAL.put(ModBlocks.ITEM_DETECTOR.asItem(), "Detects specific items behind (drops/containers) to output redstone signal"); - NORMAL.put(ModBlocks.IMPACT_PILE.asItem(), "Place on Bedrock or Deepslate and strike with falling anvil to create Moneral Fountain"); - NORMAL.put(ModBlocks.SPACE_OVERCOMPRESSOR.asItem(), "Compresses items into Neutronium Ingots, compresses multiblock outputs into drops"); - NORMAL.put(ModBlocks.ACCELERATION_RING.asItem(), "Creates acceleration field for anvils, projectiles, or players with Anvil Hammer"); - NORMAL.put(ModBlocks.DEFLECTION_RING.asItem(), "Deflects passing objects 90°, detect speed with Comparator"); - NORMAL.put(ModItems.DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); - NORMAL.put(ModItems.EMBER_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); - NORMAL.put(ModItems.FROST_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); - NORMAL.put(ModItems.ROYAL_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); - NORMAL.put(ModItems.TRANSCENDENCE_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); - NORMAL.put(ModItems.FILTER.asItem(), "Matches items based on configuration, usable in any filter slot"); - NORMAL.put(ModItems.TOTEM_OF_RECOVERY.asItem(), "Teleports to spawn on death, grants a Recall Pearl to return to death point"); - NORMAL.put(ModItems.TOTEM_OF_RAGE.asItem(), "Grants invulnerability and berserk on fatal damage, death is inevitable after 1 minute"); - NORMAL.put(ModItems.COMRADE_AMULET.asItem(), "Signable by players via right-click, prevents damage from signed players"); - NORMAL.put(ModItems.PILL_BOX.asItem(), "Store pills for quick use"); - NORMAL.put(ModItems.AMULET_BOX.asItem(), "Stores multiple active amulets or totems"); - NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL.asItem(), "Forge celestial bodies, build megastructures"); - NORMAL.put(ModItems.PIPE.get(), "Transports fluids between containers, gravity-driven flow"); - NORMAL.put(ModItems.TRANSCENDIUM_INGOT.get(), "A piece of strong-interaction matter sustained by magic, immune to most forms of destruction"); - NORMAL.put(ModBlocks.TRANSCENDIUM_BLOCK.asItem(), "A large block of strong-interaction matter sustained by magic, immune to most forms of destruction"); - NORMAL.put(ModItems.TRANSCENDIUM_NUGGET.get(), "A small piece of strong-interaction matter sustained by magic, immune to most forms of destruction"); - NORMAL.put(ModItems.VOID_MATTER.get(), "The primordial substance that creates all things, mined from the void, decays outside the void"); - NORMAL.put(ModItems.EXCITED_STATE_VOID_MATTER.get(), "The substance of black hole singularities, more unstable than ordinary void matter"); - NORMAL.put(ModItems.EARTH_CORE_SHARD.get(), "A fragment of a planet's heart, pulsing with geological might"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.FROST_GLASS.asItem(), "Frost Metal glass, Explosion proof, No tools required on collect"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_FROST_METAL_BLOCK.asItem(), "Frost Metal decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_FROST_METAL_PILLAR.asItem(), "Frost Metal decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_FROST_METAL_SLAB.asItem(), "Frost Metal decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.CUT_FROST_METAL_STAIRS.asItem(), "Frost Metal decorative block, Explosion proof"); + ItemTooltipManager.NORMAL.put(ModBlocks.SPECTRAL_ANVIL.asItem(), "Creates phantom shadows when the upper magnet is demagnetized"); + ItemTooltipManager.NORMAL.put(ModBlocks.BLOCK_PLACER.asItem(), "Places blocks in front when powered by redstone"); + ItemTooltipManager.NORMAL.put(ModItems.STRUCTURE_DISK.get(), "Stores structure data, used in blueprint mode of Smart Block Placer"); + ItemTooltipManager.NORMAL.put(ModBlocks.STRUCTURE_SCANNER.asItem(), "Scans and stores structures in Structure Disk"); + ItemTooltipManager.NORMAL.put(ModBlocks.SMART_BLOCK_PLACER.asItem(), "Advanced block placer with 5x5x5 configurable placement area"); + ItemTooltipManager.NORMAL.put(ModBlocks.FISH_TANK.asItem(), "Used for anvil synthesis and provides underwater breathing when worn"); + ItemTooltipManager.NORMAL.put(ModBlocks.BLOCK_DEVOURER.asItem(), "Breaks 3×3 area of blocks in front when powered by redstone"); + ItemTooltipManager.NORMAL.put(ModBlocks.INDUCTION_LIGHT.asItem(), "Provides lighting and configurable special modes"); + ItemTooltipManager.NORMAL.put(ModBlocks.HELIOSTATS.asItem(), "Heats targeted blocks during the day"); + ItemTooltipManager.NORMAL.put(ModItems.IONOCRAFT_BACKPACK.asItem(), "Allows creative flight while equipped, requires power from the energy grid or capacitors in the inventory"); + ItemTooltipManager.NORMAL.put(ModBlocks.BLOCK_COMPARATOR.asItem(), "Outputs signal when side blocks are the same, right-click to switch to precise state detection mode"); + ItemTooltipManager.NORMAL.put(ModBlocks.ITEM_DETECTOR.asItem(), "Detects specific items behind (drops/containers) to output redstone signal"); + ItemTooltipManager.NORMAL.put(ModBlocks.IMPACT_PILE.asItem(), "Place on Bedrock or Deepslate and strike with falling anvil to create Moneral Fountain"); + ItemTooltipManager.NORMAL.put(ModBlocks.SPACE_OVERCOMPRESSOR.asItem(), "Compresses items into Neutronium Ingots, compresses multiblock outputs into drops"); + ItemTooltipManager.NORMAL.put(ModBlocks.ACCELERATION_RING.asItem(), "Creates acceleration field for anvils, projectiles, or players with Anvil Hammer"); + ItemTooltipManager.NORMAL.put(ModBlocks.DEFLECTION_RING.asItem(), "Deflects passing objects 90°, detect speed with Comparator"); + ItemTooltipManager.NORMAL.put(ModItems.DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); + ItemTooltipManager.NORMAL.put(ModItems.EMBER_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); + ItemTooltipManager.NORMAL.put(ModItems.FROST_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); + ItemTooltipManager.NORMAL.put(ModItems.ROYAL_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); + ItemTooltipManager.NORMAL.put(ModItems.TRANSCENDENCE_DRAGON_ROD.asItem(), "Portable block devourer with adjustable range"); + ItemTooltipManager.NORMAL.put(ModItems.FILTER.asItem(), "Matches items based on configuration, usable in any filter slot"); + ItemTooltipManager.NORMAL.put(ModItems.TOTEM_OF_RECOVERY.asItem(), "Teleports to spawn on death, grants a Recall Pearl to return to death point"); + ItemTooltipManager.NORMAL.put(ModItems.TOTEM_OF_RAGE.asItem(), "Grants invulnerability and berserk on fatal damage, death is inevitable after 1 minute"); + ItemTooltipManager.NORMAL.put(ModItems.COMRADE_AMULET.asItem(), "Signable by players via right-click, prevents damage from signed players"); + ItemTooltipManager.NORMAL.put(ModItems.PILL_BOX.asItem(), "Store pills for quick use"); + ItemTooltipManager.NORMAL.put(ModItems.AMULET_BOX.asItem(), "Stores multiple active amulets or totems"); + ItemTooltipManager.NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL.asItem(), "Forge celestial bodies, build megastructures"); + ItemTooltipManager.NORMAL.put(ModItems.PIPE.get(), "Transports fluids between containers, gravity-driven flow"); + ItemTooltipManager.NORMAL.put(ModItems.TRANSCENDIUM_INGOT.get(), "A piece of strong-interaction matter sustained by magic, immune to most forms of destruction"); + ItemTooltipManager.NORMAL.put(ModBlocks.TRANSCENDIUM_BLOCK.asItem(), "A large block of strong-interaction matter sustained by magic, immune to most forms of destruction"); + ItemTooltipManager.NORMAL.put(ModItems.TRANSCENDIUM_NUGGET.get(), "A small piece of strong-interaction matter sustained by magic, immune to most forms of destruction"); + ItemTooltipManager.NORMAL.put(ModItems.VOID_MATTER.get(), "The primordial substance that creates all things, mined from the void, decays outside the void"); + ItemTooltipManager.NORMAL.put(ModItems.EXCITED_STATE_VOID_MATTER.get(), "The substance of black hole singularities, more unstable than ordinary void matter"); + ItemTooltipManager.NORMAL.put(ModItems.EARTH_CORE_SHARD.get(), "A fragment of a planet's heart, pulsing with geological might"); + ItemTooltipManager.NORMAL.put( ModItems.MULTIPHASE_MATTER.get(), "Matter that exists in multiple stable phases simultaneously, switchable under special conditions" ); - NORMAL.put(ModBlocks.OVERSEER.asItem(), "Chunk loader that works on suitable base"); - NORMAL.put(ModBlocks.PUMP.asItem(), "Pumps fluids, consumes 32 kW"); - NORMAL.put(ModBlocks.CREATIVE_CRATE.asItem(), "Infinite item storage and supply"); - NORMAL.put(ModBlocks.CREATIVE_FLUID_TANK.asItem(), "Infinite fluid storage and supply"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.OVERSEER.asItem(), "Chunk loader that works on suitable base"); + ItemTooltipManager.NORMAL.put(ModBlocks.PUMP.asItem(), "Pumps fluids, consumes 32 kW"); + ItemTooltipManager.NORMAL.put(ModBlocks.CREATIVE_CRATE.asItem(), "Infinite item storage and supply"); + ItemTooltipManager.NORMAL.put(ModBlocks.CREATIVE_FLUID_TANK.asItem(), "Infinite fluid storage and supply"); + ItemTooltipManager.NORMAL.put( ModBlocks.FLUID_TANK.asItem(), """ Stores 16B of fluid; Menger Sponges expand it to 12800B and make it infinite when full Can interact with Dispensers for fluid transfer""" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.LARGE_FLUID_TANK.asItem(), """ Stores 512B shared by any number of fluids @@ -386,199 +386,199 @@ public class ItemTooltipManager { Can store multiple fluids, each type of fluid that reaches 12800B will be converted to infinite Can interact with Dispensers for fluid transfer""" ); - NORMAL.put(ModBlocks.DRAIN.asItem(), "Transfers fluid vertically, outputting downward and drawing from above"); - NORMAL.put(ModBlocks.REDSTONE_WIRE.asItem(), "Transmit redstone signals more precisely"); - NORMAL.put(ModBlocks.TRADING_STATION.asItem(), "Trading platform for players and villagers"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.DRAIN.asItem(), "Transfers fluid vertically, outputting downward and drawing from above"); + ItemTooltipManager.NORMAL.put(ModBlocks.REDSTONE_WIRE.asItem(), "Transmit redstone signals more precisely"); + ItemTooltipManager.NORMAL.put(ModBlocks.TRADING_STATION.asItem(), "Trading platform for players and villagers"); + ItemTooltipManager.NORMAL.put( ModBlocks.CORRUPTED_BEACON.asItem(), "Releases the wither power within the beacon, its beam accelerates time flow or causes mutations" ); - NORMAL.put(ModBlocks.LARGE_CAKE.asItem(), "A cake, a very big cake. 27 bites, each bite fills you up"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.LARGE_CAKE.asItem(), "A cake, a very big cake. 27 bites, each bite fills you up"); + ItemTooltipManager.NORMAL.put( ModBlocks.CONFINEMENT_CHAMBER.asItem(), "Contains elementary particles and unstable items, keeping them stable" ); - NORMAL.put(ModBlocks.CONFINED_TIME_ANVILON.asItem(), "Confinement chamber for time-type Anvilon"); - NORMAL.put(ModBlocks.CONFINED_SPACE_ANVILON.asItem(), "Confinement chamber for space-type Anvilon"); - NORMAL.put(ModBlocks.CONFINED_MASS_ANVILON.asItem(), "Confinement chamber for mass-type Anvilon"); - NORMAL.put(ModBlocks.CONFINED_ENERGY_ANVILON.asItem(), "Confinement chamber for energy-type Anvilon"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.CONFINED_TIME_ANVILON.asItem(), "Confinement chamber for time-type Anvilon"); + ItemTooltipManager.NORMAL.put(ModBlocks.CONFINED_SPACE_ANVILON.asItem(), "Confinement chamber for space-type Anvilon"); + ItemTooltipManager.NORMAL.put(ModBlocks.CONFINED_MASS_ANVILON.asItem(), "Confinement chamber for mass-type Anvilon"); + ItemTooltipManager.NORMAL.put(ModBlocks.CONFINED_ENERGY_ANVILON.asItem(), "Confinement chamber for energy-type Anvilon"); + ItemTooltipManager.NORMAL.put( ModBlocks.CONFINED_NEUTRONIUM_INGOT_BLOCK.asItem(), "A confinement chamber containing a Charged Neutronium Ingot" ); - NORMAL.put(ModBlocks.NEUTRON_IRRADIATOR.asItem(), "Performs neutron irradiation recipes, absorbs confined anvilons for block procedural process"); - NORMAL.put(ModBlocks.CAKE_BASE_BLOCK.asItem(), "A block of cake base, use a shovel as a spoon to eat it"); - NORMAL.put(ModBlocks.CREAM_BLOCK.asItem(), "A block of cream, use a shovel as a spoon to eat it"); - NORMAL.put(ModBlocks.BERRY_CREAM_BLOCK.asItem(), "A block of berry cream, use a shovel as a spoon to eat it"); - NORMAL.put(ModBlocks.CHOCOLATE_CREAM_BLOCK.asItem(), "A block of chocolate cream, use a shovel as a spoon to eat it"); - NORMAL.put(ModBlocks.CAKE_BLOCK.asItem(), "A block of cream cake, use a shovel as a spoon to eat it"); - NORMAL.put(ModBlocks.BERRY_CAKE_BLOCK.asItem(), "A block of berry cake, use a shovel as a spoon to eat it"); - NORMAL.put(ModBlocks.CHOCOLATE_CAKE_BLOCK.asItem(), "A block of chocolate cake, use a shovel as a spoon to eat it"); - NORMAL.put(ModBlocks.CONTROL_VALVE.asItem(), "Controls the type and flow rate of passing fluids and can be locked by redstone"); - NORMAL.put(ModBlocks.SPACETIME_SUPERCOMPUTER.asItem(), "Consumes power to run certain time commands"); - NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_AMPLIFIER.asItem(), "Amplifies the Celestial Forging Anvil to support larger megastructures"); - NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_LOGISTICS_INTERFACE.asItem(), "Item I/O interface for the Celestial Forging Anvil"); - NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_FLUID_INTERFACE.asItem(), "Fluid I/O interface for the Celestial Forging Anvil"); - NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_LASER_INTERFACE.asItem(), "Laser I/O interface for the Celestial Forging Anvil"); - NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_INTERFACE_PLACEHOLDER.asItem(), "Placeholder block for Celestial Forging Anvil structure"); - NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_PORTAL.asItem(), "Teleports players and entities between two portals"); - NORMAL.put(ModBlocks.LENS.asItem(), "Use special glass to enchant lasers"); - NORMAL.put(ModItems.CHECK_VALVE.get(), "Allows fluid to flow in only one direction"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.NEUTRON_IRRADIATOR.asItem(), "Performs neutron irradiation recipes, absorbs confined anvilons for block procedural process"); + ItemTooltipManager.NORMAL.put(ModBlocks.CAKE_BASE_BLOCK.asItem(), "A block of cake base, use a shovel as a spoon to eat it"); + ItemTooltipManager.NORMAL.put(ModBlocks.CREAM_BLOCK.asItem(), "A block of cream, use a shovel as a spoon to eat it"); + ItemTooltipManager.NORMAL.put(ModBlocks.BERRY_CREAM_BLOCK.asItem(), "A block of berry cream, use a shovel as a spoon to eat it"); + ItemTooltipManager.NORMAL.put(ModBlocks.CHOCOLATE_CREAM_BLOCK.asItem(), "A block of chocolate cream, use a shovel as a spoon to eat it"); + ItemTooltipManager.NORMAL.put(ModBlocks.CAKE_BLOCK.asItem(), "A block of cream cake, use a shovel as a spoon to eat it"); + ItemTooltipManager.NORMAL.put(ModBlocks.BERRY_CAKE_BLOCK.asItem(), "A block of berry cake, use a shovel as a spoon to eat it"); + ItemTooltipManager.NORMAL.put(ModBlocks.CHOCOLATE_CAKE_BLOCK.asItem(), "A block of chocolate cake, use a shovel as a spoon to eat it"); + ItemTooltipManager.NORMAL.put(ModBlocks.CONTROL_VALVE.asItem(), "Controls the type and flow rate of passing fluids and can be locked by redstone"); + ItemTooltipManager.NORMAL.put(ModBlocks.SPACETIME_SUPERCOMPUTER.asItem(), "Consumes power to run certain time commands"); + ItemTooltipManager.NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_AMPLIFIER.asItem(), "Amplifies the Celestial Forging Anvil to support larger megastructures"); + ItemTooltipManager.NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_LOGISTICS_INTERFACE.asItem(), "Item I/O interface for the Celestial Forging Anvil"); + ItemTooltipManager.NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_FLUID_INTERFACE.asItem(), "Fluid I/O interface for the Celestial Forging Anvil"); + ItemTooltipManager.NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_LASER_INTERFACE.asItem(), "Laser I/O interface for the Celestial Forging Anvil"); + ItemTooltipManager.NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_INTERFACE_PLACEHOLDER.asItem(), "Placeholder block for Celestial Forging Anvil structure"); + ItemTooltipManager.NORMAL.put(ModBlocks.CELESTIAL_FORGING_ANVIL_PORTAL.asItem(), "Teleports players and entities between two portals"); + ItemTooltipManager.NORMAL.put(ModBlocks.LENS.asItem(), "Use special glass to enchant lasers"); + ItemTooltipManager.NORMAL.put(ModItems.CHECK_VALVE.get(), "Allows fluid to flow in only one direction"); + ItemTooltipManager.NORMAL.put( ModItems.DYSON_SPHERE_COMPONENT.get(), "Material for building a Dyson Sphere, used in the Celestial Forging Anvil" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModItems.PENROSE_SPHERE_COMPONENT.get(), "Material for building a Penrose Sphere, used in the Celestial Forging Anvil" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModItems.MATTER_DECOMPRESSOR_COMPONENT.get(), "Material for building a Matter Decompressor, used in the Celestial Forging Anvil" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModItems.WORMHOLE_STABILIZER_COMPONENT.get(), "Material for building a Wormhole Stabilizer, used in the Celestial Forging Anvil" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModItems.STELLAR_RING_COMPONENT.get(), "Material for building a Stellar Ring Collider, used in the Celestial Forging Anvil" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModItems.MAGNETAR_COIL_COMPONENT.get(), "Material for building a Magnetar Coil, used in the Celestial Forging Anvil" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModItems.STELLAR_EVOLUTION_ACCELERATOR_COMPONENT.get(), "Material for building a Stellar Evolution Accelerator, used in the Celestial Forging Anvil" ); - NORMAL.put(ModBlocks.LARGE_LASER.asItem(), "Equivalent to 16 lasers, outputs 16 intensity levels of laser, consumes 256 kW"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.LARGE_LASER.asItem(), "Equivalent to 16 lasers, outputs 16 intensity levels of laser, consumes 256 kW"); + ItemTooltipManager.NORMAL.put( ModBlocks.SUGAR_BLOCK.asItem(), """ A large block of sugar Also a piezoelectric crystal, but seems fragile""" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.FLINT_BLOCK.asItem(), """ A large block of flint When pushed or pulled by a piston, it creates fire around it if an iron block is nearby""" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.GUNPOWER_BLOCK.asItem(), """ A large block of gunpowder If struck by a falling anvil, it explodes and launches the anvil back up to the height it fell from""" ); - NORMAL.put( + ItemTooltipManager.NORMAL.put( ModBlocks.ROTTEN_FLESH_BLOCK.asItem(), """ A large block of rotten flesh It cushions fall damage, but landing on it will make you nauseous for 30 seconds Can also be smelted into Netherrack""" ); - NORMAL.put(ModBlocks.SINGULARITY_CRYSTAL.asItem(), "Data disk for storing extreme celestial data from the Celestial Forging Anvil"); - NORMAL.put(ModItems.LASER_GUN.get(), "Hold right-click to consume power and fire a laser that grows increasingly powerful"); - NORMAL.put(ModItems.CORRUPTED_BEACON_ACTIVATOR.get(), "Hold right-click to consume power and fire a corruption beam"); - NORMAL.put(ModItems.TESLA_GUN.get(), "Hold right-click to consume power and fire chain lightning that bounces between mobs"); - NORMAL.put(ModItems.ANVIL_RAILGUN.get(), "Hold right-click to consumes power to charge up and launch a high-speed anvil"); - NORMAL.put(ModItems.SPECTRAL_SLINGSHOT.get(), "Hold right-click to consume power and fires spectral weapons"); - NORMAL.put(ModItems.ENERGY_WEAPON_PLATFORM.get(), "640 MFE stored, but will only inherit the result of Energy Weapon Making"); - NORMAL.put( + ItemTooltipManager.NORMAL.put(ModBlocks.SINGULARITY_CRYSTAL.asItem(), "Data disk for storing extreme celestial data from the Celestial Forging Anvil"); + ItemTooltipManager.NORMAL.put(ModItems.LASER_GUN.get(), "Hold right-click to consume power and fire a laser that grows increasingly powerful"); + ItemTooltipManager.NORMAL.put(ModItems.CORRUPTED_BEACON_ACTIVATOR.get(), "Hold right-click to consume power and fire a corruption beam"); + ItemTooltipManager.NORMAL.put(ModItems.TESLA_GUN.get(), "Hold right-click to consume power and fire chain lightning that bounces between mobs"); + ItemTooltipManager.NORMAL.put(ModItems.ANVIL_RAILGUN.get(), "Hold right-click to consumes power to charge up and launch a high-speed anvil"); + ItemTooltipManager.NORMAL.put(ModItems.SPECTRAL_SLINGSHOT.get(), "Hold right-click to consume power and fires spectral weapons"); + ItemTooltipManager.NORMAL.put(ModItems.ENERGY_WEAPON_PLATFORM.get(), "640 MFE stored, but will only inherit the result of Energy Weapon Making"); + ItemTooltipManager.NORMAL.put( ModBlocks.INFINITE_COLLECTOR.asItem(), """ Generates power by collecting both heat and charge, no upper power limit Provides a baseline output of 256 kW""" ); - NORMAL.put(ModBlocks.LOAD_MONITOR.asItem(), "Monitor the grid load condition, can output a signal by redstone comparator"); - NORMAL.put(ModBlocks.CHUTE.asItem(), "An advanced Hopper, can transfer a full stack of items at a time"); - NORMAL.put(ModBlocks.MAGNETIC_CHUTE.asItem(), "An advanced Chute, with the ability to transport items vertically"); + ItemTooltipManager.NORMAL.put(ModBlocks.LOAD_MONITOR.asItem(), "Monitor the grid load condition, can output a signal by redstone comparator"); + ItemTooltipManager.NORMAL.put(ModBlocks.CHUTE.asItem(), "An advanced Hopper, can transfer a full stack of items at a time"); + ItemTooltipManager.NORMAL.put(ModBlocks.MAGNETIC_CHUTE.asItem(), "An advanced Chute, with the ability to transport items vertically"); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.LASER_GUN.get(), """ The laser damages mobs and can also mine blocks Charging longer increases damage, but watch out for overheating! Enchanting the laser gun alters its beam behavior""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.CORRUPTED_BEACON_ACTIVATOR.get(), """ Fires a beam of corruption that pierces through targets, dealing damage and inflicting Wither It passes through glass and does not convert mobs Enchanting the Corrupted Beacon Exciter boosts the beam's damage""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.TESLA_GUN.get(), """ Fires chain lightning that arcs between up to 4 mobs, dealing reduced damage with each bounce The lightning can convert mobs, and lightning rods will also be targeted Each strike is followed by a cooldown, which can be shortened by enchanting the Tesla Gun""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.ANVIL_RAILGUN.get(), """ Hold right-click to load an anvil from your offhand into the railgun Then hold right-click again to charge up, and release to launch the anvil Longer charging results in higher speed and damage Enchanting the Anvil Railgun can boost damage, reduce charge time, or change its firing behavior""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.SPECTRAL_SLINGSHOT.get(), """ Hold right-click to load your offhand weapon into the Spectral Slingshot Once loaded, right-click again to fire a spectral copy of that weapon, dealing damage Each shot has a cooldown, which can be reduced by enchanting the launcher""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.ENERGY_WEAPON_PLATFORM.get(), """ 640 MFE stored, but will only inherit the result of Energy Weapon Making Can be crafted with different materials to create various energy weapons Consumes capacitors to restore power""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.CHECK_VALVE.get(), """ When holding a check valve, right-click one end of a pipe to convert that end into a check valve Can remove check valve by right-clicking it while holding a check valve, or with an empty hand Supplying a redstone signal reverses the flow direction of the check valve""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.CELESTIAL_FORGING_ANVIL.asItem(), """ Place an anvil to determine celestial parameters Once a suitable celestial body is found, lock it to build a megastructure Unlocking the celestial body will destroy the megastructure Different megastructures serve different purposes — check the megastructure button for details"""); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.SPECTRAL_ANVIL.asItem(), "When the upper magnet is demagnetized, a phantom shadow is created and falls downward, " + "it can pass through transparent blocks, and no matter the actual height, the impact is always treated as a 2‑block fall" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.BLOCK_PLACER.asItem(), """ When powered by redstone, this block places a block in front of it If struck by a falling anvil, the placement distance increases — the farther the anvil falls, the farther the block is placed No internal inventory and must obtain blocks from dropped items or container inventories behind it""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.SMART_BLOCK_PLACER.asItem(), """ Advanced block placer with 5x5x5 placement area, configurable via GUI Supports pickup mode (from containers or drops) and move mode (direct block movement) Requires power supply, consumes 8 kW Put Structure Disk to enable Blue Print Mode, consumes 64 kW""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.STRUCTURE_SCANNER.asItem(), """ Can store structures in Structure Disk and be used in the blueprint mode of Smart Block Placer Maximum can store 16×16×16 structure When powered by redstone, it will automatically scans and stores structures""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.FISH_TANK.asItem(), """ It is sturdier than it looks and can be used as a substitute for the alchemy pot to perform related anvil synthesis Wearing it on your head provides a temporary underwater breathing effect Right-click the top with an item in hand to place the item inside Right-click the lower part of the fish tank with a tropical fish bucket in hand to release the tropical fish""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.BLOCK_DEVOURER.asItem(), """ When powered by redstone, this block instantly breaks a 3×3 area of blocks in front of it If struck by a falling anvil, the breaking range increases — the farther the anvil falls, the larger the area it destroys No internal inventory, outputs items behind it — into containers, as dropped items, or at the break location if blocked Base world blocks such as stone, dirt, and deepslate drop only small amounts""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.INDUCTION_LIGHT.asItem(), """ Provides lighting with a power consumption of 1 kW Right‑click with Redstone to switch to Growth Acceleration Mode @@ -586,21 +586,21 @@ Supports pickup mode (from containers or drops) and move mode (direct block move Right‑click with Void Matter to switch to Anti‑Animal Spawning Mode All three special modes consume 16 kW of power""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.HELIOSTATS.asItem(), """ Right‑click a Netherite Block or Tungsten Block with the handheld heliostat to set target block After placing the heliostat, it will heat the targeted block during the day, as well as the blocks above it Right‑click a targeted heliostat to inherit its target""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.OVERSEER.asItem(), "Chunk loader that works on suitable pyramid-shaped base, higher base layers provide a larger maximum load range (max 4 layers, 9x9 range), different base blocks provide different effects" ); - SHIFT.put(ModBlocks.PUMP.asItem(), """ + ItemTooltipManager.SHIFT.put(ModBlocks.PUMP.asItem(), """ Provides 10 blocks of headlift on both input and output sides (including the pump itself) Also functions as check valve, allowing liquid to flow through only in the pump's direction A redstone signal disables the pump"""); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.CREATIVE_CRATE.asItem(), """ Provides infinite items of a set type: place items inside to configure Items will not be consumed when taken out @@ -608,43 +608,43 @@ Supports pickup mode (from containers or drops) and move mode (direct block move Creative players left-click to clear the configuration Survival players left-click to take out items""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.CREATIVE_FLUID_TANK.asItem(), """ Provides infinite fluid of a set type: fill fluid inside to configure Fluid will not be consumed when extracted Destroys all input fluid when no fluid is configured""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.SPACETIME_SUPERCOMPUTER.asItem(), """ Executes commands stored in the supercomputer on a timer Each execution consumes power from the grid Acts as the computational core of the Celestial Forging Anvil""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.CELESTIAL_FORGING_ANVIL_PORTAL.asItem(), """ Teleports players and entities between two portals Requires a Celestial Forging Anvil with an established wormhole connection""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.DRAIN.asItem(), """ Draining: when more than 1 B is stored and there is space below, outputs fluid downward and fills the entire space from the bottom up Suction: when less than 3 B is stored and the same fluid is above, draws fluid from above and can empty the entire space above Does not interact with fluid at the same height; fluid can be stored for free only when it forms an infinite source""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.REDSTONE_WIRE.asItem(), """ It can be attached to any full face of a block, only inputs and outputs redstone signals at its breaks (ends) The redstone signal level does not decay within the wire, and the wire will not output the signal received from redstone dust back to redstone dust""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.TRADING_STATION.asItem(), """ Can be set to trade with players or villagers Villagers will actively trade with stations that have valid offers and fair prices Has 12 slots for temporary item storage""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.CHUTE.asItem(), """ Can set item filter Shift and left-click a slot to disable it @@ -652,7 +652,7 @@ only inputs and outputs redstone signals at its breaks (ends) Multiple Chutes connected turn into a Simple Chute Simple Chute has only one slot and cannot be locked by redstone""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModBlocks.MAGNETIC_CHUTE.asItem(), """ The output items will be launched with speed Can set item filter @@ -661,31 +661,31 @@ only inputs and outputs redstone signals at its breaks (ends) Multiple Magnetic Chutes connected turn into a Simple Magnetic Chute Simple Magnetic Chute has only one slot and cannot be locked by redstone""" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.DRAGON_ROD.asItem(), "Portable block devourer, left-click to mine, right-click to adjust range, larger range costs more durability" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.EMBER_DRAGON_ROD.asItem(), "Portable block devourer, left-click to mine, right-click to adjust range, larger range costs more durability" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.FROST_DRAGON_ROD.asItem(), "Portable block devourer, left-click to mine, right-click to adjust range, larger range costs more durability" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.ROYAL_DRAGON_ROD.asItem(), "Portable block devourer, left-click to mine, right-click to adjust range, larger range costs more durability" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.TRANSCENDENCE_DRAGON_ROD.asItem(), "Portable block devourer, left-click to mine, right-click to adjust range, larger range costs more durability" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.PILL_BOX.asItem(), "Store pills, right-click to take one pill each, and press [%s] to use them in the inventory" ); - SHIFT.put( + ItemTooltipManager.SHIFT.put( ModItems.AMULET_BOX.asItem(), """ Stores multiple active amulets or totems Right click to store the Totems of Undying on your inventory, and shift-right-click to retrieve the totems; @@ -694,8 +694,8 @@ only inputs and outputs redstone signals at its breaks (ends) // NORMAL 优先:基础 key 使用短文本,SHIFT 仅用于 .shift key Map allTooltips = Maps.newHashMap(); - allTooltips.putAll(SHIFT); - allTooltips.putAll(NORMAL); + allTooltips.putAll(ItemTooltipManager.SHIFT); + allTooltips.putAll(ItemTooltipManager.NORMAL); NEED_TOOLTIP_ITEMS = Collections.unmodifiableMap(allTooltips); } @@ -721,19 +721,19 @@ public static void addTooltip(ItemStack stack, Consumer builder, Tool ).withColor(0xFFAA00)); } else { ItemTooltipManager.addNormalTooltip(builder, item); - builder.accept(SHIFT_TIP); + builder.accept(ItemTooltipManager.SHIFT_TIP); } - } else if (SHIFT.containsKey(item)) { + } else if (ItemTooltipManager.SHIFT.containsKey(item)) { // SHIFT 物品:默认显示短文本+提示,按住 Shift 显示长文本(.shift) if (flags.hasShiftDown()) { ItemTooltipManager.addShiftTooltip(builder, item); } else { - if (NORMAL.containsKey(item)) { + if (ItemTooltipManager.NORMAL.containsKey(item)) { ItemTooltipManager.addNormalTooltip(builder, item); } - builder.accept(SHIFT_TIP); + builder.accept(ItemTooltipManager.SHIFT_TIP); } - } else if (NORMAL.containsKey(item)) { + } else if (ItemTooltipManager.NORMAL.containsKey(item)) { ItemTooltipManager.addNormalTooltip(builder, item); } if (stack.is(ModItemTags.REINFORCED_CONCRETE)) { @@ -758,7 +758,7 @@ private static void addNormalTooltip(Consumer builder, Item item) { private static void addShiftTooltip(Consumer builder, Item item) { if (item == ModItems.PILL_BOX.asItem()) { builder.accept(Component.translatable( - getTranslationKeyShift(item), + ItemTooltipManager.getTranslationKeyShift(item), Component.keybind("key.anvilcraft.use_pill_box") ).withStyle(ChatFormatting.GRAY)); return; @@ -772,10 +772,10 @@ public static String getTranslationKey(Item item) { } public static String getTranslationKeyShift(Item item) { - return getTranslationKey(item) + ".shift"; + return ItemTooltipManager.getTranslationKey(item) + ".shift"; } public static Map getShiftMap() { - return Collections.unmodifiableMap(SHIFT); + return Collections.unmodifiableMap(ItemTooltipManager.SHIFT); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/TooltipRenderHelper.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/TooltipRenderHelper.java index e2cbb98b98..1adb72c391 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/TooltipRenderHelper.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/TooltipRenderHelper.java @@ -29,7 +29,7 @@ public static void renderOutline( VoxelShape shape, int color ) { - renderOutline( + TooltipRenderHelper.renderOutline( poseStack.last(), consumer, camX, @@ -51,7 +51,7 @@ public static void renderOutline( VoxelShape shape, int color ) { - renderShape( + TooltipRenderHelper.renderShape( poseStack, consumer, shape, @@ -128,7 +128,16 @@ public static void renderTooltipWithItemIcon( int finalVy = vy; int finalWidth = width; int finalHeight = height + 16; - renderTooltipBackground(graphics, vx, finalVy, finalWidth, finalHeight, backgroundColor, borderTopColor, borderBottomColor); + TooltipRenderHelper.renderTooltipBackground( + graphics, + vx, + finalVy, + finalWidth, + finalHeight, + backgroundColor, + borderTopColor, + borderBottomColor + ); graphics.item(itemStack, vx, vy); @@ -164,12 +173,12 @@ private static void renderTooltipBackground( int j = y - 3; int k = width + 3 + 3; int l = height + 3 + 3; - renderHorizontalLine(graphics, i, j - 1, k, backgroundColor); - renderHorizontalLine(graphics, i, j + l, k, backgroundColor); - renderRectangle(graphics, i, j, k, l, backgroundColor); - renderVerticalLine(graphics, i - 1, j, l, backgroundColor); - renderVerticalLine(graphics, i + k, j, l, backgroundColor); - renderFrameGradient(graphics, i, j + 1, k, l, borderTopColor, borderBottomColor); + TooltipRenderHelper.renderHorizontalLine(graphics, i, j - 1, k, backgroundColor); + TooltipRenderHelper.renderHorizontalLine(graphics, i, j + l, k, backgroundColor); + TooltipRenderHelper.renderRectangle(graphics, i, j, k, l, backgroundColor); + TooltipRenderHelper.renderVerticalLine(graphics, i - 1, j, l, backgroundColor); + TooltipRenderHelper.renderVerticalLine(graphics, i + k, j, l, backgroundColor); + TooltipRenderHelper.renderFrameGradient(graphics, i, j + 1, k, l, borderTopColor, borderBottomColor); } private static void renderFrameGradient( @@ -181,10 +190,10 @@ private static void renderFrameGradient( int topColor, int bottomColor ) { - renderVerticalLineGradient(graphics, x, y, height - 2, topColor, bottomColor); - renderVerticalLineGradient(graphics, x + width - 1, y, height - 2, topColor, bottomColor); - renderHorizontalLine(graphics, x, y - 1, width, topColor); - renderHorizontalLine(graphics, x, y - 1 + height - 1, width, bottomColor); + TooltipRenderHelper.renderVerticalLineGradient(graphics, x, y, height - 2, topColor, bottomColor); + TooltipRenderHelper.renderVerticalLineGradient(graphics, x + width - 1, y, height - 2, topColor, bottomColor); + TooltipRenderHelper.renderHorizontalLine(graphics, x, y - 1, width, topColor); + TooltipRenderHelper.renderHorizontalLine(graphics, x, y - 1 + height - 1, width, bottomColor); } private static void renderVerticalLine(GuiGraphicsExtractor graphics, int x, int y, int length, int color) { diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/HeatableBlockTooltipProvider.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/HeatableBlockTooltipProvider.java index d48179c821..bb4fd6366f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/HeatableBlockTooltipProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/HeatableBlockTooltipProvider.java @@ -74,7 +74,7 @@ private void refreshDuration(BlockEntity entity) { if (this.pendingDuration != null || level.getGameTime() < this.nextDurationRefresh) { return; } - this.nextDurationRefresh = level.getGameTime() + DURATION_REFRESH_INTERVAL; + this.nextDurationRefresh = level.getGameTime() + HeatableBlockTooltipProvider.DURATION_REFRESH_INTERVAL; this.pendingDuration = RPC.invoke(RpcTarget.server(), HeatableBlockEntity::getDuration, entity.getBlockPos()) .thenApply(OptionalInt::of) .exceptionally(_ -> OptionalInt.empty()); diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/LargeCauldronTooltipProvider.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/LargeCauldronTooltipProvider.java index f206e0e5ae..d966fe8c35 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/LargeCauldronTooltipProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/LargeCauldronTooltipProvider.java @@ -34,24 +34,29 @@ public List tooltip(BlockEntity value) { List previews = cauldron.getRecipePreviews(); List lines = new ArrayList<>(); - lines.add(heading("tooltip.anvilcraft.large_cauldron.inputs")); + lines.add(LargeCauldronTooltipProvider.heading("tooltip.anvilcraft.large_cauldron.inputs")); for (int slot = 0; slot < cauldron.getInputHandler().size(); slot++) { ItemStack stack = cauldron.getInputHandler().getStackInSlot(slot); if (stack.isEmpty()) continue; - lines.add(itemLine(stack, categoriesForSlot(previews, slot))); + lines.add(LargeCauldronTooltipProvider.itemLine(stack, LargeCauldronTooltipProvider.categoriesForSlot(previews, slot))); } - lines.add(heading("tooltip.anvilcraft.large_cauldron.outputs")); - for (ItemStack stack : aggregateOutputs(cauldron)) { - lines.add(itemLine(stack, categoriesForOutput(previews, cauldron, stack))); + lines.add(LargeCauldronTooltipProvider.heading("tooltip.anvilcraft.large_cauldron.outputs")); + for (ItemStack stack : LargeCauldronTooltipProvider.aggregateOutputs(cauldron)) { + lines.add( + LargeCauldronTooltipProvider.itemLine(stack, LargeCauldronTooltipProvider.categoriesForOutput(previews, cauldron, stack))); } - lines.add(heading("tooltip.anvilcraft.large_cauldron.fluids")); + lines.add(LargeCauldronTooltipProvider.heading("tooltip.anvilcraft.large_cauldron.fluids")); boolean topLayer = true; for (int tank = cauldron.getFluids().size() - 1; tank >= 0; tank--) { FluidStack fluid = cauldron.getFluids().getFluidInTank(tank); if (fluid.isEmpty()) continue; - lines.add(fluidLine(fluid, categoriesForFluid(previews, fluid), topLayer && cauldron.isIgnited())); + lines.add(LargeCauldronTooltipProvider.fluidLine( + fluid, + LargeCauldronTooltipProvider.categoriesForFluid(previews, fluid), + topLayer && cauldron.isIgnited() + )); topLayer = false; } return lines; @@ -66,7 +71,7 @@ private static Component itemLine(ItemStack stack, Set categories) { .append(stack.getHoverName()) .append(Component.literal(" x" + stack.getCount())) .withStyle(ChatFormatting.GRAY); - appendRecipeSuffix(line, categories); + LargeCauldronTooltipProvider.appendRecipeSuffix(line, categories); return ITooltipProvider.withIndentAndMerge(line); } @@ -80,7 +85,7 @@ private static Component fluidLine(FluidStack fluid, Set categories, boo "tooltip.anvilcraft.large_cauldron.burning" ).withStyle(ChatFormatting.RED)); } - appendRecipeSuffix(line, categories); + LargeCauldronTooltipProvider.appendRecipeSuffix(line, categories); return ITooltipProvider.withIndentAndMerge(line); } @@ -134,7 +139,7 @@ private static Set categoriesForOutput( ) { Set result = new LinkedHashSet<>(); for (int slot = 0; slot < cauldron.getOutputHandler().size(); slot++) { - ItemStack stack = stackInSlot(cauldron, slot); + ItemStack stack = LargeCauldronTooltipProvider.stackInSlot(cauldron, slot); if (!ItemStack.isSameItemSameComponents(displayed, stack)) continue; for (LargeCauldronBlockEntity.RecipePreview preview : previews) { if (preview.outputSlot() == slot) result.add(preview.categoryPath()); @@ -146,7 +151,7 @@ private static Set categoriesForOutput( private static List aggregateOutputs(LargeCauldronBlockEntity cauldron) { List result = new ArrayList<>(); for (int slot = 0; slot < cauldron.getOutputHandler().size(); slot++) { - ItemStack stack = stackInSlot(cauldron, slot); + ItemStack stack = LargeCauldronTooltipProvider.stackInSlot(cauldron, slot); if (stack.isEmpty()) continue; ItemStack existing = null; for (ItemStack candidate : result) { diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/RedstoneWireTooltipProvider.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/RedstoneWireTooltipProvider.java index 5493c82024..aabef4f4f0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/RedstoneWireTooltipProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/RedstoneWireTooltipProvider.java @@ -14,6 +14,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.neoforged.neoforge.client.network.ClientPacketDistributor; +import org.jspecify.annotations.Nullable; import java.util.ArrayList; import java.util.List; @@ -32,12 +33,12 @@ public class RedstoneWireTooltipProvider extends ITooltipProvider.BlockTooltipPr /** 客户端每个位置上次发包的游戏时间。 */ private static final Long2LongOpenHashMap LAST_REQUEST = new Long2LongOpenHashMap(); /** 上述位置缓存所属的客户端世界。 */ - private static Level cachedLevel; + private static @Nullable Level cachedLevel; static { // 使用不会与合法红石强度重叠的哨兵值,避免额外维护 containsKey 集合。 - NON_DUST_POWER.defaultReturnValue(-1); - LAST_REQUEST.defaultReturnValue(Long.MIN_VALUE); + RedstoneWireTooltipProvider.NON_DUST_POWER.defaultReturnValue(-1); + RedstoneWireTooltipProvider.LAST_REQUEST.defaultReturnValue(Long.MIN_VALUE); } @Override @@ -51,13 +52,13 @@ public List tooltip(Level level, BlockPos pos, BlockState state) { // 遵守统一兼容配置,避免 Jade 与铁砧锤 HUD 在同一位置重复显示信息。 return List.of(); } - ensureLevel(level); + RedstoneWireTooltipProvider.ensureLevel(level); long packedPos = pos.asLong(); long gameTime = level.getGameTime(); - long lastRequest = LAST_REQUEST.get(packedPos); - if (lastRequest == Long.MIN_VALUE || gameTime - lastRequest >= REQUEST_INTERVAL) { + long lastRequest = RedstoneWireTooltipProvider.LAST_REQUEST.get(packedPos); + if (lastRequest == Long.MIN_VALUE || gameTime - lastRequest >= RedstoneWireTooltipProvider.REQUEST_INTERVAL) { // HUD 可能每帧调用 tooltip,按游戏刻限频可显著减少客户端到服务端的小包数量。 - LAST_REQUEST.put(packedPos, gameTime); + RedstoneWireTooltipProvider.LAST_REQUEST.put(packedPos, gameTime); ClientPacketDistributor.sendToServer(new RedstoneWirePowerRequestPacket(pos)); } @@ -66,7 +67,7 @@ public List tooltip(Level level, BlockPos pos, BlockState state) { lines.add(Component.translatable( "tooltip.anvilcraft.redstone.power", RedstoneWireNetworkManager.getPower(level, pos) ).withStyle(ChatFormatting.GRAY)); - int nonDustPower = NON_DUST_POWER.get(packedPos); + int nonDustPower = RedstoneWireTooltipProvider.NON_DUST_POWER.get(packedPos); if (nonDustPower >= 0) { // 收到服务端权威值之前不显示占位数字,避免把“未知”误导成真实的零输出。 lines.add(Component.translatable( @@ -83,17 +84,17 @@ public int priority() { /** 接收服务端返回的非红石粉输入强度并更新当前位置缓存。 */ public static void receive(Level level, BlockPos pos, int nonDustPower) { - ensureLevel(level); - NON_DUST_POWER.put(pos.asLong(), nonDustPower); + RedstoneWireTooltipProvider.ensureLevel(level); + RedstoneWireTooltipProvider.NON_DUST_POWER.put(pos.asLong(), nonDustPower); } private static void ensureLevel(Level level) { - if (cachedLevel == level) { + if (RedstoneWireTooltipProvider.cachedLevel == level) { return; } // 方块坐标在不同维度会重复,切换世界后必须整体清空,不能复用上一维度的数据和限频时间。 - cachedLevel = level; - NON_DUST_POWER.clear(); - LAST_REQUEST.clear(); + RedstoneWireTooltipProvider.cachedLevel = level; + RedstoneWireTooltipProvider.NON_DUST_POWER.clear(); + RedstoneWireTooltipProvider.LAST_REQUEST.clear(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/ShulkerContainerTooltipProvider.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/ShulkerContainerTooltipProvider.java index 4e6361c900..38b6017b22 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/ShulkerContainerTooltipProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/impl/ShulkerContainerTooltipProvider.java @@ -77,15 +77,15 @@ private void refreshUpgradeCount(BlockEntity value) { if (this.pendingUpgradeCount != null || level.getGameTime() < this.nextMetadataRefresh) { return; } - this.nextMetadataRefresh = level.getGameTime() + METADATA_REFRESH_INTERVAL; + this.nextMetadataRefresh = level.getGameTime() + ShulkerContainerTooltipProvider.METADATA_REFRESH_INTERVAL; this.pendingUpgradeCount = StorageClientStub.loadMetadata(value.getBlockPos()) - .thenApply(metadata -> OptionalInt.of(calculateUpgradeCount(metadata.capacity().spaceSize()))) + .thenApply(metadata -> OptionalInt.of(ShulkerContainerTooltipProvider.calculateUpgradeCount(metadata.capacity().spaceSize()))) .exceptionally(_ -> OptionalInt.empty()); } private static int calculateUpgradeCount(int spaceSize) { int upgradeCount = 0; - while (spaceSize > INITIAL_SPACE_SIZE) { + while (spaceSize > ShulkerContainerTooltipProvider.INITIAL_SPACE_SIZE) { spaceSize /= 2; upgradeCount++; } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/providers/IItemTooltipProvider.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/providers/IItemTooltipProvider.java new file mode 100644 index 0000000000..4499d83d14 --- /dev/null +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/providers/IItemTooltipProvider.java @@ -0,0 +1,19 @@ +package dev.dubhe.anvilcraft.api.tooltip.providers; + +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.component.TooltipDisplay; + +import java.util.function.Consumer; + +public interface IItemTooltipProvider { + void appendItemTooltip( + ItemStack stack, + Item.TooltipContext context, + TooltipDisplay display, + Consumer builder, + TooltipFlag tooltipFlag + ); +} diff --git a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/providers/ITooltipProvider.java b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/providers/ITooltipProvider.java index f00815df0c..4f1fd2f94e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/tooltip/providers/ITooltipProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/tooltip/providers/ITooltipProvider.java @@ -77,7 +77,7 @@ public ItemStack icon(BlockEntity value) { } static Component withIndentAndMerge(Component... components) { - MutableComponent indentation = INDENTATION.copy(); + MutableComponent indentation = ITooltipProvider.INDENTATION.copy(); for (Component component : components) { indentation.append(component); } diff --git a/src/main/java/dev/dubhe/anvilcraft/api/world/load/LevelLoadManager.java b/src/main/java/dev/dubhe/anvilcraft/api/world/load/LevelLoadManager.java index c6716c1f4f..fcbb18df63 100644 --- a/src/main/java/dev/dubhe/anvilcraft/api/world/load/LevelLoadManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/api/world/load/LevelLoadManager.java @@ -19,43 +19,43 @@ public class LevelLoadManager { private static final Map, Map> CHUNK_REF_COUNT = new HashMap<>(); public static void register(BlockPos centerPos, LoadChunkData data, ServerLevel level) { - if (LOAD_DATA_MAP.containsKey(centerPos)) return; - LOAD_DATA_MAP.put(centerPos, data); - reload(level); + if (LevelLoadManager.LOAD_DATA_MAP.containsKey(centerPos)) return; + LevelLoadManager.LOAD_DATA_MAP.put(centerPos, data); + LevelLoadManager.reload(level); } public static boolean checkRegistered(BlockPos pos) { - return LOAD_DATA_MAP.containsKey(pos); + return LevelLoadManager.LOAD_DATA_MAP.containsKey(pos); } public static void unregister(BlockPos centerPos, Level level) { - LoadChunkData data = LOAD_DATA_MAP.get(centerPos); + LoadChunkData data = LevelLoadManager.LOAD_DATA_MAP.get(centerPos); if (data == null) return; data.markRemoved(); if (level instanceof ServerLevel serverLevel) { - reload(serverLevel); + LevelLoadManager.reload(serverLevel); } } static void lazy(Runnable task) { - if (serverStarted) { + if (LevelLoadManager.serverStarted) { task.run(); } else { - deferredTasks.add(task); + LevelLoadManager.deferredTasks.add(task); } } public static void notifyServerStarted() { - serverStarted = true; - while (!deferredTasks.isEmpty()) { - deferredTasks.poll().run(); + LevelLoadManager.serverStarted = true; + while (!LevelLoadManager.deferredTasks.isEmpty()) { + LevelLoadManager.deferredTasks.poll().run(); } } public static void forceChunk(int chunkX, int chunkZ, boolean load, ServerLevel level) { ChunkPos cp = new ChunkPos(chunkX, chunkZ); ResourceKey dim = level.dimension(); - Map refMap = CHUNK_REF_COUNT.computeIfAbsent(dim, k -> new HashMap<>()); + Map refMap = LevelLoadManager.CHUNK_REF_COUNT.computeIfAbsent(dim, k -> new HashMap<>()); int count = refMap.getOrDefault(cp, 0); if (load) { @@ -72,26 +72,26 @@ public static void forceChunk(int chunkX, int chunkZ, boolean load, ServerLevel } public static void reload(ServerLevel level) { - LOAD_DATA_MAP.values().stream() + LevelLoadManager.LOAD_DATA_MAP.values().stream() .filter(LoadChunkData::isRemoved) .forEach(d -> d.discard(level)); - LOAD_DATA_MAP.values().stream() + LevelLoadManager.LOAD_DATA_MAP.values().stream() .filter(d -> !d.isRemoved()) .forEach(d -> d.apply(level)); - LOAD_DATA_MAP.values().removeIf(LoadChunkData::isRemoved); + LevelLoadManager.LOAD_DATA_MAP.values().removeIf(LoadChunkData::isRemoved); } public static void removeAll(ServerLevel level) { - LOAD_DATA_MAP.values().forEach(d -> { + LevelLoadManager.LOAD_DATA_MAP.values().forEach(d -> { d.markRemoved(); d.discard(level); }); - LOAD_DATA_MAP.clear(); - CHUNK_REF_COUNT.clear(); + LevelLoadManager.LOAD_DATA_MAP.clear(); + LevelLoadManager.CHUNK_REF_COUNT.clear(); } public static int getOverseerChunkCount(BlockPos centerPos) { - LoadChunkData data = LOAD_DATA_MAP.get(centerPos); + LoadChunkData data = LevelLoadManager.LOAD_DATA_MAP.get(centerPos); return (data != null && !data.isRemoved() && data.getSource() == LoadChunkData.Source.OVERSEER) @@ -100,7 +100,7 @@ public static int getOverseerChunkCount(BlockPos centerPos) { } public static int getAllOverseerForcedChunkCount(ServerLevel level) { - return LOAD_DATA_MAP.values().stream() + return LevelLoadManager.LOAD_DATA_MAP.values().stream() .filter(data -> !data.isRemoved()) .filter(data -> data.getSource() == LoadChunkData.Source.OVERSEER) .filter(data -> data.getServerLevel().dimension().equals(level.dimension())) @@ -109,4 +109,4 @@ public static int getAllOverseerForcedChunkCount(ServerLevel level) { .mapToInt(cp -> 1) .sum(); } -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/block/LargeCauldronBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/LargeCauldronBlock.java index 71a8e3a09b..255f0112ca 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/LargeCauldronBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/LargeCauldronBlock.java @@ -32,7 +32,6 @@ import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; @@ -59,11 +58,11 @@ public class LargeCauldronBlock private static final double WALL_THICKNESS = 0.25; private static final double BOTTOM_WALL_MIN_Y = 0.5; private static final double CLIMBING_EPSILON = 1.0E-5; - private static final Map SHAPES = createShapes(); + private static final Map SHAPES = LargeCauldronBlock.createShapes(); public LargeCauldronBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(HALF, Cube3x3PartHalf.BOTTOM_CENTER)); + this.registerDefaultState(this.stateDefinition.any().setValue(LargeCauldronBlock.HALF, Cube3x3PartHalf.BOTTOM_CENTER)); } @Override @@ -73,22 +72,22 @@ public Vec3i getMainPartOffset() { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF); + builder.add(LargeCauldronBlock.HALF); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)); + return state.setValue(LargeCauldronBlock.HALF, state.getValue(LargeCauldronBlock.HALF).rotate(rotation)); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)); + return state.setValue(LargeCauldronBlock.HALF, state.getValue(LargeCauldronBlock.HALF).mirror(mirror)); } @Override public Property getPart() { - return HALF; + return LargeCauldronBlock.HALF; } @Override @@ -149,33 +148,33 @@ public BlockEntityTicker getTicker( @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - Cube3x3PartHalf part = state.getValue(HALF); + Cube3x3PartHalf part = state.getValue(LargeCauldronBlock.HALF); if (part.getOffsetY() == 2 && context.isHoldingItem(ModBlocks.GIANT_ANVIL.asItem())) { return Shapes.block(); } - return SHAPES.get(part); + return LargeCauldronBlock.SHAPES.get(part); } @Override public boolean isLadder(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity) { - return entity != null && touchesWall(state, pos, entity.getBoundingBox()); + return LargeCauldronBlock.touchesWall(state, pos, entity.getBoundingBox()); } public static @Nullable BlockPos findClimbableWall(LevelReader level, LivingEntity entity) { AABB box = entity.getBoundingBox(); BlockPos min = BlockPos.containing( - box.minX - CLIMBING_EPSILON, - box.minY - CLIMBING_EPSILON, - box.minZ - CLIMBING_EPSILON + box.minX - LargeCauldronBlock.CLIMBING_EPSILON, + box.minY - LargeCauldronBlock.CLIMBING_EPSILON, + box.minZ - LargeCauldronBlock.CLIMBING_EPSILON ); BlockPos max = BlockPos.containing( - box.maxX + CLIMBING_EPSILON, - box.maxY + CLIMBING_EPSILON, - box.maxZ + CLIMBING_EPSILON + box.maxX + LargeCauldronBlock.CLIMBING_EPSILON, + box.maxY + LargeCauldronBlock.CLIMBING_EPSILON, + box.maxZ + LargeCauldronBlock.CLIMBING_EPSILON ); for (BlockPos pos : BlockPos.betweenClosed(min, max)) { BlockState state = level.getBlockState(pos); - if (state.getBlock() instanceof LargeCauldronBlock && touchesWall(state, pos, box)) { + if (state.getBlock() instanceof LargeCauldronBlock && LargeCauldronBlock.touchesWall(state, pos, box)) { return pos.immutable(); } } @@ -183,30 +182,31 @@ public boolean isLadder(BlockState state, LevelReader level, BlockPos pos, Livin } private static boolean touchesWall(BlockState state, BlockPos pos, AABB box) { - Cube3x3PartHalf part = state.getValue(HALF); - double wallMinY = pos.getY() + (part.getOffsetY() == 0 ? BOTTOM_WALL_MIN_Y : 0.0); + Cube3x3PartHalf part = state.getValue(LargeCauldronBlock.HALF); + double wallMinY = pos.getY() + (part.getOffsetY() == 0 ? LargeCauldronBlock.BOTTOM_WALL_MIN_Y : 0.0); double wallMaxY = pos.getY() + 1.0; - if (!overlaps(box.minY, box.maxY, wallMinY, wallMaxY)) return false; + if (!LargeCauldronBlock.overlaps(box.minY, box.maxY, wallMinY, wallMaxY)) return false; - if (part.getOffsetX() != 0 && overlaps(box.minZ, box.maxZ, pos.getZ(), pos.getZ() + 1.0)) { - double wallMinX = pos.getX() + (part.getOffsetX() < 0 ? 0.0 : 1.0 - WALL_THICKNESS); - double wallMaxX = wallMinX + WALL_THICKNESS; - if (touches(box.minX, box.maxX, wallMinX, wallMaxX)) return true; + if (part.getOffsetX() != 0 && LargeCauldronBlock.overlaps(box.minZ, box.maxZ, pos.getZ(), pos.getZ() + 1.0)) { + double wallMinX = pos.getX() + (part.getOffsetX() < 0 ? 0.0 : 1.0 - LargeCauldronBlock.WALL_THICKNESS); + double wallMaxX = wallMinX + LargeCauldronBlock.WALL_THICKNESS; + if (LargeCauldronBlock.touches(box.minX, box.maxX, wallMinX, wallMaxX)) return true; } - if (part.getOffsetZ() != 0 && overlaps(box.minX, box.maxX, pos.getX(), pos.getX() + 1.0)) { - double wallMinZ = pos.getZ() + (part.getOffsetZ() < 0 ? 0.0 : 1.0 - WALL_THICKNESS); - double wallMaxZ = wallMinZ + WALL_THICKNESS; - return touches(box.minZ, box.maxZ, wallMinZ, wallMaxZ); + if (part.getOffsetZ() != 0 && LargeCauldronBlock.overlaps(box.minX, box.maxX, pos.getX(), pos.getX() + 1.0)) { + double wallMinZ = pos.getZ() + (part.getOffsetZ() < 0 ? 0.0 : 1.0 - LargeCauldronBlock.WALL_THICKNESS); + double wallMaxZ = wallMinZ + LargeCauldronBlock.WALL_THICKNESS; + return LargeCauldronBlock.touches(box.minZ, box.maxZ, wallMinZ, wallMaxZ); } return false; } private static boolean touches(double min, double max, double wallMin, double wallMax) { - return Math.abs(max - wallMin) <= CLIMBING_EPSILON || Math.abs(min - wallMax) <= CLIMBING_EPSILON; + return Math.abs(max - wallMin) <= LargeCauldronBlock.CLIMBING_EPSILON || Math.abs(min - wallMax) + <= LargeCauldronBlock.CLIMBING_EPSILON; } private static boolean overlaps(double min, double max, double otherMin, double otherMax) { - return max > otherMin + CLIMBING_EPSILON && min < otherMax - CLIMBING_EPSILON; + return max > otherMin + LargeCauldronBlock.CLIMBING_EPSILON && min < otherMax - LargeCauldronBlock.CLIMBING_EPSILON; } @Override @@ -214,11 +214,6 @@ protected VoxelShape getInteractionShape(BlockState state, BlockGetter level, Bl return Shapes.block(); } - @Override - protected RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } - @Override protected boolean propagatesSkylightDown(BlockState state) { return true; @@ -262,8 +257,8 @@ protected InteractionResult useItemOn( if (FluidInteractionItems.isFluidInteractionItem(stack)) { return Util.sidedSuccess(level); } - if (isExtractionSurface(state, hit) && hand == InteractionHand.MAIN_HAND) { - int slot = LargeCauldronBlockEntity.inputSlotForPart(state.getValue(HALF)); + if (LargeCauldronBlock.isExtractionSurface(state, hit) && hand == InteractionHand.MAIN_HAND) { + int slot = LargeCauldronBlockEntity.inputSlotForPart(state.getValue(LargeCauldronBlock.HALF)); if (stack.isEmpty()) { return cauldron.extractItemsToHand(player, hand, slot) ? Util.sidedSuccess(level) @@ -285,10 +280,10 @@ protected InteractionResult useItemOn( } return Util.sidedSuccess(level); } - if (hand != InteractionHand.MAIN_HAND || stack.isEmpty() || !canInsertAt(state, hit)) { + if (hand != InteractionHand.MAIN_HAND || stack.isEmpty() || !LargeCauldronBlock.canInsertAt(state, hit)) { return InteractionResult.PASS; } - int preferredSlot = LargeCauldronBlockEntity.inputSlotForPart(state.getValue(HALF)); + int preferredSlot = LargeCauldronBlockEntity.inputSlotForPart(state.getValue(LargeCauldronBlock.HALF)); if (level.isClientSide()) return InteractionResult.SUCCESS; return cauldron.insertFromHand(stack, preferredSlot) ? InteractionResult.SUCCESS @@ -296,13 +291,13 @@ protected InteractionResult useItemOn( } private static boolean canInsertAt(BlockState state, BlockHitResult hit) { - Cube3x3PartHalf part = state.getValue(HALF); + Cube3x3PartHalf part = state.getValue(LargeCauldronBlock.HALF); if (part.getOffsetY() != 2) return false; return hit.getDirection() == Direction.UP || hit.getDirection().getAxis().isHorizontal(); } private static boolean isExtractionSurface(BlockState state, BlockHitResult hit) { - return state.getValue(HALF).getOffsetY() == 0 && hit.getDirection() == Direction.UP; + return state.getValue(LargeCauldronBlock.HALF).getOffsetY() == 0 && hit.getDirection() == Direction.UP; } @Override @@ -314,8 +309,8 @@ protected InteractionResult useWithoutItem( BlockHitResult hit ) { if (!player.getMainHandItem().isEmpty()) return InteractionResult.PASS; - Cube3x3PartHalf part = state.getValue(HALF); - if (!isExtractionSurface(state, hit)) return InteractionResult.PASS; + Cube3x3PartHalf part = state.getValue(LargeCauldronBlock.HALF); + if (!LargeCauldronBlock.isExtractionSurface(state, hit)) return InteractionResult.PASS; LargeCauldronBlockEntity cauldron = LargeCauldronBlockEntity.getMain(level, pos, state); if (cauldron == null) return InteractionResult.PASS; int slot = LargeCauldronBlockEntity.inputSlotForPart(part); @@ -329,7 +324,7 @@ public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { if (!level.isClientSide() && entity instanceof ItemEntity item) { LargeCauldronBlockEntity cauldron = LargeCauldronBlockEntity.getMain(level, pos, state); if (cauldron != null) { - cauldron.absorbItem(item, LargeCauldronBlockEntity.inputSlotForPart(state.getValue(HALF))); + cauldron.absorbItem(item, LargeCauldronBlockEntity.inputSlotForPart(state.getValue(LargeCauldronBlock.HALF))); } } super.stepOn(level, pos, state, entity); @@ -347,7 +342,7 @@ protected void entityInside( if (level.isClientSide() || !(entity instanceof ItemEntity item)) return; LargeCauldronBlockEntity cauldron = LargeCauldronBlockEntity.getMain(level, pos, state); if (cauldron != null) { - cauldron.absorbItem(item, LargeCauldronBlockEntity.inputSlotForPart(state.getValue(HALF))); + cauldron.absorbItem(item, LargeCauldronBlockEntity.inputSlotForPart(state.getValue(LargeCauldronBlock.HALF))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireBlock.java index 12370b6034..039a03fa00 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireBlock.java @@ -42,7 +42,12 @@ public class RedstoneWireBlock extends Block implements IHammerRemovable { public static final EnumProperty EAST = EnumProperty.create("east", ConnectionType.class); public static final EnumProperty SOUTH = EnumProperty.create("south", ConnectionType.class); public static final EnumProperty WEST = EnumProperty.create("west", ConnectionType.class); - public static final List> CONNECTION_PROPERTIES = List.of(NORTH, EAST, SOUTH, WEST); + public static final List> CONNECTION_PROPERTIES = List.of( + RedstoneWireBlock.NORTH, + RedstoneWireBlock.EAST, + RedstoneWireBlock.SOUTH, + RedstoneWireBlock.WEST + ); /** 从导线位置指向其支撑方块的方向。 */ public static final EnumProperty ATTACHMENT = EnumProperty.create("attachment", Direction.class); /** 是否在中心绘制接线点。 */ @@ -58,8 +63,8 @@ public class RedstoneWireBlock extends Block implements IHammerRemovable { private static final int CONNECTION_TYPE_COUNT = ConnectionType.values().length; /** 影响形状的状态组合数:附着面 x 四个方向的连接类型 x 中心接点。 */ private static final int SHAPE_STATE_COUNT = - Direction.values().length * CONNECTION_TYPE_COUNT * CONNECTION_TYPE_COUNT - * CONNECTION_TYPE_COUNT * CONNECTION_TYPE_COUNT * 2; + Direction.values().length * RedstoneWireBlock.CONNECTION_TYPE_COUNT * RedstoneWireBlock.CONNECTION_TYPE_COUNT + * RedstoneWireBlock.CONNECTION_TYPE_COUNT * RedstoneWireBlock.CONNECTION_TYPE_COUNT * 2; /** * 按状态索引缓存合并后的形状。 * @@ -67,29 +72,32 @@ public class RedstoneWireBlock extends Block implements IHammerRemovable { * 每次都重新调用 {@code getShape};如果在这里现算 {@link Shapes#or},导线附近每个实体 * 每 tick 都会产生大量形状合并与分配。实际用到的组合远少于全部 7500 种,因此惰性填充。

*/ - private static final AtomicReferenceArray SHAPE_CACHE = - new AtomicReferenceArray<>(SHAPE_STATE_COUNT); + private static final AtomicReferenceArray<@Nullable VoxelShape> SHAPE_CACHE = + new AtomicReferenceArray<>(RedstoneWireBlock.SHAPE_STATE_COUNT); static { // 碰撞/选取形状只由附着方向和连接类型决定,预计算可避免每次光线检测都重复坐标变换与形状合并。 for (Direction attachment : Direction.values()) { - Direction north = getLocalDirection(attachment, 0); - DOT_SHAPES.put(attachment, transformedBox(attachment, north, 4.0, 0.0, 4.0, 12.0, 2.5, 12.0)); + Direction north = RedstoneWireBlock.getLocalDirection(attachment, 0); + RedstoneWireBlock.DOT_SHAPES.put( + attachment, + RedstoneWireBlock.transformedBox(attachment, north, 4.0, 0.0, 4.0, 12.0, 2.5, 12.0) + ); List sides = new ArrayList<>(4); List corners = new ArrayList<>(4); List specialCorners = new ArrayList<>(4); List ups = new ArrayList<>(4); for (int index = 0; index < 4; index++) { - Direction tangent = getLocalDirection(attachment, index); - sides.add(transformedBox(attachment, tangent, 5.0, 0.0, 0.0, 11.0, 2.0, 8.0)); - corners.add(transformedBox(attachment, tangent, 5.0, 0.0, -2.0, 11.0, 2.0, 8.0)); - specialCorners.add(transformedBox(attachment, tangent, 5.0, 0.0, -1.0, 11.0, 2.0, 8.0)); - ups.add(transformedBox(attachment, tangent, 5.0, 1.0, -0.1, 11.0, 18.0, 2.0)); + Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); + sides.add(RedstoneWireBlock.transformedBox(attachment, tangent, 5.0, 0.0, 0.0, 11.0, 2.0, 8.0)); + corners.add(RedstoneWireBlock.transformedBox(attachment, tangent, 5.0, 0.0, -2.0, 11.0, 2.0, 8.0)); + specialCorners.add(RedstoneWireBlock.transformedBox(attachment, tangent, 5.0, 0.0, -1.0, 11.0, 2.0, 8.0)); + ups.add(RedstoneWireBlock.transformedBox(attachment, tangent, 5.0, 1.0, -0.1, 11.0, 18.0, 2.0)); } - SIDE_SHAPES.put(attachment, List.copyOf(sides)); - CORNER_SHAPES.put(attachment, List.copyOf(corners)); - CORNER_SP_SHAPES.put(attachment, List.copyOf(specialCorners)); - UP_SHAPES.put(attachment, List.copyOf(ups)); + RedstoneWireBlock.SIDE_SHAPES.put(attachment, List.copyOf(sides)); + RedstoneWireBlock.CORNER_SHAPES.put(attachment, List.copyOf(corners)); + RedstoneWireBlock.CORNER_SP_SHAPES.put(attachment, List.copyOf(specialCorners)); + RedstoneWireBlock.UP_SHAPES.put(attachment, List.copyOf(ups)); } } @@ -97,19 +105,19 @@ public RedstoneWireBlock(Properties properties) { super(properties); // 默认保留一条南北向直线,使孤立导线刚放下时也有可见且可重新定向的形状。 this.registerDefaultState(this.stateDefinition.any() - .setValue(NORTH, ConnectionType.SIDE) - .setValue(EAST, ConnectionType.NONE) - .setValue(SOUTH, ConnectionType.SIDE) - .setValue(WEST, ConnectionType.NONE) - .setValue(ATTACHMENT, Direction.DOWN) - .setValue(DOT, false)); + .setValue(RedstoneWireBlock.NORTH, ConnectionType.SIDE) + .setValue(RedstoneWireBlock.EAST, ConnectionType.NONE) + .setValue(RedstoneWireBlock.SOUTH, ConnectionType.SIDE) + .setValue(RedstoneWireBlock.WEST, ConnectionType.NONE) + .setValue(RedstoneWireBlock.ATTACHMENT, Direction.DOWN) + .setValue(RedstoneWireBlock.DOT, false)); } @Override public BlockState getStateForPlacement(BlockPlaceContext context) { Direction attachment = context.getClickedFace().getOpposite(); - BlockState state = emptyState(this.defaultBlockState().setValue(ATTACHMENT, attachment)); - Direction preferred = getLocalDirection(attachment, 0); + BlockState state = RedstoneWireBlock.emptyState(this.defaultBlockState().setValue(RedstoneWireBlock.ATTACHMENT, attachment)); + Direction preferred = RedstoneWireBlock.getLocalDirection(attachment, 0); // 用玩家视线在附着面上的主要方向决定孤立导线朝向,避免墙面导线总沿固定世界轴放置。 for (Direction direction : context.getNearestLookingDirections()) { if (direction.getAxis() != attachment.getAxis()) { @@ -117,16 +125,16 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { break; } } - int index = getLocalIndex(attachment, preferred); + int index = RedstoneWireBlock.getLocalIndex(attachment, preferred); // 先生成一条直线,再让 connectionState 根据真实邻居扩展为拐角、分叉或爬升形态。 - state = state.setValue(CONNECTION_PROPERTIES.get(index), ConnectionType.SIDE) - .setValue(CONNECTION_PROPERTIES.get((index + 2) % 4), ConnectionType.SIDE); + state = state.setValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index), ConnectionType.SIDE) + .setValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get((index + 2) % 4), ConnectionType.SIDE); return this.connectionState(context.getLevel(), context.getClickedPos(), state); } @Override protected boolean canSurvive(BlockState state, LevelReader level, BlockPos pos) { - Direction attachment = state.getValue(ATTACHMENT); + Direction attachment = state.getValue(RedstoneWireBlock.ATTACHMENT); BlockPos supportPos = pos.relative(attachment); BlockState support = level.getBlockState(supportPos); // 原版漏斗顶面可放红石粉,但其面坚固性判定不满足这里的通用条件,因此显式兼容。 @@ -136,42 +144,43 @@ protected boolean canSurvive(BlockState state, LevelReader level, BlockPos pos) @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - int key = shapeKey(state); - VoxelShape cached = SHAPE_CACHE.get(key); + int key = RedstoneWireBlock.shapeKey(state); + VoxelShape cached = RedstoneWireBlock.SHAPE_CACHE.get(key); if (cached != null) { return cached; } - VoxelShape shape = buildShape(state); + VoxelShape shape = RedstoneWireBlock.buildShape(state); // 同一状态在多线程下算出的形状等价,先写入者胜出即可,不需要额外同步。 - SHAPE_CACHE.compareAndSet(key, null, shape); + RedstoneWireBlock.SHAPE_CACHE.compareAndSet(key, null, shape); return shape; } /** 把影响形状的状态属性压成缓存下标。 */ private static int shapeKey(BlockState state) { - int key = state.getValue(ATTACHMENT).ordinal(); + int key = state.getValue(RedstoneWireBlock.ATTACHMENT).ordinal(); for (int index = 0; index < 4; index++) { - key = key * CONNECTION_TYPE_COUNT + state.getValue(CONNECTION_PROPERTIES.get(index)).ordinal(); + key = key * RedstoneWireBlock.CONNECTION_TYPE_COUNT + + state.getValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index)).ordinal(); } - return key * 2 + (state.getValue(DOT) ? 1 : 0); + return key * 2 + (state.getValue(RedstoneWireBlock.DOT) ? 1 : 0); } private static VoxelShape buildShape(BlockState state) { - Direction attachment = state.getValue(ATTACHMENT); - VoxelShape shape = state.getValue(DOT) ? DOT_SHAPES.get(attachment) : Shapes.empty(); + Direction attachment = state.getValue(RedstoneWireBlock.ATTACHMENT); + VoxelShape shape = state.getValue(RedstoneWireBlock.DOT) ? RedstoneWireBlock.DOT_SHAPES.get(attachment) : Shapes.empty(); for (int index = 0; index < 4; index++) { - ConnectionType side = state.getValue(CONNECTION_PROPERTIES.get(index)); + ConnectionType side = state.getValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index)); if (side.isConnected() && side != ConnectionType.CORNER && side != ConnectionType.CORNER_SP) { - shape = Shapes.or(shape, SIDE_SHAPES.get(attachment).get(index)); + shape = Shapes.or(shape, RedstoneWireBlock.SIDE_SHAPES.get(attachment).get(index)); } if (side == ConnectionType.CORNER) { - shape = Shapes.or(shape, CORNER_SHAPES.get(attachment).get(index)); + shape = Shapes.or(shape, RedstoneWireBlock.CORNER_SHAPES.get(attachment).get(index)); } if (side == ConnectionType.CORNER_SP) { - shape = Shapes.or(shape, CORNER_SP_SHAPES.get(attachment).get(index)); + shape = Shapes.or(shape, RedstoneWireBlock.CORNER_SP_SHAPES.get(attachment).get(index)); } if (side == ConnectionType.UP) { - shape = Shapes.or(shape, UP_SHAPES.get(attachment).get(index)); + shape = Shapes.or(shape, RedstoneWireBlock.UP_SHAPES.get(attachment).get(index)); } } return shape; @@ -211,7 +220,7 @@ protected void neighborChanged( return; } if (!state.canSurvive(level, pos)) { - dropResources(state, level, pos); + Block.dropResources(state, level, pos); level.removeBlock(pos, false); } else { // Orientation 仅在实验性红石模式下携带传播方向;普通模式由管理器扫描相邻方块。 @@ -241,8 +250,8 @@ public boolean canConnectRedstone( } else { terminalDirection = direction.getOpposite(); } - int index = getLocalIndex(state.getValue(ATTACHMENT), terminalDirection); - if (index < 0 || !state.getValue(CONNECTION_PROPERTIES.get(index)).isConnected()) { + int index = RedstoneWireBlock.getLocalIndex(state.getValue(RedstoneWireBlock.ATTACHMENT), terminalDirection); + if (index < 0 || !state.getValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index)).isConnected()) { return false; } // 内部接线端只负责连通网络;仅开放端点应被外部元件视为红石接口。 @@ -262,10 +271,10 @@ protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direc return 0; } Direction outputDirection = direction.getOpposite(); - int index = getLocalIndex(state.getValue(ATTACHMENT), outputDirection); + int index = RedstoneWireBlock.getLocalIndex(state.getValue(RedstoneWireBlock.ATTACHMENT), outputDirection); if (index < 0 - || !state.getValue(CONNECTION_PROPERTIES.get(index)).isConnected() - || isManuallyHidden(level, pos, state, index) + || !state.getValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index)).isConnected() + || RedstoneWireBlock.isManuallyHidden(level, pos, state, index) || this.hasWireConnection(level, pos, state, index)) { return 0; } @@ -281,19 +290,26 @@ protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direc @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(NORTH, EAST, SOUTH, WEST, ATTACHMENT, DOT); + builder.add( + RedstoneWireBlock.NORTH, + RedstoneWireBlock.EAST, + RedstoneWireBlock.SOUTH, + RedstoneWireBlock.WEST, + RedstoneWireBlock.ATTACHMENT, + RedstoneWireBlock.DOT + ); } private boolean hasWireConnection(BlockGetter level, BlockPos pos, BlockState state, int index) { - Connection[] cached = RedstoneWireNetworkManager.getConnections(level, pos); + var cached = RedstoneWireNetworkManager.getConnections(level, pos); // 客户端和缓存尚未建立的服务端仍需即时计算,保证外观与信号查询不会依赖事件执行顺序。 - return (cached == null ? findConnection(level, pos, state, index) : cached[index]) != null; + return (cached == null ? RedstoneWireBlock.findConnection(level, pos, state, index) : cached[index]) != null; } private boolean isOpenTerminal(BlockGetter level, BlockPos pos, BlockState state, int index) { - Connection[] cached = RedstoneWireNetworkManager.getConnections(level, pos); - return (cached == null ? findConnection(level, pos, state, index) : cached[index]) == null - && !isManuallyHidden(level, pos, state, index); + var cached = RedstoneWireNetworkManager.getConnections(level, pos); + return (cached == null ? RedstoneWireBlock.findConnection(level, pos, state, index) : cached[index]) == null + && !RedstoneWireBlock.isManuallyHidden(level, pos, state, index); } /** 供原版红石粉采样斜下方导线的非粉线信号,避免该特殊连接只改变外观。 */ @@ -306,13 +322,13 @@ public static int getUpwardDustSignal(BlockGetter level, BlockPos dustPos) { continue; } Direction attachment = towardWire.getOpposite(); - if (wireState.getValue(ATTACHMENT) != attachment) { + if (wireState.getValue(RedstoneWireBlock.ATTACHMENT) != attachment) { continue; } - int index = getLocalIndex(attachment, Direction.UP); + int index = RedstoneWireBlock.getLocalIndex(attachment, Direction.UP); if (index < 0 - || !wireState.getValue(CONNECTION_PROPERTIES.get(index)).isConnected() - || !hasUpwardDustConnection(level, wirePos, wireState, index) + || !wireState.getValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index)).isConnected() + || !RedstoneWireBlock.hasUpwardDustConnection(level, wirePos, wireState, index) || !wire.isOpenTerminal(level, wirePos, wireState, index)) { continue; } @@ -324,22 +340,22 @@ public static int getUpwardDustSignal(BlockGetter level, BlockPos dustPos) { /** 根据当前世界重新计算指定导线的四向外观状态。 */ BlockState connectionState(BlockGetter level, BlockPos pos, BlockState oldState) { - return this.connectionState(level, pos, oldState, findConnections(level, pos, oldState)); + return this.connectionState(level, pos, oldState, RedstoneWireBlock.findConnections(level, pos, oldState)); } /** 使用已经求出的连接关系生成方块状态,供网络重建时避免重复搜索。 */ BlockState connectionState( - BlockGetter level, BlockPos pos, BlockState oldState, Connection[] connections + BlockGetter level, BlockPos pos, BlockState oldState, @Nullable Connection[] connections ) { // 从空状态开始可以清除已经断开的旧方向,同时保留附着面。 - BlockState result = emptyState(this.defaultBlockState() - .setValue(ATTACHMENT, oldState.getValue(ATTACHMENT))); + BlockState result = RedstoneWireBlock.emptyState(this.defaultBlockState() + .setValue(RedstoneWireBlock.ATTACHMENT, oldState.getValue(RedstoneWireBlock.ATTACHMENT))); int forcedTerminalMask = RedstoneWireNetworkManager.getForcedTerminalMask(level, pos); int hiddenTerminalMask = RedstoneWireNetworkManager.getHiddenConnectionMask(level, pos); for (int index = 0; index < 4; index++) { - Connection connection = connections[index]; - EnumProperty property = CONNECTION_PROPERTIES.get(index); - ConnectionType side = getConnection( + var connection = connections[index]; + EnumProperty property = RedstoneWireBlock.CONNECTION_PROPERTIES.get(index); + ConnectionType side = RedstoneWireBlock.getConnection( level, pos, result, @@ -351,23 +367,23 @@ BlockState connectionState( result = result.setValue(property, side); } - int visibleMask = connectedMask(result); + int visibleMask = RedstoneWireBlock.connectedMask(result); int connectionCount = Integer.bitCount(visibleMask); if (connectionCount == 0) { // 孤立导线保留旧直线轴,即使两端均被手动断开也不能退化为空形态。 - int fallbackMask = fallbackMask(oldState); + int fallbackMask = RedstoneWireBlock.fallbackMask(oldState); for (int index = 0; index < 4; index++) { if ((fallbackMask & (1 << index)) != 0) { - result = result.setValue(CONNECTION_PROPERTIES.get(index), ConnectionType.SIDE); + result = result.setValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index), ConnectionType.SIDE); } } } else if (connectionCount == 1) { // 以最后剩下的方向为轴补齐反向,保证导线最少始终是一条直线。 int first = Integer.numberOfTrailingZeros(visibleMask); - result = result.setValue(CONNECTION_PROPERTIES.get((first + 2) % 4), ConnectionType.SIDE); + result = result.setValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get((first + 2) % 4), ConnectionType.SIDE); } - visibleMask = connectedMask(result); + visibleMask = RedstoneWireBlock.connectedMask(result); connectionCount = Integer.bitCount(visibleMask); int first = connectionCount == 0 ? -1 : Integer.numberOfTrailingZeros(visibleMask); int secondMask = first < 0 ? 0 : visibleMask & ~(1 << first); @@ -375,13 +391,13 @@ BlockState connectionState( // 直线不需要中心贴图;拐角或三岔以上需要中心点遮住各段模型的接缝。 boolean dot = connectionCount >= 3 || connectionCount == 2 && second != (first + 2) % 4; - return result.setValue(DOT, dot); + return result.setValue(RedstoneWireBlock.DOT, dot); } private static int connectedMask(BlockState state) { int mask = 0; for (int index = 0; index < 4; index++) { - if (state.getValue(CONNECTION_PROPERTIES.get(index)).isConnected()) { + if (state.getValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index)).isConnected()) { mask |= 1 << index; } } @@ -389,15 +405,16 @@ private static int connectedMask(BlockState state) { } private static int fallbackMask(BlockState oldState) { - boolean eastWest = oldState.getValue(EAST).isConnected() || oldState.getValue(WEST).isConnected(); + boolean eastWest = oldState.getValue(RedstoneWireBlock.EAST).isConnected() + || oldState.getValue(RedstoneWireBlock.WEST).isConnected(); return eastWest ? 0b1010 : 0b0101; } private static BlockState emptyState(BlockState state) { - for (EnumProperty property : CONNECTION_PROPERTIES) { + for (EnumProperty property : RedstoneWireBlock.CONNECTION_PROPERTIES) { state = state.setValue(property, ConnectionType.NONE); } - return state.setValue(DOT, false); + return state.setValue(RedstoneWireBlock.DOT, false); } private static ConnectionType getConnection( @@ -418,20 +435,20 @@ private static ConnectionType getConnection( } if (forcedTerminal) { // 强制端口不要求相邻已有红石元件;墙面向上的粉线连接仍使用专用短拐角。 - return hasUpwardDustConnection(level, pos, state, index) + return RedstoneWireBlock.hasUpwardDustConnection(level, pos, state, index) ? ConnectionType.CORNER_SP : ConnectionType.SIDE; } - if (hasDustConnection(level, pos, state, index)) { + if (RedstoneWireBlock.hasDustConnection(level, pos, state, index)) { // 原版粉线也是真实接入端;墙面向上的粉线使用专用短拐角避免模型插入粉线。 - return hasUpwardDustConnection(level, pos, state, index) + return RedstoneWireBlock.hasUpwardDustConnection(level, pos, state, index) ? ConnectionType.CORNER_SP : ConnectionType.SIDE; } - Direction tangent = getLocalDirection(state.getValue(ATTACHMENT), index); + Direction tangent = RedstoneWireBlock.getLocalDirection(state.getValue(RedstoneWireBlock.ATTACHMENT), index); BlockPos adjacentPos = pos.relative(tangent); BlockState adjacent = level.getBlockState(adjacentPos); - return canAttachTo(level, adjacentPos, adjacent, tangent) ? ConnectionType.SIDE : ConnectionType.NONE; + return RedstoneWireBlock.canAttachTo(level, adjacentPos, adjacent, tangent) ? ConnectionType.SIDE : ConnectionType.NONE; } private static boolean canAttachTo(BlockGetter level, BlockPos pos, BlockState state, Direction direction) { @@ -448,8 +465,8 @@ private static boolean canAttachTo(BlockGetter level, BlockPos pos, BlockState s /** 侧面导线向上断开时,检查支撑方块顶面的原版红石粉斜角连接。 */ private static boolean hasUpwardDustConnection(BlockGetter level, BlockPos pos, BlockState state, int index) { - Direction attachment = state.getValue(ATTACHMENT); - if (!attachment.getAxis().isHorizontal() || getLocalDirection(attachment, index) != Direction.UP) { + Direction attachment = state.getValue(RedstoneWireBlock.ATTACHMENT); + if (!attachment.getAxis().isHorizontal() || RedstoneWireBlock.getLocalDirection(attachment, index) != Direction.UP) { return false; } return level.getBlockState(pos.relative(attachment).above()).is(Blocks.REDSTONE_WIRE); @@ -457,11 +474,11 @@ private static boolean hasUpwardDustConnection(BlockGetter level, BlockPos pos, /** 原版红石粉只有与导线处于同一附着面,或位于墙面向上拐角时才算真实接入。 */ private static boolean hasDustConnection(BlockGetter level, BlockPos pos, BlockState state, int index) { - if (hasUpwardDustConnection(level, pos, state, index)) { + if (RedstoneWireBlock.hasUpwardDustConnection(level, pos, state, index)) { return true; } - Direction attachment = state.getValue(ATTACHMENT); - Direction tangent = getLocalDirection(attachment, index); + Direction attachment = state.getValue(RedstoneWireBlock.ATTACHMENT); + Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); if (attachment != Direction.DOWN || !tangent.getAxis().isHorizontal()) { return false; } @@ -472,19 +489,20 @@ private static boolean hasDustConnection(BlockGetter level, BlockPos pos, BlockS /** 该端口是否接入了自定义导线、原版粉线或普通红石元件,而不是单纯的直线外观回退。 */ static boolean hasConnectionTarget(BlockGetter level, BlockPos pos, BlockState state, int index) { - if (findConnection(level, pos, state, index) != null || hasDustConnection(level, pos, state, index)) { + if (RedstoneWireBlock.findConnection(level, pos, state, index) != null + || RedstoneWireBlock.hasDustConnection(level, pos, state, index)) { return true; } - Direction tangent = getLocalDirection(state.getValue(ATTACHMENT), index); + Direction tangent = RedstoneWireBlock.getLocalDirection(state.getValue(RedstoneWireBlock.ATTACHMENT), index); BlockPos adjacentPos = pos.relative(tangent); - return canAttachTo(level, adjacentPos, level.getBlockState(adjacentPos), tangent); + return RedstoneWireBlock.canAttachTo(level, adjacentPos, level.getBlockState(adjacentPos), tangent); } /** 返回开放端点实际对应的外部方块位置;斜角红石粉位于支撑方块的顶面。 */ static BlockPos terminalTarget(BlockGetter level, BlockPos pos, BlockState state, Direction tangent) { - int index = getLocalIndex(state.getValue(ATTACHMENT), tangent); - if (index >= 0 && hasUpwardDustConnection(level, pos, state, index)) { - return pos.relative(state.getValue(ATTACHMENT)).above(); + int index = RedstoneWireBlock.getLocalIndex(state.getValue(RedstoneWireBlock.ATTACHMENT), tangent); + if (index >= 0 && RedstoneWireBlock.hasUpwardDustConnection(level, pos, state, index)) { + return pos.relative(state.getValue(RedstoneWireBlock.ATTACHMENT)).above(); } return pos.relative(tangent); } @@ -496,14 +514,14 @@ static BlockPos terminalTarget(BlockGetter level, BlockPos pos, BlockState state */ @Nullable static Connection findConnection(BlockGetter level, BlockPos pos, BlockState state, int index) { - Connection geometric = findGeometricConnection(level, pos, state, index); - if (geometric == null || isPortHidden(level, pos, index)) { + Connection geometric = RedstoneWireBlock.findGeometricConnection(level, pos, state, index); + if (geometric == null || RedstoneWireBlock.isPortHidden(level, pos, index)) { return null; } int connectedCount = 0; for (long neighbor : geometric.positions()) { - if (!isNeighborPortHidden(level, pos, BlockPos.of(neighbor))) { + if (!RedstoneWireBlock.isNeighborPortHidden(level, pos, BlockPos.of(neighbor))) { connectedCount++; } } @@ -516,7 +534,7 @@ static Connection findConnection(BlockGetter level, BlockPos pos, BlockState sta long[] connectedNeighbors = new long[connectedCount]; int targetIndex = 0; for (long neighbor : geometric.positions()) { - if (!isNeighborPortHidden(level, pos, BlockPos.of(neighbor))) { + if (!RedstoneWireBlock.isNeighborPortHidden(level, pos, BlockPos.of(neighbor))) { connectedNeighbors[targetIndex++] = neighbor; } } @@ -526,9 +544,9 @@ static Connection findConnection(BlockGetter level, BlockPos pos, BlockState sta /** 返回忽略玩家手动断开标记的原始几何连接。 */ @Nullable static Connection findGeometricConnection(BlockGetter level, BlockPos pos, BlockState state, int index) { - Direction attachment = state.getValue(ATTACHMENT); - Direction tangent = getLocalDirection(attachment, index); - BlockPos endpoint = endpoint(pos, attachment, tangent); + Direction attachment = state.getValue(RedstoneWireBlock.ATTACHMENT); + Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); + BlockPos endpoint = RedstoneWireBlock.endpoint(pos, attachment, tangent); BlockPos raisedEndpoint = endpoint.relative(attachment.getOpposite(), 2); BlockPos supportPos = pos.relative(attachment); long[] directNeighbors = new long[8]; @@ -541,20 +559,20 @@ static Connection findGeometricConnection(BlockGetter level, BlockPos pos, Block // 端点用二倍整数坐标表示,枚举 6 个附着面 x 4 个切向即可精确反解所有可能与其重合的导线。 for (Direction candidateAttachment : Direction.values()) { for (int candidateIndex = 0; candidateIndex < 4; candidateIndex++) { - Direction candidateTangent = getLocalDirection(candidateAttachment, candidateIndex); - BlockPos candidatePos = positionForEndpoint(endpoint, candidateAttachment, candidateTangent); + Direction candidateTangent = RedstoneWireBlock.getLocalDirection(candidateAttachment, candidateIndex); + BlockPos candidatePos = RedstoneWireBlock.positionForEndpoint(endpoint, candidateAttachment, candidateTangent); if (candidatePos == null || candidatePos.equals(pos)) { continue; } BlockState candidate = level.getBlockState(candidatePos); if (!(candidate.getBlock() instanceof RedstoneWireBlock) - || candidate.getValue(ATTACHMENT) != candidateAttachment - || !canConnectDirectly( + || candidate.getValue(RedstoneWireBlock.ATTACHMENT) != candidateAttachment + || !RedstoneWireBlock.canConnectDirectly( level, pos, attachment, tangent, supportPos, candidatePos, candidateAttachment )) { continue; } - directCount = addUnique(directNeighbors, directCount, candidatePos.asLong()); + directCount = RedstoneWireBlock.addUnique(directNeighbors, directCount, candidatePos.asLong()); boolean crossesSurface = candidateAttachment != attachment; if (attachment.getAxis().isHorizontal() && crossesSurface) { // 墙面导线绕支撑方块边缘转向时需要向负局部坐标延伸,用专门模型覆盖拐角。 @@ -564,47 +582,47 @@ static Connection findGeometricConnection(BlockGetter level, BlockPos pos, Block } if (directCount > 0) { // 共享同一物理端点的直接连接优先,避免同时把附近可爬升导线错误并入网络。 - return new Connection(copyOf(directNeighbors, directCount), directSide); + return new Connection(RedstoneWireBlock.copyOf(directNeighbors, directCount), directSide); } - boolean canClimbFromCurrent = canClimb(level, pos, attachment, tangent); + boolean canClimbFromCurrent = RedstoneWireBlock.canClimb(level, pos, attachment, tangent); // 没有直接连接时才检查隔着一格高度的上下坡关系,复现红石粉沿完整碰撞面爬升的行为。 for (Direction candidateAttachment : Direction.values()) { - if (!canShareClimbingEdge(attachment, candidateAttachment)) { + if (!RedstoneWireBlock.canShareClimbingEdge(attachment, candidateAttachment)) { continue; } for (int candidateIndex = 0; candidateIndex < 4; candidateIndex++) { - Direction candidateTangent = getLocalDirection(candidateAttachment, candidateIndex); - BlockPos candidatePos = positionForEndpoint( + Direction candidateTangent = RedstoneWireBlock.getLocalDirection(candidateAttachment, candidateIndex); + BlockPos candidatePos = RedstoneWireBlock.positionForEndpoint( raisedEndpoint, candidateAttachment, candidateTangent ); - if (isNearby(pos, candidatePos)) { + if (RedstoneWireBlock.isNearby(pos, candidatePos)) { BlockState candidate = level.getBlockState(candidatePos); if (candidate.getBlock() instanceof RedstoneWireBlock - && candidate.getValue(ATTACHMENT) == candidateAttachment + && candidate.getValue(RedstoneWireBlock.ATTACHMENT) == candidateAttachment && canClimbFromCurrent - && !hasDirectConnectionAtEndpoint(level, candidatePos, candidate, candidateIndex)) { - climbingCount = addUnique(climbingNeighbors, climbingCount, candidatePos.asLong()); + && !RedstoneWireBlock.hasDirectConnectionAtEndpoint(level, candidatePos, candidate, candidateIndex)) { + climbingCount = RedstoneWireBlock.addUnique(climbingNeighbors, climbingCount, candidatePos.asLong()); // 从当前导线向外爬升时,当前这一段需要额外绘制竖直模型。 climbingSide = ConnectionType.UP; } } BlockPos lowerEndpoint = endpoint.relative(candidateAttachment, 2); - candidatePos = positionForEndpoint(lowerEndpoint, candidateAttachment, candidateTangent); - if (isNearby(pos, candidatePos)) { + candidatePos = RedstoneWireBlock.positionForEndpoint(lowerEndpoint, candidateAttachment, candidateTangent); + if (RedstoneWireBlock.isNearby(pos, candidatePos)) { BlockState candidate = level.getBlockState(candidatePos); if (candidate.getBlock() instanceof RedstoneWireBlock - && candidate.getValue(ATTACHMENT) == candidateAttachment - && canClimb(level, candidatePos, candidateAttachment, candidateTangent) - && !hasDirectConnectionAtEndpoint(level, candidatePos, candidate, candidateIndex)) { - climbingCount = addUnique(climbingNeighbors, climbingCount, candidatePos.asLong()); + && candidate.getValue(RedstoneWireBlock.ATTACHMENT) == candidateAttachment + && RedstoneWireBlock.canClimb(level, candidatePos, candidateAttachment, candidateTangent) + && !RedstoneWireBlock.hasDirectConnectionAtEndpoint(level, candidatePos, candidate, candidateIndex)) { + climbingCount = RedstoneWireBlock.addUnique(climbingNeighbors, climbingCount, candidatePos.asLong()); } } } } if (climbingCount > 0) { - return new Connection(copyOf(climbingNeighbors, climbingCount), climbingSide); + return new Connection(RedstoneWireBlock.copyOf(climbingNeighbors, climbingCount), climbingSide); } return null; } @@ -615,7 +633,7 @@ static int findGeometricConnectionIndex( ) { long target = targetPos.asLong(); for (int index = 0; index < 4; index++) { - Connection connection = findGeometricConnection(level, pos, state, index); + Connection connection = RedstoneWireBlock.findGeometricConnection(level, pos, state, index); if (connection == null) { continue; } @@ -641,7 +659,7 @@ private static boolean isNeighborPortHidden(BlockGetter level, BlockPos pos, Blo if (!(neighborState.getBlock() instanceof RedstoneWireBlock)) { return false; } - int neighborIndex = findGeometricConnectionIndex(level, neighborPos, neighborState, pos); + int neighborIndex = RedstoneWireBlock.findGeometricConnectionIndex(level, neighborPos, neighborState, pos); return neighborIndex >= 0 && (hiddenMask & (1 << neighborIndex)) != 0; } @@ -649,15 +667,15 @@ private static boolean isNeighborPortHidden(BlockGetter level, BlockPos pos, Blo static boolean isManuallyHidden( BlockGetter level, BlockPos pos, BlockState state, int index ) { - if (isPortHidden(level, pos, index)) { + if (RedstoneWireBlock.isPortHidden(level, pos, index)) { return true; } - Connection geometric = findGeometricConnection(level, pos, state, index); + Connection geometric = RedstoneWireBlock.findGeometricConnection(level, pos, state, index); if (geometric == null) { return false; } for (long neighbor : geometric.positions()) { - if (isNeighborPortHidden(level, pos, BlockPos.of(neighbor))) { + if (RedstoneWireBlock.isNeighborPortHidden(level, pos, BlockPos.of(neighbor))) { return true; } } @@ -667,25 +685,25 @@ static boolean isManuallyHidden( private static boolean hasDirectConnectionAtEndpoint( BlockGetter level, BlockPos pos, BlockState state, int index ) { - Direction attachment = state.getValue(ATTACHMENT); - Direction tangent = getLocalDirection(attachment, index); - BlockPos endpoint = endpoint(pos, attachment, tangent); + Direction attachment = state.getValue(RedstoneWireBlock.ATTACHMENT); + Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); + BlockPos endpoint = RedstoneWireBlock.endpoint(pos, attachment, tangent); BlockPos supportPos = pos.relative(attachment); // 一个端点最多只有 24 种朝向表示(6 个附着面 x 4 个切向),枚举比维护额外空间索引更便宜。 for (Direction candidateAttachment : Direction.values()) { for (int candidateIndex = 0; candidateIndex < 4; candidateIndex++) { - Direction candidateTangent = getLocalDirection(candidateAttachment, candidateIndex); - BlockPos candidatePos = positionForEndpoint(endpoint, candidateAttachment, candidateTangent); + Direction candidateTangent = RedstoneWireBlock.getLocalDirection(candidateAttachment, candidateIndex); + BlockPos candidatePos = RedstoneWireBlock.positionForEndpoint(endpoint, candidateAttachment, candidateTangent); if (candidatePos == null || candidatePos.equals(pos)) { continue; } BlockState candidate = level.getBlockState(candidatePos); if (!(candidate.getBlock() instanceof RedstoneWireBlock) - || candidate.getValue(ATTACHMENT) != candidateAttachment) { + || candidate.getValue(RedstoneWireBlock.ATTACHMENT) != candidateAttachment) { continue; } - if (canConnectDirectly( + if (RedstoneWireBlock.canConnectDirectly( level, pos, attachment, tangent, supportPos, candidatePos, candidateAttachment )) { return true; @@ -755,7 +773,7 @@ private static boolean canConnectDirectly( } // 跨面连接必须共同依附于同一个支撑方块,且拐角空间不能被实体导体占据。 return candidatePos.relative(candidateAttachment).equals(supportPos) - && !isCornerBlocked(level, pos, tangent); + && !RedstoneWireBlock.isCornerBlocked(level, pos, tangent); } private static boolean isCornerBlocked(BlockGetter level, BlockPos pos, Direction tangent) { @@ -764,11 +782,11 @@ private static boolean isCornerBlocked(BlockGetter level, BlockPos pos, Directio } /** 按局部北、东、南、西顺序计算一根导线的全部内部连接。 */ - static Connection[] findConnections(BlockGetter level, BlockPos pos, BlockState state) { + static @Nullable Connection[] findConnections(BlockGetter level, BlockPos pos, BlockState state) { // 数组索引与 CONNECTION_PROPERTIES 共享同一局部方向约定,Manager 可以直接缓存并复用。 - Connection[] connections = new Connection[4]; + @Nullable Connection[] connections = new Connection[4]; for (int index = 0; index < connections.length; index++) { - connections[index] = findConnection(level, pos, state, index); + connections[index] = RedstoneWireBlock.findConnection(level, pos, state, index); } return connections; } @@ -779,7 +797,7 @@ private static boolean canClimb(BlockGetter level, BlockPos pos, Direction attac BlockPos bridgePos = pos.relative(tangent); BlockState bridge = level.getBlockState(bridgePos); return !level.getBlockState(pos.relative(outward)).isRedstoneConductor(level, pos.relative(outward)) - && hasFullCollisionFace(level, bridgePos, bridge, tangent.getOpposite()); + && RedstoneWireBlock.hasFullCollisionFace(level, bridgePos, bridge, tangent.getOpposite()); } /** 只有朝向导线的碰撞面完整时才允许爬升,与支撑方块的具体类型无关。 */ @@ -817,7 +835,7 @@ public boolean reattach(Level level, BlockPos pos, BlockState state) { public boolean editConnection( Level level, BlockPos pos, BlockState state, Vec3 hitLocation, boolean directHit ) { - ClickedPort clicked = getClickedPort(pos, state, hitLocation, directHit); + ClickedPort clicked = RedstoneWireBlock.getClickedPort(pos, state, hitLocation, directHit); return RedstoneWireNetworkManager.editConnection( level, pos, state, clicked.index(), clicked.onConnectionSegment(), clicked.turnIndex() ); @@ -830,13 +848,13 @@ private static ClickedPort getClickedPort( double dx = hitLocation.x - pos.getX() - 0.5; double dy = hitLocation.y - pos.getY() - 0.5; double dz = hitLocation.z - pos.getZ() - 0.5; - Direction attachment = state.getValue(ATTACHMENT); - int result = directHit ? getHitConnectionIndex(state, attachment, dx, dy, dz) : -1; + Direction attachment = state.getValue(RedstoneWireBlock.ATTACHMENT); + int result = directHit ? RedstoneWireBlock.getHitConnectionIndex(state, attachment, dx, dy, dz) : -1; boolean onConnectionSegment = result >= 0; if (result < 0) { - result = getClosestConnectionIndex(attachment, dx, dy, dz); + result = RedstoneWireBlock.getClosestConnectionIndex(attachment, dx, dy, dz); } - Direction perpendicular = getLocalDirection(attachment, (result + 1) % 4); + Direction perpendicular = RedstoneWireBlock.getLocalDirection(attachment, (result + 1) % 4); double transverse = dx * perpendicular.getStepX() + dy * perpendicular.getStepY() + dz * perpendicular.getStepZ(); @@ -851,12 +869,12 @@ private static int getHitConnectionIndex( int result = -1; double bestProjection = Double.NEGATIVE_INFINITY; for (int index = 0; index < 4; index++) { - if (!state.getValue(CONNECTION_PROPERTIES.get(index)).isConnected()) { + if (!state.getValue(RedstoneWireBlock.CONNECTION_PROPERTIES.get(index)).isConnected()) { continue; } - Direction tangent = getLocalDirection(attachment, index); + Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); double projection = dx * tangent.getStepX() + dy * tangent.getStepY() + dz * tangent.getStepZ(); - Direction perpendicular = getLocalDirection(attachment, (index + 1) % 4); + Direction perpendicular = RedstoneWireBlock.getLocalDirection(attachment, (index + 1) % 4); double transverse = dx * perpendicular.getStepX() + dy * perpendicular.getStepY() + dz * perpendicular.getStepZ(); @@ -875,7 +893,7 @@ private static int getClosestConnectionIndex(Direction attachment, double dx, do int result = 0; double bestProjection = Double.NEGATIVE_INFINITY; for (int index = 0; index < 4; index++) { - Direction tangent = getLocalDirection(attachment, index); + Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); double projection = dx * tangent.getStepX() + dy * tangent.getStepY() + dz * tangent.getStepZ(); if (projection > bestProjection) { bestProjection = projection; @@ -896,7 +914,7 @@ public static Direction getLocalDirection(Direction attachment, int index) { : attachment == Direction.UP ? Direction.SOUTH : Direction.UP; Direction outward = attachment.getOpposite(); // 叉积得到局部东向,保证四个方向在从导线外侧观察时始终保持一致的环绕顺序。 - Direction east = cross(north, outward); + Direction east = RedstoneWireBlock.cross(north, outward); return switch (index) { case 0 -> north; case 1 -> east; @@ -910,7 +928,7 @@ public static Direction getLocalDirection(Direction attachment, int index) { static int getLocalIndex(Direction attachment, Direction worldDirection) { // 方向只有四个,线性查找比维护 6x6 的静态映射更直观,且只发生在局部连接计算中。 for (int index = 0; index < 4; index++) { - if (getLocalDirection(attachment, index) == worldDirection) { + if (RedstoneWireBlock.getLocalDirection(attachment, index) == worldDirection) { return index; } } @@ -941,7 +959,7 @@ public static float[] transformBox( double maxZ ) { Direction outward = attachment.getOpposite(); - Direction right = cross(tangent, outward); + Direction right = RedstoneWireBlock.cross(tangent, outward); double[] bounds = {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}; // 变换后的轴可能交换或反向,因此遍历八个角点重新求 min/max,不能只转换两个对角点。 @@ -975,7 +993,7 @@ public static Direction transformDirection( Direction attachment, Direction tangent, Direction localDirection ) { Direction outward = attachment.getOpposite(); - Direction right = cross(tangent, outward); + Direction right = RedstoneWireBlock.cross(tangent, outward); // 与 transformBox 使用完全相同的局部基,确保模型面、剔除方向和碰撞盒不会互相错位。 int x = right.getStepX() * localDirection.getStepX() + outward.getStepX() * localDirection.getStepY() @@ -999,7 +1017,7 @@ private static VoxelShape transformedBox( double maxY, double maxZ ) { - float[] box = transformBox(attachment, tangent, minX, minY, minZ, maxX, maxY, maxZ); + float[] box = RedstoneWireBlock.transformBox(attachment, tangent, minX, minY, minZ, maxX, maxY, maxZ); return Block.box(box[0], box[1], box[2], box[3], box[4], box[5]); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireClientPowerCache.java b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireClientPowerCache.java index e08d3ff13a..a593d741fb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireClientPowerCache.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireClientPowerCache.java @@ -8,6 +8,7 @@ import net.minecraft.core.SectionPos; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; +import org.jspecify.annotations.Nullable; import java.util.concurrent.ConcurrentHashMap; @@ -20,54 +21,54 @@ public final class RedstoneWireClientPowerCache { private static final ConcurrentHashMap POWERS = new ConcurrentHashMap<>(); private static final Long2ObjectOpenHashMap POSITIONS_BY_CHUNK = new Long2ObjectOpenHashMap<>(); - private static volatile Level cachedLevel; + private static volatile @Nullable Level cachedLevel; private RedstoneWireClientPowerCache() { } /** 返回指定客户端世界中导线的显示功率;尚未同步时返回零。 */ - public static int get(Level level, BlockPos pos) { - if (level == null || cachedLevel != level) { + public static int get(@Nullable Level level, BlockPos pos) { + if (level == null || RedstoneWireClientPowerCache.cachedLevel != level) { return 0; } - Byte value = POWERS.get(pos.asLong()); + Byte value = RedstoneWireClientPowerCache.POWERS.get(pos.asLong()); return value == null ? 0 : Byte.toUnsignedInt(value); } /** 供区块渲染区域查询当前客户端世界的功率。 */ public static int getCurrent(BlockPos pos) { - return get(cachedLevel, pos); + return RedstoneWireClientPowerCache.get(RedstoneWireClientPowerCache.cachedLevel, pos); } /** 更新单个位置,返回其显示颜色是否发生变化。 */ public static boolean update(Level level, BlockPos pos, int power) { - ensureLevel(level); + RedstoneWireClientPowerCache.ensureLevel(level); LongOpenHashSet dirtySections = new LongOpenHashSet(); int clampedPower = Math.clamp(power, 0, 15); if (clampedPower == 0) { - remove(pos.asLong(), dirtySections); + RedstoneWireClientPowerCache.remove(pos.asLong(), dirtySections); } else { - put(pos, clampedPower, dirtySections); + RedstoneWireClientPowerCache.put(pos, clampedPower, dirtySections); } return !dirtySections.isEmpty(); } /** 应用一个区块的功率同步,并返回需要重建渲染的区段集合。 */ public static LongOpenHashSet apply(Level level, RedstoneWirePowerSyncPacket packet) { - ensureLevel(level); + RedstoneWireClientPowerCache.ensureLevel(level); long chunkPos = packet.chunkPos(); LongOpenHashSet dirtySections = new LongOpenHashSet(); if (packet.replace()) { - clearChunkInternal(chunkPos, dirtySections); + RedstoneWireClientPowerCache.clearChunkInternal(chunkPos, dirtySections); } for (RedstoneWirePowerSyncPacket.PowerGroup group : packet.groups()) { int power = group.power(); for (int packed : group.positions()) { BlockPos pos = RedstoneWirePowerSyncPacket.unpack(chunkPos, packed); if (power == 0) { - remove(pos.asLong(), dirtySections); + RedstoneWireClientPowerCache.remove(pos.asLong(), dirtySections); } else { - put(pos, power, dirtySections); + RedstoneWireClientPowerCache.put(pos, power, dirtySections); } } } @@ -75,84 +76,82 @@ public static LongOpenHashSet apply(Level level, RedstoneWirePowerSyncPacket pac } /** 清理客户端不再加载的区块,避免已移除导线的坐标长期留在缓存中。 */ - public static void clearChunk(Level level, ChunkPos chunkPos) { - if (level == null || cachedLevel != level) { + public static void clearChunk(@Nullable Level level, ChunkPos chunkPos) { + if (level == null || RedstoneWireClientPowerCache.cachedLevel != level) { return; } - clearChunkInternal(chunkPos.pack(), null); + RedstoneWireClientPowerCache.clearChunkInternal(chunkPos.pack(), null); } /** 清理客户端世界切换时的全部派生数据。 */ - public static void clear(Level level) { - if (level != null && cachedLevel != level) { + public static void clear(@Nullable Level level) { + if (level != null && RedstoneWireClientPowerCache.cachedLevel != level) { return; } - cachedLevel = null; - POWERS.clear(); - POSITIONS_BY_CHUNK.clear(); + RedstoneWireClientPowerCache.cachedLevel = null; + RedstoneWireClientPowerCache.POWERS.clear(); + RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.clear(); } private static void ensureLevel(Level level) { - if (cachedLevel == level) { + if (RedstoneWireClientPowerCache.cachedLevel == level) { return; } - cachedLevel = null; - POWERS.clear(); - POSITIONS_BY_CHUNK.clear(); - cachedLevel = level; + RedstoneWireClientPowerCache.cachedLevel = null; + RedstoneWireClientPowerCache.POWERS.clear(); + RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.clear(); + RedstoneWireClientPowerCache.cachedLevel = level; } private static void put(BlockPos pos, int power, LongOpenHashSet dirtySections) { long packedPos = pos.asLong(); byte value = (byte) power; - Byte old = POWERS.put(packedPos, value); + Byte old = RedstoneWireClientPowerCache.POWERS.put(packedPos, value); if (old == null) { - addIndex(pos); + RedstoneWireClientPowerCache.addIndex(pos); if (value != 0) { - markDirty(pos, dirtySections); + RedstoneWireClientPowerCache.markDirty(pos, dirtySections); } } else if (old.byteValue() != value) { - markDirty(pos, dirtySections); + RedstoneWireClientPowerCache.markDirty(pos, dirtySections); } } private static void remove(long packedPos, LongOpenHashSet dirtySections) { - Byte old = POWERS.remove(packedPos); + Byte old = RedstoneWireClientPowerCache.POWERS.remove(packedPos); if (old == null) { return; } BlockPos pos = BlockPos.of(packedPos); long chunkPos = ChunkPos.pack(pos.getX() >> 4, pos.getZ() >> 4); - LongOpenHashSet positions = POSITIONS_BY_CHUNK.get(chunkPos); - if (positions != null) { + if (RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.containsKey(chunkPos)) { + LongOpenHashSet positions = RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.get(chunkPos); positions.remove(packedPos); if (positions.isEmpty()) { - POSITIONS_BY_CHUNK.remove(chunkPos); + RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.remove(chunkPos); } } - markDirty(pos, dirtySections); + RedstoneWireClientPowerCache.markDirty(pos, dirtySections); } private static void addIndex(BlockPos pos) { long chunkPos = ChunkPos.pack(pos.getX() >> 4, pos.getZ() >> 4); - POSITIONS_BY_CHUNK.computeIfAbsent(chunkPos, ignored -> new LongOpenHashSet()).add(pos.asLong()); + RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.computeIfAbsent(chunkPos, ignored -> new LongOpenHashSet()).add(pos.asLong()); } - private static void clearChunkInternal(long chunkPos, LongOpenHashSet dirtySections) { - LongOpenHashSet positions = POSITIONS_BY_CHUNK.remove(chunkPos); - if (positions == null) { - return; - } + private static void clearChunkInternal(long chunkPos, @Nullable LongOpenHashSet dirtySections) { + if (!RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.containsKey(chunkPos)) return; + LongOpenHashSet positions = RedstoneWireClientPowerCache.POSITIONS_BY_CHUNK.remove(chunkPos); for (LongIterator iterator = positions.iterator(); iterator.hasNext();) { long packedPos = iterator.nextLong(); - POWERS.remove(packedPos); + RedstoneWireClientPowerCache.POWERS.remove(packedPos); if (dirtySections != null) { - markDirty(BlockPos.of(packedPos), dirtySections); + RedstoneWireClientPowerCache.markDirty(BlockPos.of(packedPos), dirtySections); } } } - private static void markDirty(BlockPos pos, LongOpenHashSet dirtySections) { + private static void markDirty(BlockPos pos, @Nullable LongOpenHashSet dirtySections) { if (dirtySections != null) { dirtySections.add(SectionPos.asLong(pos)); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireConnectionOverrides.java b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireConnectionOverrides.java index fdbe7d79bd..cb4326391c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireConnectionOverrides.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireConnectionOverrides.java @@ -35,8 +35,8 @@ final class RedstoneWireConnectionOverrides extends SavedData { private static final int HIDDEN_SHIFT = 4; private static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - Entry.CODEC.listOf().fieldOf(WIRES_KEY).forGetter(RedstoneWireConnectionOverrides::toEntries), - Codec.BOOL.optionalFieldOf(LEGACY_MIGRATION_KEY, false) + Entry.CODEC.listOf().fieldOf(RedstoneWireConnectionOverrides.WIRES_KEY).forGetter(RedstoneWireConnectionOverrides::toEntries), + Codec.BOOL.optionalFieldOf(RedstoneWireConnectionOverrides.LEGACY_MIGRATION_KEY, false) .forGetter(overrides -> overrides.legacyMigrationComplete) ).apply(instance, RedstoneWireConnectionOverrides::new)); @@ -68,7 +68,7 @@ static RedstoneWireConnectionOverrides get(ServerLevel level) { result = new RedstoneWireConnectionOverrides(); } if (!result.legacyMigrationComplete) { - RedstoneWireConnectionOverrides legacy = loadLegacy(level, storage); + RedstoneWireConnectionOverrides legacy = RedstoneWireConnectionOverrides.loadLegacy(level, storage); if (legacy != null) { result.mergeMissing(legacy); } @@ -85,17 +85,18 @@ static RedstoneWireConnectionOverrides get(ServerLevel level) { ServerLevel level, SavedDataStorage storage ) { - for (Path dataFile : legacyDataFiles(level)) { + for (Path dataFile : RedstoneWireConnectionOverrides.legacyDataFiles(level)) { if (!Files.isRegularFile(dataFile)) { continue; } try { CompoundTag root = storage.readTagFromDisk(dataFile, null, 0); CompoundTag data = root.getCompound("data").orElse(root); - if (!data.contains(WIRES_KEY) && !data.contains(LEGACY_WIRES_KEY)) { + if (!data.contains(RedstoneWireConnectionOverrides.WIRES_KEY) && !data.contains( + RedstoneWireConnectionOverrides.LEGACY_WIRES_KEY)) { continue; } - RedstoneWireConnectionOverrides result = loadEntries(data); + RedstoneWireConnectionOverrides result = RedstoneWireConnectionOverrides.loadEntries(data); AnvilCraft.LOGGER.info("Migrated redstone wire connection overrides from {}", dataFile); return result; } catch (Exception exception) { @@ -110,7 +111,7 @@ private static List legacyDataFiles(ServerLevel level) { Path currentDimensionFolder = DimensionType.getStorageFolder(level.dimension(), worldFolder); Path currentDataFolder = currentDimensionFolder.resolve("data"); List result = new ArrayList<>(); - Path currentLegacyFile = currentDataFolder.resolve(LEGACY_FILE_NAME); + Path currentLegacyFile = currentDataFolder.resolve(RedstoneWireConnectionOverrides.LEGACY_FILE_NAME); result.add(currentLegacyFile); Path legacyDimensionFolder; @@ -123,7 +124,7 @@ private static List legacyDataFiles(ServerLevel level) { } else { legacyDimensionFolder = currentDimensionFolder; } - Path legacyFile = legacyDimensionFolder.resolve("data").resolve(LEGACY_FILE_NAME); + Path legacyFile = legacyDimensionFolder.resolve("data").resolve(RedstoneWireConnectionOverrides.LEGACY_FILE_NAME); if (!legacyFile.equals(currentLegacyFile)) { result.add(legacyFile); } @@ -140,13 +141,15 @@ private void mergeMissing(RedstoneWireConnectionOverrides legacy) { private static RedstoneWireConnectionOverrides loadEntries(CompoundTag data) { RedstoneWireConnectionOverrides result = new RedstoneWireConnectionOverrides(); - ListTag wires = data.contains(WIRES_KEY) - ? data.getListOrEmpty(WIRES_KEY) - : data.getListOrEmpty(LEGACY_WIRES_KEY); + ListTag wires = data.contains(RedstoneWireConnectionOverrides.WIRES_KEY) + ? data.getListOrEmpty(RedstoneWireConnectionOverrides.WIRES_KEY) + : data.getListOrEmpty(RedstoneWireConnectionOverrides.LEGACY_WIRES_KEY); for (int index = 0; index < wires.size(); index++) { CompoundTag wire = wires.getCompoundOrEmpty(index); - String posKey = wire.contains(POS_KEY) ? POS_KEY : LEGACY_POS_KEY; - String flagsKey = wire.contains(FLAGS_KEY) ? FLAGS_KEY : LEGACY_FLAGS_KEY; + String posKey = wire.contains(RedstoneWireConnectionOverrides.POS_KEY) ? RedstoneWireConnectionOverrides.POS_KEY + : RedstoneWireConnectionOverrides.LEGACY_POS_KEY; + String flagsKey = wire.contains(RedstoneWireConnectionOverrides.FLAGS_KEY) ? RedstoneWireConnectionOverrides.FLAGS_KEY + : RedstoneWireConnectionOverrides.LEGACY_FLAGS_KEY; if (!wire.contains(posKey) || !wire.contains(flagsKey)) { continue; } @@ -167,21 +170,22 @@ private List toEntries() { } int forcedMask(long pos) { - return Byte.toUnsignedInt(this.entries.get(pos)) & DIRECTION_MASK; + return Byte.toUnsignedInt(this.entries.get(pos)) & RedstoneWireConnectionOverrides.DIRECTION_MASK; } int hiddenMask(long pos) { - return Byte.toUnsignedInt(this.entries.get(pos)) >>> HIDDEN_SHIFT; + return Byte.toUnsignedInt(this.entries.get(pos)) >>> RedstoneWireConnectionOverrides.HIDDEN_SHIFT; } boolean setForcedMask(long pos, int mask) { int flags = Byte.toUnsignedInt(this.entries.get(pos)); - return this.setFlags(pos, flags & ~DIRECTION_MASK | mask & DIRECTION_MASK); + return this.setFlags( + pos, flags & ~RedstoneWireConnectionOverrides.DIRECTION_MASK | mask & RedstoneWireConnectionOverrides.DIRECTION_MASK); } boolean setHidden(long pos, int index, boolean hidden) { int flags = Byte.toUnsignedInt(this.entries.get(pos)); - int bit = 1 << index + HIDDEN_SHIFT; + int bit = 1 << index + RedstoneWireConnectionOverrides.HIDDEN_SHIFT; return this.setFlags(pos, hidden ? flags | bit : flags & ~bit); } @@ -209,8 +213,8 @@ private boolean setFlags(long pos, int flags) { /// 单个导线位置的端口覆写记录 private record Entry(long pos, int flags) { private static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - Codec.LONG.fieldOf(POS_KEY).forGetter(Entry::pos), - Codec.INT.fieldOf(FLAGS_KEY).forGetter(Entry::flags) + Codec.LONG.fieldOf(RedstoneWireConnectionOverrides.POS_KEY).forGetter(Entry::pos), + Codec.INT.fieldOf(RedstoneWireConnectionOverrides.FLAGS_KEY).forGetter(Entry::flags) ).apply(instance, Entry::new)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireNetworkManager.java b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireNetworkManager.java index f4ddc14bde..d9c4c4a8af 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireNetworkManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/RedstoneWireNetworkManager.java @@ -16,6 +16,7 @@ import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.SectionPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.BlockGetter; @@ -62,7 +63,7 @@ private RedstoneWireNetworkManager() { public static void topologyChanged(Level level, BlockPos pos) { if (level instanceof ServerLevel serverLevel) { // 客户端只消费同步后的方块状态,拓扑的权威计算必须集中在服务端。 - state(serverLevel).requestTopologyUpdate(pos.asLong()); + RedstoneWireNetworkManager.state(serverLevel).requestTopologyUpdate(pos.asLong()); } } @@ -76,25 +77,26 @@ public static void neighborChanged( if (!(level instanceof ServerLevel serverLevel)) { return; } - LevelNetworks state = state(serverLevel); + LevelNetworks state = RedstoneWireNetworkManager.state(serverLevel); if (state.applyingTopology && neighborBlock instanceof RedstoneWireBlock) { // connectionState 写回外观会触发导线间邻居通知;此时拓扑已由当前重建过程掌握,继续响应会递归重建。 return; } long packedPos = pos.asLong(); - Network network = state.byWire.get(packedPos); + Network network = state.networkAt(packedPos); if (network == null || !network.valid) { // 新加载、刚放置或已经失效的位置没有可信缓存,只能从该点重新发现连通分量。 if (neighborPos == null) { state.rememberAdjacentObservers(pos); - } else if (level.hasChunkAt(neighborPos) && level.getBlockState(neighborPos).is(Blocks.OBSERVER)) { + } else if (RedstoneWireNetworkManager.hasChunk(serverLevel, neighborPos) + && level.getBlockState(neighborPos).is(Blocks.OBSERVER)) { // 先记录侦测器区块,确保本轮首次建网不会跳过其邻居扫描。 state.rememberObserver(neighborPos); } state.requestTopologyUpdate(packedPos); return; } - Node node = network.nodes.get(packedPos); + Node node = network.nodeAt(packedPos); BlockState blockState = level.getBlockState(pos); if (node == null || !(blockState.getBlock() instanceof RedstoneWireBlock block)) { state.requestTopologyUpdate(packedPos); @@ -119,15 +121,15 @@ public static void neighborChanged( return; } if (neighborPos == null) { - RedstoneWireBlock.Connection[] current = RedstoneWireBlock.findConnections(level, pos, blockState); - if (!connectionsEqual(node.connections, current)) { + var current = RedstoneWireBlock.findConnections(level, pos, blockState); + if (!RedstoneWireNetworkManager.connectionsEqual(node.connections, current)) { state.requestTopologyUpdate(packedPos); } else if (!network.overflow) { state.requestSignalUpdate(network); } return; } - if (!mayAffectWireTopology(pos, neighborPos, blockState, node.connections)) { + if (!RedstoneWireNetworkManager.mayAffectWireTopology(pos, neighborPos, blockState, node.connections)) { if (!network.overflow) { // 与任何内部连接无关的邻居只能改变端点输入,复用拓扑直接重算信号即可。 state.requestSignalUpdate(network); @@ -135,8 +137,8 @@ public static void neighborChanged( return; } - RedstoneWireBlock.Connection[] current = RedstoneWireBlock.findConnections(level, pos, blockState); - if (!connectionsEqual(node.connections, current)) { + var current = RedstoneWireBlock.findConnections(level, pos, blockState); + if (!RedstoneWireNetworkManager.connectionsEqual(node.connections, current)) { state.requestTopologyUpdate(packedPos); } else if (!network.overflow) { // 邻居位于潜在连接方向,但实际连接数组没有变化,最终仍只需刷新输入值。 @@ -146,19 +148,19 @@ public static void neighborChanged( /** 在服务端 tick 末尾继续处理上一轮因收敛上限而留下的更新。 */ public static void tick() { - for (LevelNetworks state : LEVELS.values()) { + for (LevelNetworks state : RedstoneWireNetworkManager.LEVELS.values()) { state.tick(); } } /** 世界卸载时释放该维度的全部派生缓存。 */ public static void clear(ServerLevel level) { - LEVELS.remove(level); + RedstoneWireNetworkManager.LEVELS.remove(level); } /** 将指定区块中当前已求值的导线功率发送给刚开始观察该区块的玩家。 */ public static void syncChunk(ServerPlayer player, ServerLevel level, ChunkAccess chunk) { - LevelNetworks state = state(level); + LevelNetworks state = RedstoneWireNetworkManager.state(level); state.runUpdates(); for (RedstoneWirePowerSyncPacket packet : state.createChunkSync(chunk.getPos())) { PacketDistributor.sendToPlayer(player, packet); @@ -168,7 +170,7 @@ public static void syncChunk(ServerPlayer player, ServerLevel level, ChunkAccess /** 清除已移除导线的持久化端口覆盖和客户端功率缓存。 */ public static void wireRemoved(Level level, BlockPos pos) { if (level instanceof ServerLevel serverLevel) { - state(serverLevel).connectionOverrides.clear(pos.asLong()); + RedstoneWireNetworkManager.state(serverLevel).connectionOverrides.clear(pos.asLong()); PacketDistributor.sendToPlayersTrackingChunk( serverLevel, ChunkPos.containing(pos), @@ -183,7 +185,7 @@ public static void wireRemoved(Level level, BlockPos pos) { /** 扫描新加载区块中的导线,并将它们作为待建网种子。 */ public static void chunkLoaded(ServerLevel level, ChunkAccess chunk) { - LevelNetworks state = state(level); + LevelNetworks state = RedstoneWireNetworkManager.state(level); // 只扫描区块自己的方块,避免加载事件为了找网络而同步加载相邻区块。 chunk.findBlocks( blockState -> blockState.getBlock() instanceof RedstoneWireBlock || blockState.is(Blocks.OBSERVER), @@ -200,7 +202,7 @@ public static void chunkLoaded(ServerLevel level, ChunkAccess chunk) { /** 区块卸载时移除其中节点,并重建仍处于加载状态的网络部分。 */ public static void chunkUnloaded(ServerLevel level, ChunkPos chunkPos) { - LevelNetworks state = LEVELS.get(level); + LevelNetworks state = RedstoneWireNetworkManager.LEVELS.get(level); if (state != null) { state.chunkUnloaded(chunkPos.pack()); } @@ -208,21 +210,21 @@ public static void chunkUnloaded(ServerLevel level, ChunkPos chunkPos) { /** 返回当前线程是否正在屏蔽自定义导线的信号输出。 */ public static boolean isSuppressingSignal() { - return SUPPRESS_SIGNAL.get(); + return RedstoneWireNetworkManager.SUPPRESS_SIGNAL.get(); } /** 获取已缓存的四向连接;客户端、溢出网络或尚未建网时返回 {@code null}。 */ - static RedstoneWireBlock.Connection @Nullable [] getConnections(BlockGetter level, BlockPos pos) { + static RedstoneWireBlock.@Nullable Connection @Nullable [] getConnections(BlockGetter level, BlockPos pos) { if (!(level instanceof ServerLevel serverLevel)) { return null; } - LevelNetworks state = LEVELS.get(serverLevel); + LevelNetworks state = RedstoneWireNetworkManager.LEVELS.get(serverLevel); if (state == null) { return null; } - Network network = state.byWire.get(pos.asLong()); + Network network = state.networkAt(pos.asLong()); // 溢出网络的节点集合不完整,使用其连接缓存会把截断边界误判为开放端点。 - Node node = network == null || !network.valid || network.overflow ? null : network.nodes.get(pos.asLong()); + Node node = network == null || !network.valid || network.overflow ? null : network.nodeAt(pos.asLong()); return node == null ? null : node.connections; } @@ -231,7 +233,7 @@ static int getForcedTerminalMask(BlockGetter level, BlockPos pos) { if (!(level instanceof ServerLevel serverLevel)) { return 0; } - return state(serverLevel).connectionOverrides.forcedMask(pos.asLong()); + return RedstoneWireNetworkManager.state(serverLevel).connectionOverrides.forcedMask(pos.asLong()); } /** 返回玩家为指定导线强制隐藏并断开的端口掩码。 */ @@ -239,7 +241,7 @@ static int getHiddenConnectionMask(BlockGetter level, BlockPos pos) { if (!(level instanceof ServerLevel serverLevel)) { return 0; } - return state(serverLevel).connectionOverrides.hiddenMask(pos.asLong()); + return RedstoneWireNetworkManager.state(serverLevel).connectionOverrides.hiddenMask(pos.asLong()); } /** 按点击方向切换开放端口或导线间连接;客户端只进行成功预测。 */ @@ -259,13 +261,13 @@ static boolean editConnection( if (!(level instanceof ServerLevel serverLevel)) { return false; } - return state(serverLevel).editConnection(pos, blockState, index, onConnectionSegment, turnIndex); + return RedstoneWireNetworkManager.state(serverLevel).editConnection(pos, blockState, index, onConnectionSegment, turnIndex); } /** 改挂面等操作会改变局部方向定义,因此必须清除旧端口覆盖。 */ static void clearConnectionOverrides(Level level, BlockPos pos) { if (level instanceof ServerLevel serverLevel) { - state(serverLevel).connectionOverrides.clear(pos.asLong()); + RedstoneWireNetworkManager.state(serverLevel).connectionOverrides.clear(pos.asLong()); } } @@ -278,13 +280,13 @@ static int getNonDustPower(BlockGetter level, BlockPos pos, int clientFallback) if (!(level instanceof ServerLevel serverLevel)) { return clientFallback; } - Network network = state(serverLevel).getOrBuildNetwork(pos.asLong()); + Network network = RedstoneWireNetworkManager.state(serverLevel).getOrBuildNetwork(pos.asLong()); return network == null || !network.valid || network.overflow ? 0 : network.nonDustPower; } /** 为服务端提示查询返回非红石粉输入强度,必要时同步建立当前位置的网络。 */ public static int getNonDustPower(ServerLevel level, BlockPos pos) { - LevelNetworks state = state(level); + LevelNetworks state = RedstoneWireNetworkManager.state(level); Network network = state.getOrBuildNetwork(pos.asLong()); return network == null || !network.valid || network.overflow ? 0 : network.nonDustPower; } @@ -297,7 +299,7 @@ public static int getNonDustPower(ServerLevel level, BlockPos pos) { */ public static int getPower(BlockGetter level, BlockPos pos) { if (level instanceof ServerLevel serverLevel) { - return getPower(serverLevel, pos); + return RedstoneWireNetworkManager.getPower(serverLevel, pos); } if (level instanceof Level clientLevel && clientLevel.isClientSide()) { return RedstoneWireClientPowerCache.get(clientLevel, pos); @@ -307,22 +309,30 @@ public static int getPower(BlockGetter level, BlockPos pos) { /** 为服务端红石查询返回总输入强度,必要时同步建立当前位置的网络。 */ public static int getPower(ServerLevel level, BlockPos pos) { - Network network = state(level).getOrBuildNetwork(pos.asLong()); + Network network = RedstoneWireNetworkManager.state(level).getOrBuildNetwork(pos.asLong()); return network == null || !network.valid ? 0 : network.totalPower; } private static LevelNetworks state(ServerLevel level) { // 网络缓存无需持久化;LevelNetworks 首次访问时同时惰性取得该维度的稀疏端口覆盖数据。 - return LEVELS.computeIfAbsent(level, LevelNetworks::new); + return RedstoneWireNetworkManager.LEVELS.computeIfAbsent(level, LevelNetworks::new); + } + + private static boolean hasChunk(ServerLevel level, BlockPos pos) { + return level.hasChunk( + SectionPos.blockToSectionCoord(pos.getX()), + SectionPos.blockToSectionCoord(pos.getZ()) + ); } /** 比较两组连接是否指向相同节点并采用相同显示形态。 */ private static boolean connectionsEqual( - RedstoneWireBlock.Connection[] first, RedstoneWireBlock.Connection[] second + RedstoneWireBlock.@Nullable Connection[] first, + RedstoneWireBlock.@Nullable Connection[] second ) { for (int index = 0; index < first.length; index++) { - RedstoneWireBlock.Connection a = first[index]; - RedstoneWireBlock.Connection b = second[index]; + var a = first[index]; + var b = second[index]; if (a == b) { continue; } @@ -339,7 +349,7 @@ private static boolean mayAffectWireTopology( BlockPos pos, BlockPos neighborPos, BlockState state, - RedstoneWireBlock.Connection[] connections + RedstoneWireBlock.@Nullable Connection[] connections ) { int dx = neighborPos.getX() - pos.getX(); int dy = neighborPos.getY() - pos.getY(); @@ -378,6 +388,7 @@ private static final class LevelNetworks { private final LongOpenHashSet observerChunks = new LongOpenHashSet(); /** 防止写回连接外观产生的导线邻居通知再次触发拓扑重建。 */ private boolean applyingTopology; + /** 防止邻居通知重入更新循环;重入请求只加入集合,由外层循环合并处理。 */ private boolean processingUpdates; private long lastOverflowWarning = Long.MIN_VALUE; @@ -387,6 +398,27 @@ private LevelNetworks(ServerLevel level) { this.connectionOverrides = RedstoneWireConnectionOverrides.get(level); } + private @Nullable Network networkAt(long packedPos) { + if (!this.byWire.containsKey(packedPos)) { + return null; + } + return this.byWire.get(packedPos); + } + + private @Nullable ObjectOpenHashSet networksInChunk(long chunkPos) { + if (!this.byChunk.containsKey(chunkPos)) { + return null; + } + return this.byChunk.get(chunkPos); + } + + private @Nullable ObjectOpenHashSet removeNetworksInChunk(long chunkPos) { + if (!this.byChunk.containsKey(chunkPos)) { + return null; + } + return this.byChunk.remove(chunkPos); + } + private void requestTopologyUpdate(long pos) { this.topologySeeds.add(pos); // 通常立即求值以保持红石同步语义;处理过程中产生的重复种子会由集合去重。 @@ -425,15 +457,15 @@ private boolean editConnection( boolean hasTarget = geometric != null || RedstoneWireBlock.hasConnectionTarget(this.level, pos, blockState, index); if ((forcedMask & bit) != 0 && !hasTarget) { - int visibleMask = connectionMask(blockState); + int visibleMask = LevelNetworks.connectionMask(blockState); int newForcedMask = forcedMask & ~bit; - if (isCorner(visibleMask)) { + if (LevelNetworks.isCorner(visibleMask)) { // 拐角上移除一侧时,把另一侧及其对向固定为完整直线,后续空侧点击才能继续累加分叉。 int remaining = visibleMask & ~bit; int remainingIndex = Integer.numberOfTrailingZeros(remaining); newForcedMask |= remaining | 1 << ((remainingIndex + 2) % 4); changed = this.connectionOverrides.setForcedMask(packedPos, newForcedMask); - } else if (isStraight(visibleMask)) { + } else if (LevelNetworks.isStraight(visibleMask)) { // 直线的人工端口不能只清除标记,否则自动回退会立刻把同一侧重新画出。 changed = this.connectionOverrides.setForcedMask(packedPos, newForcedMask); changed |= this.connectionOverrides.setHidden(packedPos, index, true); @@ -461,12 +493,12 @@ private boolean editConnection( targetMask |= 1 << direction; } } - int visibleMask = connectionMask(blockState); + int visibleMask = LevelNetworks.connectionMask(blockState); int newForcedMask; if (forcedMask == 0 && hiddenMask == 0 && Integer.bitCount(targetMask) <= 1 - && isStraight(visibleMask)) { + && LevelNetworks.isStraight(visibleMask)) { // 未编辑直线第一次点击侧面时形成拐角:优先保留真实接入端,否则保留靠近点击点的一端。 int anchor = targetMask == 0 ? turnIndex : Integer.numberOfTrailingZeros(targetMask); newForcedMask = bit | 1 << anchor; @@ -477,7 +509,7 @@ && isStraight(visibleMask)) { changed = this.connectionOverrides.setForcedMask(packedPos, newForcedMask); } } - RedstoneWireBlock.Connection[] connections = RedstoneWireBlock.findConnections( + var connections = RedstoneWireBlock.findConnections( this.level, pos, blockState ); changed |= this.ensureMinimumConnections(pos, blockState, connections, index, turnIndex); @@ -522,7 +554,7 @@ private boolean setNeighborPortsHidden( private boolean ensureMinimumConnections( BlockPos pos, BlockState blockState, - RedstoneWireBlock.Connection[] connections, + RedstoneWireBlock.@Nullable Connection[] connections, int disconnectedIndex, int turnIndex ) { @@ -531,7 +563,7 @@ private boolean ensureMinimumConnections( } RedstoneWireBlock block = (RedstoneWireBlock) blockState.getBlock(); BlockState connectedState = block.connectionState(this.level, pos, blockState, connections); - int visibleMask = connectionMask(connectedState); + int visibleMask = LevelNetworks.connectionMask(connectedState); int activeMask = visibleMask; for (int index = 0; index < 4; index++) { if (RedstoneWireBlock.isManuallyHidden(this.level, pos, connectedState, index)) { @@ -576,8 +608,10 @@ private boolean ensureMinimumConnections( } /** 求连接前修复旧覆盖数据,使迁移后的首轮建网也遵守最少两向约束。 */ - private RedstoneWireBlock.Connection[] findNormalizedConnections(BlockPos pos, BlockState blockState) { - RedstoneWireBlock.Connection[] connections = RedstoneWireBlock.findConnections( + private RedstoneWireBlock.@Nullable Connection[] findNormalizedConnections( + BlockPos pos, BlockState blockState + ) { + var connections = RedstoneWireBlock.findConnections( this.level, pos, blockState ); if (this.ensureMinimumConnections(pos, blockState, connections, -1, -1)) { @@ -617,7 +651,8 @@ private void rememberObserver(BlockPos observerPos) { private void rememberAdjacentObservers(BlockPos wirePos) { for (Direction direction : Direction.values()) { BlockPos observerPos = wirePos.relative(direction); - if (this.level.hasChunkAt(observerPos) && this.level.getBlockState(observerPos).is(Blocks.OBSERVER)) { + if (RedstoneWireNetworkManager.hasChunk(this.level, observerPos) + && this.level.getBlockState(observerPos).is(Blocks.OBSERVER)) { this.rememberObserver(observerPos); } } @@ -627,7 +662,7 @@ private void rememberAdjacentObservers(BlockPos wirePos) { private void refreshAdjacentObservers(Network network, BlockPos wirePos) { for (Direction direction : Direction.values()) { BlockPos observerPos = wirePos.relative(direction); - if (!this.level.hasChunkAt(observerPos)) { + if (!RedstoneWireNetworkManager.hasChunk(this.level, observerPos)) { continue; } this.refreshObserver(network, observerPos, this.level.getBlockState(observerPos)); @@ -645,7 +680,7 @@ private void refreshObserver(Network network, BlockPos observerPos, BlockState o private void indexObserver(BlockPos observerPos, BlockState observerState) { this.observerChunks.add(ChunkPos.pack(observerPos.getX() >> 4, observerPos.getZ() >> 4)); Direction facing = observerState.getValue(ObserverBlock.FACING); - Network network = this.byWire.get(observerPos.relative(facing).asLong()); + Network network = this.networkAt(observerPos.relative(facing).asLong()); if (network != null && network.valid && !network.overflow) { this.addObserver(network, observerPos.asLong()); } @@ -673,7 +708,8 @@ private void indexObservers(Network network) { for (Direction direction : Direction.values()) { BlockPos observerPos = wirePos.relative(direction); long observerChunk = ChunkPos.pack(observerPos.getX() >> 4, observerPos.getZ() >> 4); - if (!this.observerChunks.contains(observerChunk) || !this.level.hasChunkAt(observerPos)) { + if (!this.observerChunks.contains(observerChunk) + || !RedstoneWireNetworkManager.hasChunk(this.level, observerPos)) { continue; } BlockState observerState = this.level.getBlockState(observerPos); @@ -705,18 +741,18 @@ private void removeObserver(Network network, long observerPos) { /** 按需取得位置所属网络,供红石查询和客户端同步请求使用。 */ @Nullable private Network getOrBuildNetwork(long packedPos) { - Network network = this.byWire.get(packedPos); + Network network = this.networkAt(packedPos); if (network == null && this.level.getBlockState(BlockPos.of(packedPos)).getBlock() instanceof RedstoneWireBlock) { this.requestTopologyUpdate(packedPos); - network = this.byWire.get(packedPos); + network = this.networkAt(packedPos); } return network; } /** 生成一个区块的完整客户端功率快照;零功率位置无需写入分组。 */ private List createChunkSync(ChunkPos chunkPos) { - IntArrayList[] positionsByPower = new IntArrayList[16]; - ObjectOpenHashSet networks = this.byChunk.get(chunkPos.pack()); + var positionsByPower = new @Nullable IntArrayList[16]; + ObjectOpenHashSet networks = this.networksInChunk(chunkPos.pack()); if (networks != null) { for (Network network : networks) { if (!network.valid) { @@ -739,7 +775,7 @@ private List createChunkSync(ChunkPos chunkPos) { } } } - return chunkSyncPackets(chunkPos.pack(), positionsByPower); + return LevelNetworks.chunkSyncPackets(chunkPos.pack(), positionsByPower); } /** 将一张网络的新功率按区块批量发送给正在观察这些区块的玩家。 */ @@ -767,25 +803,25 @@ private void syncNetworkPower(Network network) { } private static List chunkSyncPackets( - long chunkPos, IntArrayList[] positionsByPower + long chunkPos, @Nullable IntArrayList[] positionsByPower ) { List packets = new ArrayList<>(); List groups = new ArrayList<>(); int packetPositions = 0; for (int power = 0; power < positionsByPower.length; power++) { - IntArrayList positions = positionsByPower[power]; + var positions = positionsByPower[power]; if (positions == null || positions.isEmpty()) { continue; } int[] values = positions.toIntArray(); for (int offset = 0; offset < values.length;) { - int count = Math.min(values.length - offset, MAX_NETWORK_SIZE - packetPositions); + int count = Math.min(values.length - offset, RedstoneWireNetworkManager.MAX_NETWORK_SIZE - packetPositions); groups.add(new RedstoneWirePowerSyncPacket.PowerGroup( power, Arrays.copyOfRange(values, offset, offset + count) )); offset += count; packetPositions += count; - if (packetPositions == MAX_NETWORK_SIZE) { + if (packetPositions == RedstoneWireNetworkManager.MAX_NETWORK_SIZE) { packets.add(new RedstoneWirePowerSyncPacket( chunkPos, packets.isEmpty(), List.copyOf(groups) )); @@ -810,7 +846,7 @@ private void runUpdates() { try { int pass = 0; while ((!this.topologySeeds.isEmpty() || !this.dirtySignals.isEmpty()) - && pass++ < MAX_SETTLING_PASSES) { + && pass++ < RedstoneWireNetworkManager.MAX_SETTLING_PASSES) { if (!this.topologySeeds.isEmpty()) { // 先快照再清空,使重建期间新增的种子自然进入下一轮,而不是干扰当前迭代器。 LongOpenHashSet seeds = new LongOpenHashSet(this.topologySeeds); @@ -841,7 +877,7 @@ private void rebuildFromSeeds(LongOpenHashSet changedPositions) { Long2ByteOpenHashMap inheritedPowers = new Long2ByteOpenHashMap(); for (LongIterator iterator = changedPositions.iterator(); iterator.hasNext();) { long packedPos = iterator.nextLong(); - Network oldNetwork = this.byWire.get(packedPos); + Network oldNetwork = this.networkAt(packedPos); if (oldNetwork != null) { affected.add(oldNetwork); } @@ -851,13 +887,13 @@ private void rebuildFromSeeds(LongOpenHashSet changedPositions) { continue; } // 新放置的导线可能把多个既有网络桥接起来,因此还要收集它当前连接到的所有邻居网络。 - RedstoneWireBlock.Connection[] connections = this.findNormalizedConnections(pos, state); - for (RedstoneWireBlock.Connection connection : connections) { + var connections = this.findNormalizedConnections(pos, state); + for (var connection : connections) { if (connection == null) { continue; } for (long neighbor : connection.positions()) { - Network neighborNetwork = this.byWire.get(neighbor); + Network neighborNetwork = this.networkAt(neighbor); if (neighborNetwork != null) { affected.add(neighborNetwork); } @@ -911,16 +947,16 @@ private void buildNetwork(long seed, Long2ByteOpenHashMap inheritedPowers) { if (inheritedPowers.containsKey(packedPos)) { inheritedPower = Math.max(inheritedPower, Byte.toUnsignedInt(inheritedPowers.get(packedPos))); } - RedstoneWireBlock.Connection[] connections = this.findNormalizedConnections(pos, state); + var connections = this.findNormalizedConnections(pos, state); nodes.put(packedPos, new Node(connections)); - if (nodes.size() >= MAX_NETWORK_SIZE) { + if (nodes.size() >= RedstoneWireNetworkManager.MAX_NETWORK_SIZE) { // 恰好等于上限且没有更多邻居仍是完整网络;只有真正被截断时才标记 overflow。 - overflow = !queue.isEmpty() || hasUnqueuedConnection(connections, queued); + overflow = !queue.isEmpty() || LevelNetworks.hasUnqueuedConnection(connections, queued); if (overflow) { break; } } - for (RedstoneWireBlock.Connection connection : connections) { + for (var connection : connections) { if (connection == null) { continue; } @@ -987,8 +1023,8 @@ private void recompute(Network network) { } int totalPower = 0; int nonDustPower = 0; - boolean wasSuppressingSignal = SUPPRESS_SIGNAL.get(); - SUPPRESS_SIGNAL.set(true); + boolean wasSuppressingSignal = RedstoneWireNetworkManager.SUPPRESS_SIGNAL.get(); + RedstoneWireNetworkManager.SUPPRESS_SIGNAL.set(true); try { // 只遍历预计算的端点,不扫描内部节点;长导线的信号采样成本由端子数而非总长度决定。 for (int index = 0; index < network.terminalWires.size(); index++) { @@ -1008,7 +1044,7 @@ private void recompute(Network network) { } } finally { // 恢复进入前的值,嵌套求值不能提前解除外层网络的防自激保护。 - SUPPRESS_SIGNAL.set(wasSuppressingSignal); + RedstoneWireNetworkManager.SUPPRESS_SIGNAL.set(wasSuppressingSignal); } boolean totalChanged = network.totalPower != totalPower; @@ -1047,7 +1083,7 @@ private void notifyObservers(Network network) { } for (LongIterator iterator = observers.iterator(); iterator.hasNext();) { BlockPos observerPos = BlockPos.of(iterator.nextLong()); - if (!this.level.hasChunkAt(observerPos)) { + if (!RedstoneWireNetworkManager.hasChunk(this.level, observerPos)) { iterator.remove(); continue; } @@ -1123,7 +1159,7 @@ private void notifyTopologyChanges(LongOpenHashSet changed) { private void warnOverflow(long seed) { long gameTime = this.level.getGameTime(); if (this.lastOverflowWarning != Long.MIN_VALUE - && gameTime - this.lastOverflowWarning < OVERFLOW_WARNING_INTERVAL) { + && gameTime - this.lastOverflowWarning < RedstoneWireNetworkManager.OVERFLOW_WARNING_INTERVAL) { // 同一维度的大型网络可能连续触发重建,限频可避免日志本身进一步放大性能问题。 return; } @@ -1131,16 +1167,16 @@ private void warnOverflow(long seed) { AnvilCraft.LOGGER.warn( "Redstone wire network at {} exceeds {} nodes; update was skipped to preserve its previous power", BlockPos.of(seed), - MAX_NETWORK_SIZE + RedstoneWireNetworkManager.MAX_NETWORK_SIZE ); } /** 从索引中移除卸载区块涉及的网络,并安排剩余已加载节点重建。 */ private void chunkUnloaded(long chunkPos) { // 卸载区块中的待处理位置已经不可访问,不能保留为下一 tick 的建网种子。 - removeChunkPositions(this.topologySeeds, chunkPos); + LevelNetworks.removeChunkPositions(this.topologySeeds, chunkPos); this.observerChunks.remove(chunkPos); - ObjectOpenHashSet affected = this.byChunk.remove(chunkPos); + ObjectOpenHashSet affected = this.removeNetworksInChunk(chunkPos); if (affected == null) { return; } @@ -1171,7 +1207,7 @@ private void invalidate(Network network, LongOpenHashSet rebuildSeeds, long excl // 先从区块反向索引移除,防止后续区块卸载再次处理同一个失效网络。 for (LongIterator iterator = network.chunks.iterator(); iterator.hasNext();) { long chunkPos = iterator.nextLong(); - ObjectOpenHashSet networks = this.byChunk.get(chunkPos); + ObjectOpenHashSet networks = this.networksInChunk(chunkPos); if (networks != null) { networks.remove(network); if (networks.isEmpty()) { @@ -1195,9 +1231,9 @@ private void invalidate(Network network, LongOpenHashSet rebuildSeeds, long excl /** 判断达到节点上限时是否仍存在尚未入队的连接,用于区分完整网络和截断网络。 */ private static boolean hasUnqueuedConnection( - RedstoneWireBlock.Connection[] connections, LongOpenHashSet queued + RedstoneWireBlock.@Nullable Connection[] connections, LongOpenHashSet queued ) { - for (RedstoneWireBlock.Connection connection : connections) { + for (var connection : connections) { if (connection == null) { continue; } @@ -1239,9 +1275,16 @@ private Network(Long2ObjectLinkedOpenHashMap nodes, boolean overflow, int this.overflow = overflow; this.totalPower = totalPower; } + + private @Nullable Node nodeAt(long packedPos) { + if (!this.nodes.containsKey(packedPos)) { + return null; + } + return this.nodes.get(packedPos); + } } /** 单根导线缓存的四向内部连接。 */ - private record Node(RedstoneWireBlock.Connection[] connections) { + private record Node(RedstoneWireBlock.@Nullable Connection[] connections) { } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/TradingStationBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/TradingStationBlock.java index 83bef58859..918d4d57f3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/TradingStationBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/TradingStationBlock.java @@ -50,8 +50,8 @@ public TradingStationBlock(Properties properties) { super(properties); this.registerDefaultState( this.defaultBlockState() - .setValue(HALF, DirectionVertical2PartHalf.BOTTOM) - .setValue(FACING, Direction.NORTH) + .setValue(TradingStationBlock.HALF, DirectionVertical2PartHalf.BOTTOM) + .setValue(TradingStationBlock.FACING, Direction.NORTH) ); } @@ -59,7 +59,7 @@ public TradingStationBlock(Properties properties) { public BlockState getStateForPlacement(BlockPlaceContext context) { Direction dir = context.getHorizontalDirection().getOpposite(); if (dir.getAxis().isVertical()) dir = Direction.NORTH; - return this.waterloggedStateForPlacement(context, this.defaultBlockState().setValue(FACING, dir)); + return this.waterloggedStateForPlacement(context, this.defaultBlockState().setValue(TradingStationBlock.FACING, dir)); } @Override @@ -89,7 +89,7 @@ public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { @Override protected boolean propagatesSkylightDown(BlockState state) { - return state.getValue(HALF) == DirectionVertical2PartHalf.TOP; + return state.getValue(TradingStationBlock.HALF) == DirectionVertical2PartHalf.TOP; } @Override @@ -99,23 +99,23 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return TradingStationBlock.FACING; } @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { - this.change(blockPos, level, (state) -> state.cycle(FACING)); + this.change(blockPos, level, (state) -> state.cycle(TradingStationBlock.FACING)); return true; } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(TradingStationBlock.FACING, rotation.rotate(state.getValue(TradingStationBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(TradingStationBlock.FACING, mirror.mirror(state.getValue(TradingStationBlock.FACING))); } @Override @@ -164,17 +164,17 @@ public boolean onDestroyedByPlayer( public Collection getBottomStates() { return Set.of( this.defaultBlockState() - .setValue(HALF, DirectionVertical2PartHalf.BOTTOM) - .setValue(FACING, Direction.NORTH), + .setValue(TradingStationBlock.HALF, DirectionVertical2PartHalf.BOTTOM) + .setValue(TradingStationBlock.FACING, Direction.NORTH), this.defaultBlockState() - .setValue(HALF, DirectionVertical2PartHalf.BOTTOM) - .setValue(FACING, Direction.SOUTH), + .setValue(TradingStationBlock.HALF, DirectionVertical2PartHalf.BOTTOM) + .setValue(TradingStationBlock.FACING, Direction.SOUTH), this.defaultBlockState() - .setValue(HALF, DirectionVertical2PartHalf.BOTTOM) - .setValue(FACING, Direction.EAST), + .setValue(TradingStationBlock.HALF, DirectionVertical2PartHalf.BOTTOM) + .setValue(TradingStationBlock.FACING, Direction.EAST), this.defaultBlockState() - .setValue(HALF, DirectionVertical2PartHalf.BOTTOM) - .setValue(FACING, Direction.WEST) + .setValue(TradingStationBlock.HALF, DirectionVertical2PartHalf.BOTTOM) + .setValue(TradingStationBlock.FACING, Direction.WEST) ); } @@ -182,12 +182,12 @@ public Collection getBottomStates() { @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - if (state.getValue(HALF) == DirectionVertical2PartHalf.TOP) return Shapes.empty(); - return switch (state.getValue(FACING)) { - case NORTH -> NORTH; - case WEST -> WEST; - case SOUTH -> SOUTH; - case EAST -> EAST; + if (state.getValue(TradingStationBlock.HALF) == DirectionVertical2PartHalf.TOP) return Shapes.empty(); + return switch (state.getValue(TradingStationBlock.FACING)) { + case NORTH -> TradingStationBlock.NORTH; + case WEST -> TradingStationBlock.WEST; + case SOUTH -> TradingStationBlock.SOUTH; + case EAST -> TradingStationBlock.EAST; case UP, DOWN -> Shapes.empty(); }; } @@ -198,7 +198,7 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, new AABB(0, 16, 11, 2, 30, 14), new AABB(14, 16, 11, 16, 30, 14) ); - private static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, NORTH); - private static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, NORTH); - private static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, NORTH); + private static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, TradingStationBlock.NORTH); + private static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, TradingStationBlock.NORTH); + private static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, TradingStationBlock.NORTH); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceGrindstoneBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceGrindstoneBlock.java index 1b0f091d8e..6d5aed5f53 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceGrindstoneBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceGrindstoneBlock.java @@ -50,7 +50,7 @@ public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) inventory, ContainerLevelAccess.create(level, pos) ), - CONTAINER_TITLE + TranscendenceGrindstoneBlock.CONTAINER_TITLE ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceSmithingTableBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceSmithingTableBlock.java index f509dcd5f2..ae6e27437b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceSmithingTableBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/TranscendenceSmithingTableBlock.java @@ -30,7 +30,7 @@ public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) inventory, ContainerLevelAccess.create(level, pos) ), - CONTAINER_TITLE + TranscendenceSmithingTableBlock.CONTAINER_TITLE ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/WipBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/WipBlock.java index b0482e3b3b..602bc9095b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/WipBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/WipBlock.java @@ -9,8 +9,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; -import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; 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; @@ -26,7 +26,7 @@ public WipBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(WipBlock::new); + return BlockBehaviour.simpleCodec(WipBlock::new); } @Nullable @@ -42,17 +42,12 @@ public List getDrops(BlockState state, LootParams.Builder params) { return super.getDrops(state, params); } BlockState initialBlockState = wipBe.getInitialBlock(); - if (initialBlockState == null || initialBlockState.isAir()) { + if (initialBlockState.isAir()) { return super.getDrops(state, params); } return initialBlockState.getDrops(params); } - @Override - protected RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } - @Override protected boolean hasAnalogOutputSignal(BlockState state) { return true; @@ -63,8 +58,7 @@ protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, BlockEntity e = level.getBlockEntity(pos); if (e instanceof WipBlockEntity wipBlockEntity) { if (wipBlockEntity.getStepCount() >= 15) return 15; - if (wipBlockEntity.getStepCount() <= 0) return 0; - return wipBlockEntity.getStepCount(); + return Math.max(wipBlockEntity.getStepCount(), 0); } return 0; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cake/LargeCakeBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cake/LargeCakeBlock.java index f5fdb14baa..a9dc7fe660 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cake/LargeCakeBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cake/LargeCakeBlock.java @@ -138,7 +138,7 @@ public class LargeCakeBlock extends SimpleMultiPartBlock { public LargeCakeBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(HALF, Cube3x3PartHalf.BOTTOM_CENTER)); + this.registerDefaultState(this.stateDefinition.any().setValue(LargeCakeBlock.HALF, Cube3x3PartHalf.BOTTOM_CENTER)); } @Override @@ -147,33 +147,33 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(HALF)) { - case TOP_CENTER -> TOP_CENTER; - case TOP_E -> TOP_E; - case TOP_W -> TOP_W; - case TOP_N -> TOP_N; - case TOP_S -> TOP_S; - case TOP_EN -> TOP_ANGLE_NE; - case TOP_ES -> TOP_ANGLE_SE; - case TOP_WN -> TOP_ANGLE_NW; - case TOP_WS -> TOP_ANGLE_SW; - case MID_CENTER -> MID_CENTER; - case MID_E -> MID_E; - case MID_W -> MID_W; - case MID_N -> MID_N; - case MID_S -> MID_S; - case MID_EN -> MID_ANGLE_NE; - case MID_ES -> MID_ANGLE_SE; - case MID_WN -> MID_ANGLE_NW; - case MID_WS -> MID_ANGLE_SW; - case BOTTOM_E -> BASE_E; - case BOTTOM_W -> BASE_W; - case BOTTOM_N -> BASE_N; - case BOTTOM_S -> BASE_S; - case BOTTOM_EN -> BASE_ANGLE_NE; - case BOTTOM_ES -> BASE_ANGLE_SE; - case BOTTOM_WN -> BASE_ANGLE_NW; - case BOTTOM_WS -> BASE_ANGLE_SW; + return switch (state.getValue(LargeCakeBlock.HALF)) { + case TOP_CENTER -> LargeCakeBlock.TOP_CENTER; + case TOP_E -> LargeCakeBlock.TOP_E; + case TOP_W -> LargeCakeBlock.TOP_W; + case TOP_N -> LargeCakeBlock.TOP_N; + case TOP_S -> LargeCakeBlock.TOP_S; + case TOP_EN -> LargeCakeBlock.TOP_ANGLE_NE; + case TOP_ES -> LargeCakeBlock.TOP_ANGLE_SE; + case TOP_WN -> LargeCakeBlock.TOP_ANGLE_NW; + case TOP_WS -> LargeCakeBlock.TOP_ANGLE_SW; + case MID_CENTER -> LargeCakeBlock.MID_CENTER; + case MID_E -> LargeCakeBlock.MID_E; + case MID_W -> LargeCakeBlock.MID_W; + case MID_N -> LargeCakeBlock.MID_N; + case MID_S -> LargeCakeBlock.MID_S; + case MID_EN -> LargeCakeBlock.MID_ANGLE_NE; + case MID_ES -> LargeCakeBlock.MID_ANGLE_SE; + case MID_WN -> LargeCakeBlock.MID_ANGLE_NW; + case MID_WS -> LargeCakeBlock.MID_ANGLE_SW; + case BOTTOM_E -> LargeCakeBlock.BASE_E; + case BOTTOM_W -> LargeCakeBlock.BASE_W; + case BOTTOM_N -> LargeCakeBlock.BASE_N; + case BOTTOM_S -> LargeCakeBlock.BASE_S; + case BOTTOM_EN -> LargeCakeBlock.BASE_ANGLE_NE; + case BOTTOM_ES -> LargeCakeBlock.BASE_ANGLE_SE; + case BOTTOM_WN -> LargeCakeBlock.BASE_ANGLE_NW; + case BOTTOM_WS -> LargeCakeBlock.BASE_ANGLE_SW; default -> Block.box(0, 1, 0, 16, 16, 16); }; } @@ -185,7 +185,7 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF); + builder.add(LargeCakeBlock.HALF); } @Override @@ -216,10 +216,10 @@ public void onPlace( BlockState oldState, boolean movedByPiston ) { - if (state.getValue(HALF) != Cube3x3PartHalf.BOTTOM_CENTER) return; + if (state.getValue(LargeCakeBlock.HALF) != Cube3x3PartHalf.BOTTOM_CENTER) return; for (Cube3x3PartHalf part : this.getParts()) { if (part == Cube3x3PartHalf.BOTTOM_CENTER) continue; - BlockState newState = state.setValue(HALF, part); + BlockState newState = state.setValue(LargeCakeBlock.HALF, part); level.setBlockAndUpdate(pos.offset(part.getOffset()), newState); } } @@ -271,7 +271,7 @@ public InteractionResult use( ) { ItemStack itemStack = player.getItemInHand(hand); if (level.isClientSide()) { - if (eat(level, pos, player).consumesAction()) { + if (LargeCakeBlock.eat(level, pos, player).consumesAction()) { return InteractionResult.SUCCESS; } @@ -280,7 +280,7 @@ public InteractionResult use( } } - return eat(level, pos, player); + return LargeCakeBlock.eat(level, pos, player); } private static InteractionResult eat(Level level, BlockPos pos, Player player) { @@ -288,7 +288,7 @@ private static InteractionResult eat(Level level, BlockPos pos, Player player) { return InteractionResult.PASS; } else { player.getFoodData().eat(15, 0.8F); - removeFromTop(level, pos, player); + LargeCakeBlock.removeFromTop(level, pos, player); return InteractionResult.SUCCESS; } } @@ -296,8 +296,8 @@ private static InteractionResult eat(Level level, BlockPos pos, Player player) { private static void removeFromTop(Level level, BlockPos pos, Player player) { BlockState aboveState = level.getBlockState(pos.above()); if (aboveState.getBlock() instanceof LargeCakeBlock - && aboveState.getValue(HALF).getOffsetY() != 0) { - removeFromTop(level, pos.above(), player); + && aboveState.getValue(LargeCakeBlock.HALF).getOffsetY() != 0) { + LargeCakeBlock.removeFromTop(level, pos.above(), player); return; } level.removeBlock(pos, false); @@ -306,11 +306,11 @@ private static void removeFromTop(Level level, BlockPos pos, Player player) { @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)); + return state.setValue(LargeCakeBlock.HALF, state.getValue(LargeCakeBlock.HALF).rotate(rotation)); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)); + return state.setValue(LargeCakeBlock.HALF, state.getValue(LargeCakeBlock.HALF).mirror(mirror)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cake/ShovelEatableCakeBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cake/ShovelEatableCakeBlock.java index 45a3b1ea7f..a5db6cd3c1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cake/ShovelEatableCakeBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cake/ShovelEatableCakeBlock.java @@ -46,7 +46,7 @@ protected InteractionResult useItemOn( return InteractionResult.PASS; } if (level.isClientSide()) { - if (eat(level, pos, player, this.getFoodLevel(), this.getSaturationLevel()).consumesAction()) { + if (ShovelEatableCakeBlock.eat(level, pos, player, this.getFoodLevel(), this.getSaturationLevel()).consumesAction()) { return InteractionResult.SUCCESS; } @@ -54,7 +54,7 @@ protected InteractionResult useItemOn( return InteractionResult.CONSUME; } } else { - InteractionResult result = eat(level, pos, player, this.getFoodLevel(), this.getSaturationLevel()); + InteractionResult result = ShovelEatableCakeBlock.eat(level, pos, player, this.getFoodLevel(), this.getSaturationLevel()); if (result == InteractionResult.SUCCESS) itemStack.hurtAndBreak(1, player, hand.asEquipmentSlot()); return result; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cake/StepEffectBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cake/StepEffectBlock.java index 5d73875cc2..5476d41f3d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cake/StepEffectBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cake/StepEffectBlock.java @@ -28,21 +28,21 @@ public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { public static void stepOnChocolateBlock(Entity entity) { if (!(entity instanceof Player player)) return; - if (entity.level().getGameTime() % EFFECT_PERIOD != 0) return; - player.addEffect(new MobEffectInstance(MobEffects.SPEED, EFFECT_DURATION, 9, true, true)); + if (entity.level().getGameTime() % StepEffectBlock.EFFECT_PERIOD != 0) return; + player.addEffect(new MobEffectInstance(MobEffects.SPEED, StepEffectBlock.EFFECT_DURATION, 9, true, true)); } public static void stepOnBlackChocolateBlock(Entity entity) { if (!(entity instanceof Player player)) return; - if (entity.level().getGameTime() % EFFECT_PERIOD != 0) return; - player.addEffect(new MobEffectInstance(MobEffects.SPEED, EFFECT_DURATION, 4, true, true)); - player.addEffect(new MobEffectInstance(MobEffects.HASTE, EFFECT_DURATION, 3, true, true)); + if (entity.level().getGameTime() % StepEffectBlock.EFFECT_PERIOD != 0) return; + player.addEffect(new MobEffectInstance(MobEffects.SPEED, StepEffectBlock.EFFECT_DURATION, 4, true, true)); + player.addEffect(new MobEffectInstance(MobEffects.HASTE, StepEffectBlock.EFFECT_DURATION, 3, true, true)); } public static void stepOnWhiteChocolateBlock(Entity entity) { if (!(entity instanceof Player player)) return; - if (entity.level().getGameTime() % EFFECT_PERIOD != 0) return; - player.addEffect(new MobEffectInstance(MobEffects.SPEED, EFFECT_DURATION, 4, true, true)); - player.addEffect(new MobEffectInstance(MobEffects.JUMP_BOOST, EFFECT_DURATION, 5, true, true)); + if (entity.level().getGameTime() % StepEffectBlock.EFFECT_PERIOD != 0) return; + player.addEffect(new MobEffectInstance(MobEffects.SPEED, StepEffectBlock.EFFECT_DURATION, 4, true, true)); + player.addEffect(new MobEffectInstance(MobEffects.JUMP_BOOST, StepEffectBlock.EFFECT_DURATION, 5, true, true)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/CementCauldronBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/CementCauldronBlock.java index 6f9ebd0ea8..7e6abe9b2b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/CementCauldronBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/CementCauldronBlock.java @@ -10,12 +10,13 @@ import net.minecraft.core.Direction; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.AbstractCauldronBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; @Getter public class CementCauldronBlock extends BaseCauldronBlock implements IHammerRemovable { public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(ins -> ins.group( - propertiesCodec(), Color.CODEC.fieldOf("color").forGetter(CementCauldronBlock::getColor) + BlockBehaviour.propertiesCodec(), Color.CODEC.fieldOf("color").forGetter(CementCauldronBlock::getColor) ).apply(ins, CementCauldronBlock::new)); private final Color color; @@ -27,7 +28,7 @@ public CementCauldronBlock(Properties properties, Color color) { @Override protected MapCodec codec() { - return CODEC; + return CementCauldronBlock.CODEC; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/LavaCauldronBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/LavaCauldronBlock.java index 11a3b6099d..3d6bf3f2de 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/LavaCauldronBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/LavaCauldronBlock.java @@ -45,7 +45,7 @@ protected void neighborChanged( @Override protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, Direction direction) { - int layer = state.getValue(LEVEL); + int layer = state.getValue(Layered4LevelCauldronBlock.LEVEL); return layer <= 2 ? layer : layer - 1; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/Layered4LevelCauldronBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/Layered4LevelCauldronBlock.java index f85e48cd55..33f4399af3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/Layered4LevelCauldronBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/Layered4LevelCauldronBlock.java @@ -12,6 +12,7 @@ import net.minecraft.world.level.block.AbstractCauldronBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; @@ -22,78 +23,83 @@ public class Layered4LevelCauldronBlock extends BaseCauldronBlock { public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(ins -> ins.group( - propertiesCodec(), + BlockBehaviour.propertiesCodec(), CauldronInteractions.CODEC .fieldOf("interactions") .forGetter(block -> block.interactions) ).apply(ins, Layered4LevelCauldronBlock::new)); public static final int MAX_LEVEL = 4; - public static final IntegerProperty LEVEL = IntegerProperty.create("level", 1, MAX_LEVEL); + public static final IntegerProperty LEVEL = IntegerProperty.create("level", 1, Layered4LevelCauldronBlock.MAX_LEVEL); public Layered4LevelCauldronBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, 1)); + this.registerDefaultState(this.stateDefinition.any().setValue(Layered4LevelCauldronBlock.LEVEL, 1)); } public Layered4LevelCauldronBlock(Properties properties, CauldronInteraction.Dispatcher interactions) { super(properties, interactions); - this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, 1)); + this.registerDefaultState(this.stateDefinition.any().setValue(Layered4LevelCauldronBlock.LEVEL, 1)); } public static void lowerFillLevel(BlockState state, Level level, BlockPos pos) { - int i = state.getValue(LEVEL) - 1; - BlockState blockstate = i == 0 ? Blocks.CAULDRON.defaultBlockState() : state.setValue(LEVEL, i); + int i = state.getValue(Layered4LevelCauldronBlock.LEVEL) - 1; + BlockState blockstate = i == 0 ? Blocks.CAULDRON.defaultBlockState() : state.setValue(Layered4LevelCauldronBlock.LEVEL, i); level.setBlockAndUpdate(pos, blockstate); level.gameEvent(GameEvent.BLOCK_CHANGE, pos, GameEvent.Context.of(blockstate)); } @Override protected MapCodec codec() { - return CODEC; + return Layered4LevelCauldronBlock.CODEC; } @Override public boolean isFull(BlockState state) { - return state.getValue(LEVEL) == MAX_LEVEL; + return state.getValue(Layered4LevelCauldronBlock.LEVEL) == Layered4LevelCauldronBlock.MAX_LEVEL; } @Override protected double getContentHeight(BlockState state) { - return (6.0 + state.getValue(LEVEL) * 2.0) / 16.0; + return (6.0 + state.getValue(Layered4LevelCauldronBlock.LEVEL) * 2.0) / 16.0; } @Override protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, Direction direction) { - return state.getValue(LEVEL); + return state.getValue(Layered4LevelCauldronBlock.LEVEL); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(LEVEL); + builder.add(Layered4LevelCauldronBlock.LEVEL); } public BlockState copyLevelFrom(BlockState otherCauldron) { - return this.defaultBlockState().setValue(LEVEL, Optional.of(otherCauldron) + return this.defaultBlockState().setValue( + Layered4LevelCauldronBlock.LEVEL, Optional.of(otherCauldron) .filter(state -> state.getBlock() instanceof Layered4LevelCauldronBlock) - .map(state -> state.getValue(LEVEL)) + .map(state -> state.getValue(Layered4LevelCauldronBlock.LEVEL)) .orElse(1)); } public BlockState fullFilled() { - return this.defaultBlockState().setValue(LEVEL, MAX_LEVEL); + return this.defaultBlockState().setValue(Layered4LevelCauldronBlock.LEVEL, Layered4LevelCauldronBlock.MAX_LEVEL); } // Shapes @Override protected VoxelShape getEntityInsideCollisionShape(BlockState state, BlockGetter level, BlockPos pos, Entity entity) { - return switch (state.getValue(LEVEL)) { - case 1 -> LEVEL1; - case 2 -> LEVEL2; - case 3 -> LEVEL3; - case 4 -> LEVEL4; - case null, default -> throw new IllegalStateException("Unexpected value " + state.getValue(LEVEL) + ". How did you get here?"); + return switch (state.getValue(Layered4LevelCauldronBlock.LEVEL)) { + case 1 -> Layered4LevelCauldronBlock.LEVEL1; + case 2 -> Layered4LevelCauldronBlock.LEVEL2; + case 3 -> Layered4LevelCauldronBlock.LEVEL3; + case 4 -> Layered4LevelCauldronBlock.LEVEL4; + case null, default -> throw new IllegalStateException( + "Unexpected value " + + state.getValue(Layered4LevelCauldronBlock.LEVEL) + + ". How did you get here?" + ); }; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/MeltGemCauldronBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/MeltGemCauldronBlock.java index b06f34be78..76723b2c5e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/MeltGemCauldronBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/MeltGemCauldronBlock.java @@ -7,6 +7,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.AbstractCauldronBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; public class MeltGemCauldronBlock extends BaseCauldronBlock implements IHammerRemovable { @@ -16,7 +17,7 @@ public MeltGemCauldronBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(MeltGemCauldronBlock::new); + return BlockBehaviour.simpleCodec(MeltGemCauldronBlock::new); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/ObsidianCauldronBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/ObsidianCauldronBlock.java index 7843d23f5d..f219ec219e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/ObsidianCauldronBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/ObsidianCauldronBlock.java @@ -7,6 +7,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.AbstractCauldronBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; public class ObsidianCauldronBlock extends BaseCauldronBlock implements IHammerRemovable { @@ -16,7 +17,7 @@ public ObsidianCauldronBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(ObsidianCauldronBlock::new); + return BlockBehaviour.simpleCodec(ObsidianCauldronBlock::new); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/OilCauldronBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/OilCauldronBlock.java index 94d4e0a5f7..e637d95fc7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cauldron/OilCauldronBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cauldron/OilCauldronBlock.java @@ -32,7 +32,11 @@ public class OilCauldronBlock extends Layered4LevelCauldronBlock implements IHam public OilCauldronBlock(Properties properties) { super(properties, ModInteractionMap.OIL); - this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, 1).setValue(OilCauldronBlock.IGNITED, false)); + this.registerDefaultState( + this.stateDefinition.any() + .setValue(Layered4LevelCauldronBlock.LEVEL, 1) + .setValue(OilCauldronBlock.IGNITED, false) + ); } public static void ignite(LevelAccessor level, BlockPos pos) { @@ -50,17 +54,17 @@ protected void entityInside( ) { if (level.isClientSide()) return; if (entity.getType().equals(EntityType.ARROW) && entity.isOnFire()) { - ignite(level, pos); + OilCauldronBlock.ignite(level, pos); return; } if (!(entity instanceof ItemEntity itemEntity)) return; if (itemEntity.getItem().is(ModItemTags.FIRE_STARTER)) { - ignite(level, pos); + OilCauldronBlock.ignite(level, pos); itemEntity.getItem().setCount(itemEntity.getItem().getCount() - 1); return; } if (itemEntity.getItem().is(ModItemTags.UNBROKEN_FIRE_STARTER)) { - ignite(level, pos); + OilCauldronBlock.ignite(level, pos); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilFluidInterfaceBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilFluidInterfaceBlock.java index 5d071ac030..9c969186eb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilFluidInterfaceBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilFluidInterfaceBlock.java @@ -14,6 +14,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.phys.shapes.CollisionContext; @@ -28,13 +29,13 @@ public class CelestialForgingAnvilFluidInterfaceBlock extends CelestialForgingAn Block.box(4, 9, 6, 12, 22, 14), Block.box(5, 12, 1, 11, 18, 7) ); - public static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, NORTH); - public static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, NORTH); - public static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, NORTH); + public static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, CelestialForgingAnvilFluidInterfaceBlock.NORTH); + public static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, CelestialForgingAnvilFluidInterfaceBlock.NORTH); + public static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, CelestialForgingAnvilFluidInterfaceBlock.NORTH); @Override protected MapCodec codec() { - return simpleCodec(CelestialForgingAnvilFluidInterfaceBlock::new); + return BlockBehaviour.simpleCodec(CelestialForgingAnvilFluidInterfaceBlock::new); } public CelestialForgingAnvilFluidInterfaceBlock(Properties properties) { @@ -43,18 +44,18 @@ public CelestialForgingAnvilFluidInterfaceBlock(Properties properties) { @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case NORTH -> NORTH; - case SOUTH -> SOUTH; - case WEST -> WEST; - case EAST -> EAST; + return switch (state.getValue(HorizontalDirectionalBlock.FACING)) { + case NORTH -> CelestialForgingAnvilFluidInterfaceBlock.NORTH; + case SOUTH -> CelestialForgingAnvilFluidInterfaceBlock.SOUTH; + case WEST -> CelestialForgingAnvilFluidInterfaceBlock.WEST; + case EAST -> CelestialForgingAnvilFluidInterfaceBlock.EAST; default -> throw new IllegalArgumentException("Unsupported direction for horizontal facing"); }; } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ACTIVE); + builder.add(HorizontalDirectionalBlock.FACING, CelestialForgingAnvilInterfaceBlock.ACTIVE); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilInterfacePlaceholderBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilInterfacePlaceholderBlock.java index a9612e7c71..1a5361713d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilInterfacePlaceholderBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilInterfacePlaceholderBlock.java @@ -70,7 +70,7 @@ protected InteractionResult useItemOn( .setValue(CelestialForgingAnvilInterfaceBlock.FACING, facing) .setValue(CelestialForgingAnvilInterfaceBlock.ACTIVE, false); level.setBlockAndUpdate(pos, placementState); - SoundType soundType = placementState.getSoundType(); + SoundType soundType = placementState.getSoundType(level, pos, player); level.playSound(null, pos, soundType.getPlaceSound(), SoundSource.BLOCKS, (soundType.getVolume() + 1.0f) / 2.0f, soundType.getPitch() * 0.8f); if (!player.getAbilities().instabuild) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLaserInterfaceBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLaserInterfaceBlock.java index f50a8c1d4d..bf4d7f8674 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLaserInterfaceBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLaserInterfaceBlock.java @@ -14,6 +14,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.phys.shapes.CollisionContext; @@ -29,13 +30,13 @@ public class CelestialForgingAnvilLaserInterfaceBlock extends CelestialForgingAn Block.box(4, 8, 6, 12, 16, 14), Block.box(5, 12, 1, 11, 18, 7) ); - public static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, NORTH); - public static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, NORTH); - public static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, NORTH); + public static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, CelestialForgingAnvilLaserInterfaceBlock.NORTH); + public static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, CelestialForgingAnvilLaserInterfaceBlock.NORTH); + public static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, CelestialForgingAnvilLaserInterfaceBlock.NORTH); @Override protected MapCodec codec() { - return simpleCodec(CelestialForgingAnvilLaserInterfaceBlock::new); + return BlockBehaviour.simpleCodec(CelestialForgingAnvilLaserInterfaceBlock::new); } public CelestialForgingAnvilLaserInterfaceBlock(Properties properties) { @@ -44,18 +45,18 @@ public CelestialForgingAnvilLaserInterfaceBlock(Properties properties) { @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case NORTH -> NORTH; - case SOUTH -> SOUTH; - case WEST -> WEST; - case EAST -> EAST; + return switch (state.getValue(HorizontalDirectionalBlock.FACING)) { + case NORTH -> CelestialForgingAnvilLaserInterfaceBlock.NORTH; + case SOUTH -> CelestialForgingAnvilLaserInterfaceBlock.SOUTH; + case WEST -> CelestialForgingAnvilLaserInterfaceBlock.WEST; + case EAST -> CelestialForgingAnvilLaserInterfaceBlock.EAST; default -> throw new IllegalArgumentException("Unsupported direction for horizontal facing"); }; } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ACTIVE); + builder.add(HorizontalDirectionalBlock.FACING, CelestialForgingAnvilInterfaceBlock.ACTIVE); } @Override @@ -69,7 +70,7 @@ protected void createBlockStateDefinition(StateDefinition.Builder type ) { if (type == ModBlockEntities.CELESTIAL_FORGING_ANVIL_LASER_INTERFACE.get()) { - return (BlockEntityTicker) (lvl, pos, st, be) -> { + return (lvl, pos, st, be) -> { if (level.isClientSide()) { ((CelestialForgingAnvilLaserInterfaceBlockEntity) be).tick(lvl); } else { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLogisticsInterfaceBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLogisticsInterfaceBlock.java index 60045bf9a6..b54bb3c2d1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLogisticsInterfaceBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cfa/interfaces/CelestialForgingAnvilLogisticsInterfaceBlock.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.phys.shapes.CollisionContext; @@ -32,13 +33,13 @@ public class CelestialForgingAnvilLogisticsInterfaceBlock extends CelestialForgi Block.box(4, 8, 6, 12, 16, 14), Block.box(5, 12, 1, 11, 18, 7) ); - public static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, NORTH); - public static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, NORTH); - public static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, NORTH); + public static final VoxelShape WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, CelestialForgingAnvilLogisticsInterfaceBlock.NORTH); + public static final VoxelShape SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, CelestialForgingAnvilLogisticsInterfaceBlock.NORTH); + public static final VoxelShape EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, CelestialForgingAnvilLogisticsInterfaceBlock.NORTH); @Override protected MapCodec codec() { - return simpleCodec(CelestialForgingAnvilLogisticsInterfaceBlock::new); + return BlockBehaviour.simpleCodec(CelestialForgingAnvilLogisticsInterfaceBlock::new); } public CelestialForgingAnvilLogisticsInterfaceBlock(Properties properties) { @@ -47,18 +48,18 @@ public CelestialForgingAnvilLogisticsInterfaceBlock(Properties properties) { @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case NORTH -> NORTH; - case SOUTH -> SOUTH; - case WEST -> WEST; - case EAST -> EAST; + return switch (state.getValue(HorizontalDirectionalBlock.FACING)) { + case NORTH -> CelestialForgingAnvilLogisticsInterfaceBlock.NORTH; + case SOUTH -> CelestialForgingAnvilLogisticsInterfaceBlock.SOUTH; + case WEST -> CelestialForgingAnvilLogisticsInterfaceBlock.WEST; + case EAST -> CelestialForgingAnvilLogisticsInterfaceBlock.EAST; default -> throw new IllegalArgumentException("Unsupported direction for horizontal facing"); }; } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ACTIVE); + builder.add(HorizontalDirectionalBlock.FACING, CelestialForgingAnvilInterfaceBlock.ACTIVE); } @Override @@ -73,7 +74,7 @@ protected void createBlockStateDefinition(StateDefinition.Builder) (lvl, pos, st, be) -> + return (lvl, pos, st, be) -> ((CelestialForgingAnvilLogisticsInterfaceBlockEntity) be).serverTick(); } return null; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilBlockItem.java index e7363dc323..89e010244f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilBlockItem.java @@ -26,8 +26,16 @@ public boolean canPlace(BlockPlaceContext context, BlockState state) { Player player = context.getPlayer(); BlockPos clickedPos = context.getClickedPos(); for (BlockPos pos : BlockPos.betweenClosed( - clickedPos.offset(PLACEMENT_RADIUS, PLACEMENT_RADIUS, PLACEMENT_RADIUS), - clickedPos.offset(-PLACEMENT_RADIUS, -PLACEMENT_RADIUS, -PLACEMENT_RADIUS) + clickedPos.offset( + CelestialForgingAnvilBlockItem.PLACEMENT_RADIUS, + CelestialForgingAnvilBlockItem.PLACEMENT_RADIUS, + CelestialForgingAnvilBlockItem.PLACEMENT_RADIUS + ), + clickedPos.offset( + -CelestialForgingAnvilBlockItem.PLACEMENT_RADIUS, + -CelestialForgingAnvilBlockItem.PLACEMENT_RADIUS, + -CelestialForgingAnvilBlockItem.PLACEMENT_RADIUS + ) )) { if (level.getBlockState(pos).is(this.getBlock())) { if (level.isClientSide() && player != null) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilInterfaceBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilInterfaceBlockItem.java index c97c6140c6..186ec404fb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilInterfaceBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/cfa/item/CelestialForgingAnvilInterfaceBlockItem.java @@ -55,10 +55,11 @@ public CelestialForgingAnvilInterfaceBlockItem(Block block, Properties propertie } if (!cfaDir.isEmpty()) { if (cfaDir.contains(player.getDirection())) { - return getBlock().defaultBlockState() + return this.getBlock().defaultBlockState() .setValue(CelestialForgingAnvilInterfaceBlock.FACING, player.getDirection().getOpposite()); } - return getBlock().defaultBlockState().setValue(CelestialForgingAnvilInterfaceBlock.FACING, cfaDir.getFirst().getOpposite()); + return this.getBlock().defaultBlockState() + .setValue(CelestialForgingAnvilInterfaceBlock.FACING, cfaDir.getFirst().getOpposite()); } if (player instanceof ServerPlayer serverPlayer) { serverPlayer.sendSystemMessage( diff --git a/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeCrateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeCrateBlock.java index 602e8e1c77..bd90633bac 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeCrateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeCrateBlock.java @@ -12,6 +12,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; 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; @@ -30,7 +31,7 @@ public CreativeCrateBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(CreativeCrateBlock::new); + return BlockBehaviour.simpleCodec(CreativeCrateBlock::new); } @Nullable diff --git a/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeFluidTankBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeFluidTankBlock.java index 5e99a497c8..8fdc783a6a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeFluidTankBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/container/CreativeFluidTankBlock.java @@ -12,6 +12,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; 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; @@ -30,7 +31,7 @@ public CreativeFluidTankBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(CreativeFluidTankBlock::new); + return BlockBehaviour.simpleCodec(CreativeFluidTankBlock::new); } @Nullable diff --git a/src/main/java/dev/dubhe/anvilcraft/block/container/FluidTankBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/container/FluidTankBlock.java index dac77c3b87..ba4afb038b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/container/FluidTankBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/container/FluidTankBlock.java @@ -24,6 +24,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; 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; @@ -41,7 +42,7 @@ public FluidTankBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(FluidTankBlock::new); + return BlockBehaviour.simpleCodec(FluidTankBlock::new); } @Nullable @@ -58,7 +59,7 @@ public BlockEntityTicker getTicker( BlockEntityType type ) { if (level.isClientSide()) return null; - return createTickerHelper(type, ModBlockEntities.FLUID_TANK.get(), FluidTankBlockEntity::serverTick); + return BaseEntityBlock.createTickerHelper(type, ModBlockEntities.FLUID_TANK.get(), FluidTankBlockEntity::serverTick); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/container/LargeFluidTankBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/container/LargeFluidTankBlock.java index 660b17c2e2..3b688116a5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/container/LargeFluidTankBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/container/LargeFluidTankBlock.java @@ -39,7 +39,6 @@ import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.HitResult; import net.neoforged.neoforge.common.world.AuxiliaryLightManager; import org.jspecify.annotations.Nullable; @@ -54,7 +53,7 @@ public LargeFluidTankBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(HALF, Cube3x3PartHalf.BOTTOM_CENTER)); + .setValue(LargeFluidTankBlock.HALF, Cube3x3PartHalf.BOTTOM_CENTER)); } @Override @@ -64,22 +63,22 @@ public Vec3i getMainPartOffset() { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF); + builder.add(LargeFluidTankBlock.HALF); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)); + return state.setValue(LargeFluidTankBlock.HALF, state.getValue(LargeFluidTankBlock.HALF).rotate(rotation)); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)); + return state.setValue(LargeFluidTankBlock.HALF, state.getValue(LargeFluidTankBlock.HALF).mirror(mirror)); } @Override public Property getPart() { - return HALF; + return LargeFluidTankBlock.HALF; } @Override @@ -137,7 +136,7 @@ protected InteractionResult useItemOn( ) { InteractionResult result = super.useItemOn(stack, state, level, pos, player, hand, hitResult); if (result == InteractionResult.PASS) { - BlockPos mainPartPos = getMainPartPos(pos, state); + BlockPos mainPartPos = this.getMainPartPos(pos, state); BlockEntity blockEntity = level.getBlockEntity(mainPartPos); if (blockEntity instanceof LargeFluidTankBlockEntity tank) { if (tank.onPlayerUse(player, hand)) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/container/storage/HyperdimensionStorageStationBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/container/storage/HyperdimensionStorageStationBlock.java index 45d3c202f4..d885e34d5e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/container/storage/HyperdimensionStorageStationBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/container/storage/HyperdimensionStorageStationBlock.java @@ -111,34 +111,34 @@ protected InteractionResult useItemOn( // region VoxelShapes @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(HALF)) { - case BOTTOM_CENTER -> BOTTOM_CENTER; - case BOTTOM_W -> BOTTOM_W; - case BOTTOM_E -> BOTTOM_E; - case BOTTOM_N -> BOTTOM_N; - case BOTTOM_S -> BOTTOM_S; - case BOTTOM_WN -> BOTTOM_NW; - case BOTTOM_WS -> BOTTOM_SW; - case BOTTOM_EN -> BOTTOM_NE; - case BOTTOM_ES -> BOTTOM_SE; - case MID_CENTER -> MID_CENTER; - case MID_N -> MID_N; - case MID_W -> MID_W; - case MID_S -> MID_S; - case MID_E -> MID_E; - case MID_WN -> MID_NW; - case MID_WS -> MID_SW; - case MID_EN -> MID_NE; - case MID_ES -> MID_SE; - case TOP_CENTER -> TOP_CENTER; - case TOP_W -> TOP_W; - case TOP_E -> TOP_E; - case TOP_N -> TOP_N; - case TOP_S -> TOP_S; - case TOP_WN -> TOP_NW; - case TOP_WS -> TOP_SW; - case TOP_EN -> TOP_NE; - case TOP_ES -> TOP_SE; + return switch (state.getValue(HyperdimensionStorageStationBlock.HALF)) { + case BOTTOM_CENTER -> HyperdimensionStorageStationBlock.BOTTOM_CENTER; + case BOTTOM_W -> HyperdimensionStorageStationBlock.BOTTOM_W; + case BOTTOM_E -> HyperdimensionStorageStationBlock.BOTTOM_E; + case BOTTOM_N -> HyperdimensionStorageStationBlock.BOTTOM_N; + case BOTTOM_S -> HyperdimensionStorageStationBlock.BOTTOM_S; + case BOTTOM_WN -> HyperdimensionStorageStationBlock.BOTTOM_NW; + case BOTTOM_WS -> HyperdimensionStorageStationBlock.BOTTOM_SW; + case BOTTOM_EN -> HyperdimensionStorageStationBlock.BOTTOM_NE; + case BOTTOM_ES -> HyperdimensionStorageStationBlock.BOTTOM_SE; + case MID_CENTER -> HyperdimensionStorageStationBlock.MID_CENTER; + case MID_N -> HyperdimensionStorageStationBlock.MID_N; + case MID_W -> HyperdimensionStorageStationBlock.MID_W; + case MID_S -> HyperdimensionStorageStationBlock.MID_S; + case MID_E -> HyperdimensionStorageStationBlock.MID_E; + case MID_WN -> HyperdimensionStorageStationBlock.MID_NW; + case MID_WS -> HyperdimensionStorageStationBlock.MID_SW; + case MID_EN -> HyperdimensionStorageStationBlock.MID_NE; + case MID_ES -> HyperdimensionStorageStationBlock.MID_SE; + case TOP_CENTER -> HyperdimensionStorageStationBlock.TOP_CENTER; + case TOP_W -> HyperdimensionStorageStationBlock.TOP_W; + case TOP_E -> HyperdimensionStorageStationBlock.TOP_E; + case TOP_N -> HyperdimensionStorageStationBlock.TOP_N; + case TOP_S -> HyperdimensionStorageStationBlock.TOP_S; + case TOP_WN -> HyperdimensionStorageStationBlock.TOP_NW; + case TOP_WS -> HyperdimensionStorageStationBlock.TOP_SW; + case TOP_EN -> HyperdimensionStorageStationBlock.TOP_NE; + case TOP_ES -> HyperdimensionStorageStationBlock.TOP_SE; }; } @@ -154,9 +154,9 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, new AABB(4, 7, 7, 12, 14, 14) ); - protected static final VoxelShape BOTTOM_W = ShapeUtil.rotate(Direction.Axis.Y, 90, BOTTOM_N); - protected static final VoxelShape BOTTOM_S = ShapeUtil.rotate(Direction.Axis.Y, 180, BOTTOM_N); - protected static final VoxelShape BOTTOM_E = ShapeUtil.rotate(Direction.Axis.Y, 270, BOTTOM_N); + protected static final VoxelShape BOTTOM_W = ShapeUtil.rotate(Direction.Axis.Y, 90, HyperdimensionStorageStationBlock.BOTTOM_N); + protected static final VoxelShape BOTTOM_S = ShapeUtil.rotate(Direction.Axis.Y, 180, HyperdimensionStorageStationBlock.BOTTOM_N); + protected static final VoxelShape BOTTOM_E = ShapeUtil.rotate(Direction.Axis.Y, 270, HyperdimensionStorageStationBlock.BOTTOM_N); protected static final VoxelShape BOTTOM_NW = ShapeUtil.merge( new AABB(0, 0, 0, 10, 10, 10), @@ -168,30 +168,30 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, new AABB(14, 4, 14, 16, 16, 16), new AABB(14, 14, 4, 16, 16, 16) ); - protected static final VoxelShape BOTTOM_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, BOTTOM_NW); - protected static final VoxelShape BOTTOM_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, BOTTOM_NW); - protected static final VoxelShape BOTTOM_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, BOTTOM_NW); + protected static final VoxelShape BOTTOM_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, HyperdimensionStorageStationBlock.BOTTOM_NW); + protected static final VoxelShape BOTTOM_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, HyperdimensionStorageStationBlock.BOTTOM_NW); + protected static final VoxelShape BOTTOM_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, HyperdimensionStorageStationBlock.BOTTOM_NW); protected static final VoxelShape MID_N = Block.boxZ(16, 4, 16); - protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_N); - protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_N); - protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_N); - protected static final VoxelShape BOTTOM_CENTER = ShapeUtil.rotate(Direction.Axis.X, 90, MID_N); - protected static final VoxelShape TOP_CENTER = ShapeUtil.rotate(Direction.Axis.X, 270, MID_N); - - protected static final VoxelShape MID_NW = ShapeUtil.rotate(Direction.Axis.Z, 90, BOTTOM_N); - protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_NW); - protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_NW); - protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_NW); - - protected static final VoxelShape TOP_N = ShapeUtil.rotate(Direction.Axis.Z, 180, BOTTOM_N); - protected static final VoxelShape TOP_W = ShapeUtil.rotate(Direction.Axis.Y, 90, TOP_N); - protected static final VoxelShape TOP_S = ShapeUtil.rotate(Direction.Axis.Y, 180, TOP_N); - protected static final VoxelShape TOP_E = ShapeUtil.rotate(Direction.Axis.Y, 270, TOP_N); - - protected static final VoxelShape TOP_NW = ShapeUtil.rotate(Direction.Axis.X, 270, BOTTOM_NW); - protected static final VoxelShape TOP_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, TOP_NW); - protected static final VoxelShape TOP_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, TOP_NW); - protected static final VoxelShape TOP_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, TOP_NW); + protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, HyperdimensionStorageStationBlock.MID_N); + protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, HyperdimensionStorageStationBlock.MID_N); + protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, HyperdimensionStorageStationBlock.MID_N); + protected static final VoxelShape BOTTOM_CENTER = ShapeUtil.rotate(Direction.Axis.X, 90, HyperdimensionStorageStationBlock.MID_N); + protected static final VoxelShape TOP_CENTER = ShapeUtil.rotate(Direction.Axis.X, 270, HyperdimensionStorageStationBlock.MID_N); + + protected static final VoxelShape MID_NW = ShapeUtil.rotate(Direction.Axis.Z, 90, HyperdimensionStorageStationBlock.BOTTOM_N); + protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, HyperdimensionStorageStationBlock.MID_NW); + protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, HyperdimensionStorageStationBlock.MID_NW); + protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, HyperdimensionStorageStationBlock.MID_NW); + + protected static final VoxelShape TOP_N = ShapeUtil.rotate(Direction.Axis.Z, 180, HyperdimensionStorageStationBlock.BOTTOM_N); + protected static final VoxelShape TOP_W = ShapeUtil.rotate(Direction.Axis.Y, 90, HyperdimensionStorageStationBlock.TOP_N); + protected static final VoxelShape TOP_S = ShapeUtil.rotate(Direction.Axis.Y, 180, HyperdimensionStorageStationBlock.TOP_N); + protected static final VoxelShape TOP_E = ShapeUtil.rotate(Direction.Axis.Y, 270, HyperdimensionStorageStationBlock.TOP_N); + + protected static final VoxelShape TOP_NW = ShapeUtil.rotate(Direction.Axis.X, 270, HyperdimensionStorageStationBlock.BOTTOM_NW); + protected static final VoxelShape TOP_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, HyperdimensionStorageStationBlock.TOP_NW); + protected static final VoxelShape TOP_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, HyperdimensionStorageStationBlock.TOP_NW); + protected static final VoxelShape TOP_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, HyperdimensionStorageStationBlock.TOP_NW); // endregion } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/container/storage/LargeCrateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/container/storage/LargeCrateBlock.java index b33b5caddf..d5772cebf7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/container/storage/LargeCrateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/container/storage/LargeCrateBlock.java @@ -111,53 +111,53 @@ protected InteractionResult useItemOn( // region VoxelShapes @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(HALF)) { - case BOTTOM_CENTER -> BOTTOM_CENTER; - case BOTTOM_W -> BOTTOM_W; - case BOTTOM_E -> BOTTOM_E; - case BOTTOM_N -> BOTTOM_N; - case BOTTOM_S -> BOTTOM_S; - case BOTTOM_WN -> BOTTOM_NW; - case BOTTOM_WS -> BOTTOM_SW; - case BOTTOM_EN -> BOTTOM_NE; - case BOTTOM_ES -> BOTTOM_SE; - case MID_CENTER -> MID_CENTER; - case MID_W -> MID_W; - case MID_E -> MID_E; - case MID_N -> MID_N; - case MID_S -> MID_S; - case MID_WN -> MID_NW; - case MID_WS -> MID_SW; - case MID_EN -> MID_NE; - case MID_ES -> MID_SE; - case TOP_CENTER -> TOP_CENTER; - case TOP_W -> TOP_W; - case TOP_E -> TOP_E; - case TOP_N -> TOP_N; - case TOP_S -> TOP_S; - case TOP_WN -> TOP_NW; - case TOP_WS -> TOP_SW; - case TOP_EN -> TOP_NE; - case TOP_ES -> TOP_SE; + return switch (state.getValue(LargeCrateBlock.HALF)) { + case BOTTOM_CENTER -> LargeCrateBlock.BOTTOM_CENTER; + case BOTTOM_W -> LargeCrateBlock.BOTTOM_W; + case BOTTOM_E -> LargeCrateBlock.BOTTOM_E; + case BOTTOM_N -> LargeCrateBlock.BOTTOM_N; + case BOTTOM_S -> LargeCrateBlock.BOTTOM_S; + case BOTTOM_WN -> LargeCrateBlock.BOTTOM_NW; + case BOTTOM_WS -> LargeCrateBlock.BOTTOM_SW; + case BOTTOM_EN -> LargeCrateBlock.BOTTOM_NE; + case BOTTOM_ES -> LargeCrateBlock.BOTTOM_SE; + case MID_CENTER -> LargeCrateBlock.MID_CENTER; + case MID_W -> LargeCrateBlock.MID_W; + case MID_E -> LargeCrateBlock.MID_E; + case MID_N -> LargeCrateBlock.MID_N; + case MID_S -> LargeCrateBlock.MID_S; + case MID_WN -> LargeCrateBlock.MID_NW; + case MID_WS -> LargeCrateBlock.MID_SW; + case MID_EN -> LargeCrateBlock.MID_NE; + case MID_ES -> LargeCrateBlock.MID_SE; + case TOP_CENTER -> LargeCrateBlock.TOP_CENTER; + case TOP_W -> LargeCrateBlock.TOP_W; + case TOP_E -> LargeCrateBlock.TOP_E; + case TOP_N -> LargeCrateBlock.TOP_N; + case TOP_S -> LargeCrateBlock.TOP_S; + case TOP_WN -> LargeCrateBlock.TOP_NW; + case TOP_WS -> LargeCrateBlock.TOP_SW; + case TOP_EN -> LargeCrateBlock.TOP_NE; + case TOP_ES -> LargeCrateBlock.TOP_SE; }; } protected static final VoxelShape MID_CENTER = Shapes.block(); protected static final VoxelShape BOTTOM_CENTER = Block.box(0, 2, 0, 16, 16, 16); - protected static final VoxelShape TOP_CENTER = ShapeUtil.rotate(Direction.Axis.X, 180, BOTTOM_CENTER); - protected static final VoxelShape MID_N = ShapeUtil.rotate(Direction.Axis.X, 270, BOTTOM_CENTER); - protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_N); - protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_N); - protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_N); + protected static final VoxelShape TOP_CENTER = ShapeUtil.rotate(Direction.Axis.X, 180, LargeCrateBlock.BOTTOM_CENTER); + protected static final VoxelShape MID_N = ShapeUtil.rotate(Direction.Axis.X, 270, LargeCrateBlock.BOTTOM_CENTER); + protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, LargeCrateBlock.MID_N); + protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, LargeCrateBlock.MID_N); + protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, LargeCrateBlock.MID_N); protected static final VoxelShape BOTTOM_N = ShapeUtil.merge( new AABB(0, 2, 2, 16, 16, 16), new AABB(0, 0, 0, 16, 7, 7) ); - protected static final VoxelShape BOTTOM_W = ShapeUtil.rotate(Direction.Axis.Y, 90, BOTTOM_N); - protected static final VoxelShape BOTTOM_S = ShapeUtil.rotate(Direction.Axis.Y, 180, BOTTOM_N); - protected static final VoxelShape BOTTOM_E = ShapeUtil.rotate(Direction.Axis.Y, 270, BOTTOM_N); + protected static final VoxelShape BOTTOM_W = ShapeUtil.rotate(Direction.Axis.Y, 90, LargeCrateBlock.BOTTOM_N); + protected static final VoxelShape BOTTOM_S = ShapeUtil.rotate(Direction.Axis.Y, 180, LargeCrateBlock.BOTTOM_N); + protected static final VoxelShape BOTTOM_E = ShapeUtil.rotate(Direction.Axis.Y, 270, LargeCrateBlock.BOTTOM_N); protected static final VoxelShape BOTTOM_NW = ShapeUtil.cut( new AABB(0, 0, 0, 16, 16, 16), @@ -165,23 +165,23 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, new AABB(7, 0, 7, 16, 2, 16), new AABB(0, 7, 7, 2, 16, 16) ); - protected static final VoxelShape BOTTOM_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, BOTTOM_NW); - protected static final VoxelShape BOTTOM_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, BOTTOM_NW); - protected static final VoxelShape BOTTOM_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, BOTTOM_NW); - - protected static final VoxelShape MID_NW = ShapeUtil.rotate(Direction.Axis.Z, 90, BOTTOM_N); - protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_NW); - protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_NW); - protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_NW); - - protected static final VoxelShape TOP_N = ShapeUtil.rotate(Direction.Axis.Z, 180, BOTTOM_N); - protected static final VoxelShape TOP_W = ShapeUtil.rotate(Direction.Axis.Y, 90, TOP_N); - protected static final VoxelShape TOP_S = ShapeUtil.rotate(Direction.Axis.Y, 180, TOP_N); - protected static final VoxelShape TOP_E = ShapeUtil.rotate(Direction.Axis.Y, 270, TOP_N); - - protected static final VoxelShape TOP_NW = ShapeUtil.rotate(Direction.Axis.X, 270, BOTTOM_NW); - protected static final VoxelShape TOP_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, TOP_NW); - protected static final VoxelShape TOP_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, TOP_NW); - protected static final VoxelShape TOP_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, TOP_NW); + protected static final VoxelShape BOTTOM_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, LargeCrateBlock.BOTTOM_NW); + protected static final VoxelShape BOTTOM_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, LargeCrateBlock.BOTTOM_NW); + protected static final VoxelShape BOTTOM_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, LargeCrateBlock.BOTTOM_NW); + + protected static final VoxelShape MID_NW = ShapeUtil.rotate(Direction.Axis.Z, 90, LargeCrateBlock.BOTTOM_N); + protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, LargeCrateBlock.MID_NW); + protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, LargeCrateBlock.MID_NW); + protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, LargeCrateBlock.MID_NW); + + protected static final VoxelShape TOP_N = ShapeUtil.rotate(Direction.Axis.Z, 180, LargeCrateBlock.BOTTOM_N); + protected static final VoxelShape TOP_W = ShapeUtil.rotate(Direction.Axis.Y, 90, LargeCrateBlock.TOP_N); + protected static final VoxelShape TOP_S = ShapeUtil.rotate(Direction.Axis.Y, 180, LargeCrateBlock.TOP_N); + protected static final VoxelShape TOP_E = ShapeUtil.rotate(Direction.Axis.Y, 270, LargeCrateBlock.TOP_N); + + protected static final VoxelShape TOP_NW = ShapeUtil.rotate(Direction.Axis.X, 270, LargeCrateBlock.BOTTOM_NW); + protected static final VoxelShape TOP_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, LargeCrateBlock.TOP_NW); + protected static final VoxelShape TOP_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, LargeCrateBlock.TOP_NW); + protected static final VoxelShape TOP_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, LargeCrateBlock.TOP_NW); // endregion } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/container/storage/ShulkerContainerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/container/storage/ShulkerContainerBlock.java index abd1425af7..c98063e5c0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/container/storage/ShulkerContainerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/container/storage/ShulkerContainerBlock.java @@ -46,8 +46,8 @@ public ShulkerContainerBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition.any() - .setValue(HALF, OpenedCube3x3PartHalf.BOTTOM_CENTER) - .setValue(OPENED, false) + .setValue(ShulkerContainerBlock.HALF, OpenedCube3x3PartHalf.BOTTOM_CENTER) + .setValue(ShulkerContainerBlock.OPENED, false) ); } @@ -58,12 +58,12 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)); + return state.setValue(ShulkerContainerBlock.HALF, state.getValue(ShulkerContainerBlock.HALF).rotate(rotation)); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)); + return state.setValue(ShulkerContainerBlock.HALF, state.getValue(ShulkerContainerBlock.HALF).mirror(mirror)); } @Override @@ -111,8 +111,8 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou public void setOpened(Level level, BlockPos pos, boolean opened) { BlockState state = level.getBlockState(pos); - if (state.is(this) && state.getValue(OPENED) != opened) { - this.updateState(level, pos, OPENED, opened, Block.UPDATE_ALL); + if (state.is(this) && state.getValue(ShulkerContainerBlock.OPENED) != opened) { + this.updateState(level, pos, ShulkerContainerBlock.OPENED, opened, Block.UPDATE_ALL); } } @@ -152,45 +152,45 @@ protected InteractionResult useItemOn( // region VoxelShapes @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(HALF)) { - case BOTTOM_CENTER -> BOTTOM_CENTER; - case BOTTOM_W -> BOTTOM_W; - case BOTTOM_E -> BOTTOM_E; - case BOTTOM_N -> BOTTOM_N; - case BOTTOM_S -> BOTTOM_S; - case BOTTOM_NW -> BOTTOM_NW; - case BOTTOM_SW -> BOTTOM_SW; - case BOTTOM_NE -> BOTTOM_NE; - case BOTTOM_SE -> BOTTOM_SE; - case MID_CENTER -> MID_CENTER; - case MID_W -> MID_W; - case MID_E -> MID_E; - case MID_N -> MID_N; - case MID_S -> MID_S; - case MID_NW -> MID_NW; - case MID_SW -> MID_SW; - case MID_NE -> MID_NE; - case MID_SE -> MID_SE; - case TOP_CENTER -> TOP_CENTER; - case TOP_W -> TOP_W; - case TOP_E -> TOP_E; - case TOP_N -> TOP_N; - case TOP_S -> TOP_S; - case TOP_NW -> TOP_NW; - case TOP_SW -> TOP_SW; - case TOP_NE -> TOP_NE; - case TOP_SE -> TOP_SE; + return switch (state.getValue(ShulkerContainerBlock.HALF)) { + case BOTTOM_CENTER -> ShulkerContainerBlock.BOTTOM_CENTER; + case BOTTOM_W -> ShulkerContainerBlock.BOTTOM_W; + case BOTTOM_E -> ShulkerContainerBlock.BOTTOM_E; + case BOTTOM_N -> ShulkerContainerBlock.BOTTOM_N; + case BOTTOM_S -> ShulkerContainerBlock.BOTTOM_S; + case BOTTOM_NW -> ShulkerContainerBlock.BOTTOM_NW; + case BOTTOM_SW -> ShulkerContainerBlock.BOTTOM_SW; + case BOTTOM_NE -> ShulkerContainerBlock.BOTTOM_NE; + case BOTTOM_SE -> ShulkerContainerBlock.BOTTOM_SE; + case MID_CENTER -> ShulkerContainerBlock.MID_CENTER; + case MID_W -> ShulkerContainerBlock.MID_W; + case MID_E -> ShulkerContainerBlock.MID_E; + case MID_N -> ShulkerContainerBlock.MID_N; + case MID_S -> ShulkerContainerBlock.MID_S; + case MID_NW -> ShulkerContainerBlock.MID_NW; + case MID_SW -> ShulkerContainerBlock.MID_SW; + case MID_NE -> ShulkerContainerBlock.MID_NE; + case MID_SE -> ShulkerContainerBlock.MID_SE; + case TOP_CENTER -> ShulkerContainerBlock.TOP_CENTER; + case TOP_W -> ShulkerContainerBlock.TOP_W; + case TOP_E -> ShulkerContainerBlock.TOP_E; + case TOP_N -> ShulkerContainerBlock.TOP_N; + case TOP_S -> ShulkerContainerBlock.TOP_S; + case TOP_NW -> ShulkerContainerBlock.TOP_NW; + case TOP_SW -> ShulkerContainerBlock.TOP_SW; + case TOP_NE -> ShulkerContainerBlock.TOP_NE; + case TOP_SE -> ShulkerContainerBlock.TOP_SE; }; } protected static final VoxelShape MID_CENTER = Shapes.block(); protected static final VoxelShape BOTTOM_CENTER = Block.box(0, 2, 0, 16, 16, 16); - protected static final VoxelShape TOP_CENTER = ShapeUtil.rotate(Direction.Axis.X, 180, BOTTOM_CENTER); - protected static final VoxelShape MID_N = ShapeUtil.rotate(Direction.Axis.X, 270, BOTTOM_CENTER); - protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_N); - protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_N); - protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_N); + protected static final VoxelShape TOP_CENTER = ShapeUtil.rotate(Direction.Axis.X, 180, ShulkerContainerBlock.BOTTOM_CENTER); + protected static final VoxelShape MID_N = ShapeUtil.rotate(Direction.Axis.X, 270, ShulkerContainerBlock.BOTTOM_CENTER); + protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, ShulkerContainerBlock.MID_N); + protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, ShulkerContainerBlock.MID_N); + protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, ShulkerContainerBlock.MID_N); protected static final VoxelShape BOTTOM_N = ShapeUtil.merge( new AABB(0, 2, 2, 16, 16, 16), @@ -198,9 +198,9 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, new AABB(0, 0, 0, 4, 8, 8), new AABB(12, 0, 0, 16, 8, 8) ); - protected static final VoxelShape BOTTOM_W = ShapeUtil.rotate(Direction.Axis.Y, 90, BOTTOM_N); - protected static final VoxelShape BOTTOM_S = ShapeUtil.rotate(Direction.Axis.Y, 180, BOTTOM_N); - protected static final VoxelShape BOTTOM_E = ShapeUtil.rotate(Direction.Axis.Y, 270, BOTTOM_N); + protected static final VoxelShape BOTTOM_W = ShapeUtil.rotate(Direction.Axis.Y, 90, ShulkerContainerBlock.BOTTOM_N); + protected static final VoxelShape BOTTOM_S = ShapeUtil.rotate(Direction.Axis.Y, 180, ShulkerContainerBlock.BOTTOM_N); + protected static final VoxelShape BOTTOM_E = ShapeUtil.rotate(Direction.Axis.Y, 270, ShulkerContainerBlock.BOTTOM_N); protected static final VoxelShape BOTTOM_NW = ShapeUtil.merge( new AABB(2, 2, 2, 16, 16, 16), @@ -208,23 +208,23 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, new AABB(0, 8, 0, 8, 12, 8), new AABB(0, 0, 8, 8, 8, 12) ); - protected static final VoxelShape BOTTOM_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, BOTTOM_NW); - protected static final VoxelShape BOTTOM_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, BOTTOM_NW); - protected static final VoxelShape BOTTOM_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, BOTTOM_NW); - - protected static final VoxelShape MID_NW = ShapeUtil.rotate(Direction.Axis.Z, 90, BOTTOM_N); - protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_NW); - protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_NW); - protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_NW); - - protected static final VoxelShape TOP_N = ShapeUtil.rotate(Direction.Axis.Z, 180, BOTTOM_N); - protected static final VoxelShape TOP_W = ShapeUtil.rotate(Direction.Axis.Y, 90, TOP_N); - protected static final VoxelShape TOP_S = ShapeUtil.rotate(Direction.Axis.Y, 180, TOP_N); - protected static final VoxelShape TOP_E = ShapeUtil.rotate(Direction.Axis.Y, 270, TOP_N); - - protected static final VoxelShape TOP_NW = ShapeUtil.rotate(Direction.Axis.X, 270, BOTTOM_NW); - protected static final VoxelShape TOP_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, TOP_NW); - protected static final VoxelShape TOP_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, TOP_NW); - protected static final VoxelShape TOP_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, TOP_NW); + protected static final VoxelShape BOTTOM_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, ShulkerContainerBlock.BOTTOM_NW); + protected static final VoxelShape BOTTOM_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, ShulkerContainerBlock.BOTTOM_NW); + protected static final VoxelShape BOTTOM_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, ShulkerContainerBlock.BOTTOM_NW); + + protected static final VoxelShape MID_NW = ShapeUtil.rotate(Direction.Axis.Z, 90, ShulkerContainerBlock.BOTTOM_N); + protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, ShulkerContainerBlock.MID_NW); + protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, ShulkerContainerBlock.MID_NW); + protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, ShulkerContainerBlock.MID_NW); + + protected static final VoxelShape TOP_N = ShapeUtil.rotate(Direction.Axis.Z, 180, ShulkerContainerBlock.BOTTOM_N); + protected static final VoxelShape TOP_W = ShapeUtil.rotate(Direction.Axis.Y, 90, ShulkerContainerBlock.TOP_N); + protected static final VoxelShape TOP_S = ShapeUtil.rotate(Direction.Axis.Y, 180, ShulkerContainerBlock.TOP_N); + protected static final VoxelShape TOP_E = ShapeUtil.rotate(Direction.Axis.Y, 270, ShulkerContainerBlock.TOP_N); + + protected static final VoxelShape TOP_NW = ShapeUtil.rotate(Direction.Axis.X, 270, ShulkerContainerBlock.BOTTOM_NW); + protected static final VoxelShape TOP_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, ShulkerContainerBlock.TOP_NW); + protected static final VoxelShape TOP_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, ShulkerContainerBlock.TOP_NW); + protected static final VoxelShape TOP_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, ShulkerContainerBlock.TOP_NW); // endregion } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/InstructBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/InstructBlock.java index d04111820e..ef249fa8a5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/InstructBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/InstructBlock.java @@ -8,39 +8,40 @@ import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; public class InstructBlock extends HorizontalDirectionalBlock implements IHammerRemovable { public InstructBlock(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH)); + this.registerDefaultState(this.getStateDefinition().any().setValue(HorizontalDirectionalBlock.FACING, Direction.NORTH)); } @Override protected MapCodec codec() { - return simpleCodec(InstructBlock::new); + return BlockBehaviour.simpleCodec(InstructBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(FACING); + builder.add(HorizontalDirectionalBlock.FACING); } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(HorizontalDirectionalBlock.FACING, rotation.rotate(state.getValue(HorizontalDirectionalBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(HorizontalDirectionalBlock.FACING))); } @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(FACING, context.getHorizontalDirection().getOpposite()); + .setValue(HorizontalDirectionalBlock.FACING, context.getHorizontalDirection().getOpposite()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/ReinforcedConcreteBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/ReinforcedConcreteBlock.java index 4ba3e92cd4..ce54a6f881 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/ReinforcedConcreteBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/ReinforcedConcreteBlock.java @@ -23,17 +23,17 @@ public class ReinforcedConcreteBlock extends Block { public ReinforcedConcreteBlock(Properties properties, Color color) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(HALF, ReinforcedConcreteHalf.SINGLE)); + this.registerDefaultState(this.stateDefinition.any().setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.SINGLE)); this.color = color; } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF); + builder.add(ReinforcedConcreteBlock.HALF); } private boolean checkHalf(BlockState state, ReinforcedConcreteHalf half) { - return state.is(this) && state.getValue(HALF) == half; + return state.is(this) && state.getValue(ReinforcedConcreteBlock.HALF) == half; } /// When piston finished a block movement, this block will receive an NC update where neighborPos is @@ -64,34 +64,34 @@ protected BlockState updateShape( if (level.isClientSide()) { return state; } - if (shouldIgnoreUpdate(pos, neighbourPos)) { + if (ReinforcedConcreteBlock.shouldIgnoreUpdate(pos, neighbourPos)) { return state; } - ReinforcedConcreteHalf half = state.getValue(HALF); + ReinforcedConcreteHalf half = state.getValue(ReinforcedConcreteBlock.HALF); BlockState aboveState = level.getBlockState(pos.above()); BlockState belowState = level.getBlockState(pos.below()); switch (half) { case TOP: if (this.checkHalf(belowState, ReinforcedConcreteHalf.SINGLE)) { - level.setBlock(pos.below(), state.setValue(HALF, ReinforcedConcreteHalf.BOTTOM), 2); + level.setBlock(pos.below(), state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.BOTTOM), 2); } else if (!this.checkHalf(belowState, ReinforcedConcreteHalf.BOTTOM)) { - state = state.setValue(HALF, ReinforcedConcreteHalf.SINGLE); + state = state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.SINGLE); } break; case BOTTOM: if (this.checkHalf(aboveState, ReinforcedConcreteHalf.SINGLE)) { - level.setBlock(pos.above(), state.setValue(HALF, ReinforcedConcreteHalf.TOP), 2); + level.setBlock(pos.above(), state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.TOP), 2); } else if (!this.checkHalf(aboveState, ReinforcedConcreteHalf.TOP)) { - state = state.setValue(HALF, ReinforcedConcreteHalf.SINGLE); + state = state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.SINGLE); } break; case SINGLE: if (neighbourPos.equals(pos.below()) && this.checkHalf(belowState, ReinforcedConcreteHalf.SINGLE)) { - state = state.setValue(HALF, ReinforcedConcreteHalf.TOP); - level.setBlock(pos.below(), state.setValue(HALF, ReinforcedConcreteHalf.BOTTOM), 2); + state = state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.TOP); + level.setBlock(pos.below(), state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.BOTTOM), 2); } else if (neighbourPos.equals(pos.above()) && this.checkHalf(aboveState, ReinforcedConcreteHalf.SINGLE)) { - state = state.setValue(HALF, ReinforcedConcreteHalf.BOTTOM); - level.setBlock(pos.above(), state.setValue(HALF, ReinforcedConcreteHalf.TOP), 2); + state = state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.BOTTOM); + level.setBlock(pos.above(), state.setValue(ReinforcedConcreteBlock.HALF, ReinforcedConcreteHalf.TOP), 2); } break; default: diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalBlock.java index f92fbb6191..9e0f742a4a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalBlock.java @@ -34,7 +34,7 @@ public void randomTick( RandomSource random ) { if (random.nextDouble() <= this.waterAbsorptionChance) { - tryAbsorbWater(level, pos); + this.tryAbsorbWater(level, pos); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalPillarBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalPillarBlock.java index 9ef0c4cd64..e661067b87 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalPillarBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/ember/EmberMetalPillarBlock.java @@ -31,7 +31,7 @@ public void randomTick( RandomSource random ) { if (random.nextDouble() <= 0.1) { - tryAbsorbWater(level, pos); + this.tryAbsorbWater(level, pos); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronBeamBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronBeamBlock.java index 7279b874c4..45f8b4a82a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronBeamBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronBeamBlock.java @@ -30,19 +30,19 @@ public class HeavyIronBeamBlock extends Block implements IHammerRemovable, Hamme public HeavyIronBeamBlock(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(AXIS, Direction.Axis.X)); + this.registerDefaultState(this.getStateDefinition().any().setValue(HeavyIronBeamBlock.AXIS, Direction.Axis.X)); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(AXIS, context.getHorizontalDirection().getOpposite().getAxis()); + .setValue(HeavyIronBeamBlock.AXIS, context.getHorizontalDirection().getOpposite().getAxis()); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(AXIS); + builder.add(HeavyIronBeamBlock.AXIS); } @Override @@ -52,10 +52,10 @@ public VoxelShape getShape( BlockPos blockPos, CollisionContext collisionContext ) { - if (blockState.getValue(AXIS) == Direction.Axis.X) { - return AABB_X; + if (blockState.getValue(HeavyIronBeamBlock.AXIS) == Direction.Axis.X) { + return HeavyIronBeamBlock.AABB_X; } else { - return AABB_Z; + return HeavyIronBeamBlock.AABB_Z; } } @@ -67,9 +67,9 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override protected BlockState rotate(BlockState state, Rotation rotation) { return switch (rotation) { - case COUNTERCLOCKWISE_90, CLOCKWISE_90 -> switch (state.getValue(AXIS)) { - case Z -> state.setValue(AXIS, Direction.Axis.X); - case X -> state.setValue(AXIS, Direction.Axis.Z); + case COUNTERCLOCKWISE_90, CLOCKWISE_90 -> switch (state.getValue(HeavyIronBeamBlock.AXIS)) { + case Z -> state.setValue(HeavyIronBeamBlock.AXIS, Direction.Axis.X); + case X -> state.setValue(HeavyIronBeamBlock.AXIS, Direction.Axis.Z); default -> state; }; default -> state; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronDoorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronDoorBlock.java index 07c60c4c33..fcc3b91758 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronDoorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronDoorBlock.java @@ -35,11 +35,11 @@ public HeavyIronDoorBlock(Properties properties) { boolean flag = level.getBestNeighborSignal(blockpos) >= 15 || level.getBestNeighborSignal(blockpos.above()) >= 15; return this.defaultBlockState() - .setValue(FACING, context.getHorizontalDirection()) - .setValue(HINGE, this.getHinge(context)) - .setValue(POWERED, flag) - .setValue(OPEN, flag) - .setValue(HALF, DoubleBlockHalf.LOWER); + .setValue(DoorBlock.FACING, context.getHorizontalDirection()) + .setValue(DoorBlock.HINGE, this.getHinge(context)) + .setValue(DoorBlock.POWERED, flag) + .setValue(DoorBlock.OPEN, flag) + .setValue(DoorBlock.HALF, DoubleBlockHalf.LOWER); } else { return null; } @@ -56,12 +56,12 @@ protected InteractionResult useItemOn( BlockHitResult hitResult ) { if (stack.getItem() instanceof AnvilHammerItem) { - state = state.cycle(OPEN); + state = state.cycle(DoorBlock.OPEN); level.setBlock(pos, state, 10); level.playSound( null, pos, - state.getValue(OPEN) ? this.type().doorOpen() : this.type().doorClose(), + state.getValue(DoorBlock.OPEN) ? this.type().doorOpen() : this.type().doorClose(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F @@ -87,13 +87,13 @@ protected void neighborChanged( boolean movedByPiston ) { boolean flag = level.getBestNeighborSignal(pos) >= 15 - || level.getBestNeighborSignal(pos.relative(state.getValue(HALF) == DoubleBlockHalf.LOWER + || level.getBestNeighborSignal(pos.relative(state.getValue(DoorBlock.HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN ) ) >= 15; - if (!this.defaultBlockState().is(block) && flag != state.getValue(POWERED)) { - if (flag != state.getValue(OPEN)) { + if (!this.defaultBlockState().is(block) && flag != state.getValue(DoorBlock.POWERED)) { + if (flag != state.getValue(DoorBlock.OPEN)) { level.playSound( null, pos, @@ -107,8 +107,8 @@ protected void neighborChanged( level.setBlock( pos, - state.setValue(POWERED, flag) - .setValue(OPEN, flag), + state.setValue(DoorBlock.POWERED, flag) + .setValue(DoorBlock.OPEN, flag), 2 ); } @@ -116,12 +116,12 @@ protected void neighborChanged( @Override public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilHammer) { - BlockState state = level.getBlockState(pos).cycle(OPEN); + BlockState state = level.getBlockState(pos).cycle(DoorBlock.OPEN); level.setBlock(pos, state, 10); level.playSound( null, pos, - state.getValue(OPEN) ? this.type().doorOpen() : this.type().doorClose(), + state.getValue(DoorBlock.OPEN) ? this.type().doorOpen() : this.type().doorClose(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F @@ -132,6 +132,6 @@ public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilH @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return DoorBlock.FACING; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronPlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronPlateBlock.java index 6af7863f92..25d3a449a0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronPlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronPlateBlock.java @@ -23,6 +23,6 @@ public VoxelShape getShape( BlockPos blockPos, CollisionContext collisionContext ) { - return AABB; + return HeavyIronPlateBlock.AABB; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronTrapdoorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronTrapdoorBlock.java index c25dd3eaa2..37c78faa4b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronTrapdoorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/decoration/heavyiron/HeavyIronTrapdoorBlock.java @@ -10,6 +10,7 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.TrapDoorBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockSetType; @@ -34,7 +35,7 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState bs = super.getStateForPlacement(context); if (bs.isEmpty()) return bs; boolean hasSignal = context.getLevel().getBestNeighborSignal(context.getClickedPos()) >= 15; - return bs.setValue(POWERED, hasSignal).setValue(OPEN, hasSignal); + return bs.setValue(TrapDoorBlock.POWERED, hasSignal).setValue(TrapDoorBlock.OPEN, hasSignal); } @Override @@ -49,7 +50,7 @@ protected InteractionResult useItemOn( ) { if (stack.getItem() instanceof AnvilHammerItem) { this.toggle(state, level, pos, player); - this.playSound(null, level, pos, state.getValue(OPEN)); + this.playSound(null, level, pos, state.getValue(TrapDoorBlock.OPEN)); return InteractionResult.SUCCESS; } return InteractionResult.FAIL; @@ -65,14 +66,14 @@ protected void neighborChanged( boolean movedByPiston ) { boolean flag = level.getBestNeighborSignal(pos) >= 15; - if (flag != state.getValue(POWERED)) { - if (state.getValue(OPEN) != flag) { - state = state.setValue(OPEN, flag); + if (flag != state.getValue(TrapDoorBlock.POWERED)) { + if (state.getValue(TrapDoorBlock.OPEN) != flag) { + state = state.setValue(TrapDoorBlock.OPEN, flag); this.playSound(null, level, pos, flag); } - level.setBlock(pos, state.setValue(POWERED, flag), 2); - if (state.getValue(WATERLOGGED)) { + level.setBlock(pos, state.setValue(TrapDoorBlock.POWERED, flag), 2); + if (state.getValue(TrapDoorBlock.WATERLOGGED)) { level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); } } @@ -82,12 +83,12 @@ protected void neighborChanged( public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilHammer) { BlockState state = level.getBlockState(pos); this.toggle(state, level, pos, player); - this.playSound(null, level, pos, !state.getValue(OPEN)); + this.playSound(null, level, pos, !state.getValue(TrapDoorBlock.OPEN)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState state) { - return FACING; + return HorizontalDirectionalBlock.FACING; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/AbstractTransmissionPoleBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/AbstractTransmissionPoleBlockEntity.java index 6e0cff10e6..c2ed8a2e67 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/AbstractTransmissionPoleBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/AbstractTransmissionPoleBlockEntity.java @@ -24,7 +24,7 @@ public AbstractTransmissionPoleBlockEntity(BlockEntityType type, BlockPos pos } @Override - public Level getCurrentLevel() { + public @Nullable Level getCurrentLevel() { return this.getLevel(); } @@ -48,7 +48,9 @@ public PowerComponentType getComponentType() { @Override public void tick() { - BlockState state = this.getLevel().getBlockState(this.getPos()); + Level level = this.getLevel(); + if (level == null) return; + BlockState state = level.getBlockState(this.getPos()); if (!this.getType().isValid(state)) return; if (!this.isHead(state)) return; @@ -57,6 +59,6 @@ public void tick() { } else if (state.getValue(IPowerComponent.SWITCH) == Switch.ON && this.getGrid() == null) { PowerGrid.addComponent(this); } - this.flushState(this.getLevel(), this.getPos()); + this.flushState(level, this.getPos()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/AccelerationRingBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/AccelerationRingBlockEntity.java index 332b2ee118..b2f25eae6e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/AccelerationRingBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/AccelerationRingBlockEntity.java @@ -43,7 +43,7 @@ public class AccelerationRingBlockEntity extends BlockEntity implements IPowerCo private static final HashMap LEVEL_ACCELERATION_INDEX = new HashMap<>(); @Getter @Setter - private PowerGrid grid; + private @Nullable PowerGrid grid; public AccelerationRingBlockEntity(BlockPos pos, BlockState blockState) { super(ModBlockEntities.ACCELERATION_RING.get(), pos, blockState); @@ -58,57 +58,59 @@ public static AccelerationRingBlockEntity createBlockEntity(BlockEntityType t } public static Iterable getAllBlocks(Level level) { - AccelerationIndex index = LEVEL_ACCELERATION_INDEX.get(level); + AccelerationIndex index = AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.get(level); return index == null ? List.of() : index.positions; } - public static AABB getAABB(Level level, BlockPos pos) { - AccelerationIndex index = LEVEL_ACCELERATION_INDEX.get(level); + public static @Nullable AABB getAABB(Level level, BlockPos pos) { + AccelerationIndex index = AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.get(level); return index == null ? null : index.areas.get(pos); } public static Iterable getBlocksAt(Level level, Vec3 pos) { - AccelerationIndex index = LEVEL_ACCELERATION_INDEX.get(level); + AccelerationIndex index = AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.get(level); return index == null ? List.of() : index.getBlocksAt(pos); } public static Iterable getBlocksAlongMovement(Level level, Vec3 start, Vec3 movement) { - AccelerationIndex index = LEVEL_ACCELERATION_INDEX.get(level); + AccelerationIndex index = AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.get(level); return index == null ? List.of() : index.getBlocksAlongMovement(start, movement); } public static Iterable getRingsAlongMovement(Level level, Vec3 start, Vec3 movement) { - AccelerationIndex index = LEVEL_ACCELERATION_INDEX.get(level); + AccelerationIndex index = AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.get(level); return index == null ? List.of() : index.getRingsAlongMovement(start, movement); } public static void clear(Level level) { - LEVEL_ACCELERATION_INDEX.remove(level); + AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.remove(level); } private void addSelfToMap() { - if (level == null) return; - LEVEL_ACCELERATION_INDEX.computeIfAbsent(level, ignored -> new AccelerationIndex()).add(getBlockPos()); + if (this.level == null) return; + AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX + .computeIfAbsent(this.level, ignored -> new AccelerationIndex()) + .add(this.getBlockPos()); } private void removeSelfFromMap() { - if (level == null) return; - AccelerationIndex index = LEVEL_ACCELERATION_INDEX.get(level); + if (this.level == null) return; + AccelerationIndex index = AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.get(this.level); if (index == null) return; - index.remove(getBlockPos()); - if (index.positions.isEmpty()) LEVEL_ACCELERATION_INDEX.remove(level); + index.remove(this.getBlockPos()); + if (index.positions.isEmpty()) AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.remove(this.level); } private void removeAccelerationArea() { - if (level == null) return; - AccelerationIndex index = LEVEL_ACCELERATION_INDEX.get(level); - if (index != null) index.removeArea(getBlockPos()); + if (this.level == null) return; + AccelerationIndex index = AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.get(this.level); + if (index != null) index.removeArea(this.getBlockPos()); } private void updateAccelerationArea(AABB area) { - if (level == null) return; - LEVEL_ACCELERATION_INDEX.computeIfAbsent(level, ignored -> new AccelerationIndex()) - .updateArea(getBlockPos(), area); + if (this.level == null) return; + AccelerationRingBlockEntity.LEVEL_ACCELERATION_INDEX.computeIfAbsent(this.level, ignored -> new AccelerationIndex()) + .updateArea(this.getBlockPos(), area); } @Override @@ -118,16 +120,16 @@ private void updateAccelerationArea(AABB area) { @Override public BlockPos getPos() { - return getBlockPos(); + return this.getBlockPos(); } @Override public PowerComponentType getComponentType() { if (this.level == null) return PowerComponentType.INVALID; - if (!this.level.getBlockState(getBlockPos()).hasProperty(AccelerationRingBlock.HALF)) { + if (!this.level.getBlockState(this.getBlockPos()).hasProperty(AccelerationRingBlock.HALF)) { return PowerComponentType.INVALID; } - if (this.level.getBlockState(getBlockPos()).getValue(AccelerationRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) { + if (this.level.getBlockState(this.getBlockPos()).getValue(AccelerationRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) { return PowerComponentType.CONSUMER; } else { return PowerComponentType.INVALID; @@ -140,13 +142,13 @@ public int getRange() { } public boolean isWork() { - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); return state.getValue(AccelerationRingBlock.SWITCH) == Switch.ON && !state.getValue(AccelerationRingBlock.OVERLOAD); } public void tick() { if (this.level == null) return; - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); if (this.level.isClientSide()) { if (!state.getValue(AccelerationRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) return; if (this.isWork()) { @@ -158,9 +160,9 @@ public void tick() { if (!state.getValue(AccelerationRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) return; if (!(state.getBlock() instanceof AccelerationRingBlock block)) return; if (this.grid.isWorking() && state.getValue(AccelerationRingBlock.OVERLOAD)) { - block.updateState(this.level, getBlockPos(), AccelerationRingBlock.OVERLOAD, false, 3); + block.updateState(this.level, this.getBlockPos(), AccelerationRingBlock.OVERLOAD, false, 3); } else if (!this.grid.isWorking() && !state.getValue(AccelerationRingBlock.OVERLOAD)) { - block.updateState(this.level, getBlockPos(), AccelerationRingBlock.OVERLOAD, true, 3); + block.updateState(this.level, this.getBlockPos(), AccelerationRingBlock.OVERLOAD, true, 3); } if (!this.isWork()) { this.removeSelfFromMap(); @@ -175,17 +177,17 @@ public void tick() { public void accelerate() { assert this.level != null; - Direction direction = getBlockState().getValue(AccelerationRingBlock.FACING); + Direction direction = this.getBlockState().getValue(AccelerationRingBlock.FACING); BlockPos.MutableBlockPos checkPos = new BlockPos.MutableBlockPos(); BlockPos endRingPos = null; ArrayList blockPositions = null; - checkPos.set(getBlockPos()); + checkPos.set(this.getBlockPos()); boolean found = false; checkPos.move(direction); for (int i = 0; i < 14; i++) { checkPos.move(direction); BlockState checkState = this.level.getBlockState(checkPos); - if (!level.isClientSide() && checkState.is(BlockTags.ANVIL) && !checkState.is(ModBlockTags.NON_MAGNETIC)) { + if (!this.level.isClientSide() && checkState.is(BlockTags.ANVIL) && !checkState.is(ModBlockTags.NON_MAGNETIC)) { if (blockPositions == null) blockPositions = new ArrayList<>(); blockPositions.add(checkPos.immutable()); } @@ -205,19 +207,19 @@ public void accelerate() { this.removeAccelerationArea(); return; } - BlockPos aabbStart = getBlockPos().relative(direction.getOpposite(), 1); - BlockState deflectionCheck = level.getBlockState(getBlockPos().relative(direction.getOpposite(), 3)); + BlockPos aabbStart = this.getBlockPos().relative(direction.getOpposite(), 1); + BlockState deflectionCheck = this.level.getBlockState(this.getBlockPos().relative(direction.getOpposite(), 3)); if ( deflectionCheck.hasProperty(DeflectionRingBlock.HALF) && deflectionCheck.getValue(DeflectionRingBlock.HALF) == DirectionCube3x3PartHalf.MID_CENTER && deflectionCheck.getValue(DeflectionRingBlock.SWITCH) == IPowerComponent.Switch.ON && !deflectionCheck.getValue(DeflectionRingBlock.OVERLOAD) ) { - aabbStart = getBlockPos().relative(direction.getOpposite(), 2); + aabbStart = this.getBlockPos().relative(direction.getOpposite(), 2); } AABB aabb = AABB.encapsulatingFullBlocks(endRingPos.relative(direction), aabbStart); this.updateAccelerationArea(aabb); - if (level.isClientSide() || blockPositions == null) return; + if (this.level.isClientSide() || blockPositions == null) return; for (BlockPos pos : blockPositions) { BlockState fallState = this.level.getBlockState(pos); this.level.setBlock(pos, Blocks.AIR.defaultBlockState(), 2); @@ -232,14 +234,14 @@ public void accelerate() { public void attractGianAnvil() { assert this.level != null; if ( - this.level.getBlockState(getBlockPos().below(2)).hasProperty(GiantAnvilBlock.HALF) - && this.level.getBlockState(getBlockPos().below(2)).getValue(GiantAnvilBlock.HALF) == Cube3x3PartHalf.TOP_CENTER + this.level.getBlockState(this.getBlockPos().below(2)).hasProperty(GiantAnvilBlock.HALF) + && this.level.getBlockState(this.getBlockPos().below(2)).getValue(GiantAnvilBlock.HALF) == Cube3x3PartHalf.TOP_CENTER ) { return; } BlockPos giantAnvilPos = null; BlockPos.MutableBlockPos checkPos = new BlockPos.MutableBlockPos(); - checkPos.set(getBlockPos().below(2)); + checkPos.set(this.getBlockPos().below(2)); for (int y = 0; y < 11; y++) { BlockState checkState = this.level.getBlockState(checkPos); if (!checkState.hasProperty(GiantAnvilBlock.HALF)) { @@ -253,18 +255,18 @@ public void attractGianAnvil() { } checkPos.move(Direction.DOWN); } - Vec3 ringCenter = getBlockPos().getCenter(); + Vec3 ringCenter = this.getBlockPos().getCenter(); FallingGiantAnvilEntity fallingGiantAnvilEntity = null; double nearestDistanceSqr = Double.POSITIVE_INFINITY; for (FallingGiantAnvilEntity entity : this.level.getEntitiesOfClass( FallingGiantAnvilEntity.class, new AABB( - getBlockPos().getX(), - getBlockPos().getY() - 2, - getBlockPos().getZ(), - getBlockPos().getX() + 1, - getBlockPos().getY() - 12, - getBlockPos().getZ() + 1 + this.getBlockPos().getX(), + this.getBlockPos().getY() - 2, + this.getBlockPos().getZ(), + this.getBlockPos().getX() + 1, + this.getBlockPos().getY() - 12, + this.getBlockPos().getZ() + 1 ) )) { double offsetX = entity.getX() - ringCenter.x; @@ -290,7 +292,7 @@ public void attractGianAnvil() { } checkPos.set(giantAnvilPos); checkPos.move(-1, 2, -1); - while (checkPos.getY() < getBlockPos().getY() - 1) { + while (checkPos.getY() < this.getBlockPos().getY() - 1) { for (int x = -1; x < 2; x++) { for (int z = -1; z < 2; z++) { BlockState checked = this.level.getBlockState(checkPos); @@ -306,9 +308,9 @@ public void attractGianAnvil() { } Block block = this.level.getBlockState(giantAnvilPos.below()).getBlock(); if (block instanceof GiantAnvilBlock giantAnvilBlock) { - giantAnvilBlock.removePartsAndUpdate(level, giantAnvilPos.below()); + giantAnvilBlock.removePartsAndUpdate(this.level, giantAnvilPos.below()); } - BlockPos newPos = getBlockPos().below(4); + BlockPos newPos = this.getBlockPos().below(4); for (Cube3x3PartHalf part : Cube3x3PartHalf.values()) { this.level.setBlockAndUpdate( newPos.offset(part.getOffset()), ModBlocks.GIANT_ANVIL.getDefaultState() @@ -321,7 +323,7 @@ public void attractGianAnvil() { @Override public int getInputPower() { - return getBlockState().getValue(AccelerationRingBlock.SWITCH) == Switch.ON ? 256 : 0; + return this.getBlockState().getValue(AccelerationRingBlock.SWITCH) == Switch.ON ? 256 : 0; } @Override @@ -347,8 +349,8 @@ private void add(BlockPos pos) { private void remove(BlockPos pos) { if (this.positions.remove(pos)) { long sectionKey = SectionPos.asLong(pos); - HashSet sectionPositions = this.ringsBySection.get(sectionKey); - if (sectionPositions != null) { + if (this.ringsBySection.containsKey(sectionKey)) { + HashSet sectionPositions = this.ringsBySection.get(sectionKey); sectionPositions.remove(pos); if (sectionPositions.isEmpty()) this.ringsBySection.remove(sectionKey); } @@ -391,28 +393,28 @@ private void removeArea(BlockPos pos) { if (sections == null) return; for (int i = 0; i < sections.size(); i++) { long sectionKey = sections.getLong(i); + if (!this.bySection.containsKey(sectionKey)) continue; HashSet sectionPositions = this.bySection.get(sectionKey); - if (sectionPositions == null) continue; sectionPositions.remove(pos); if (sectionPositions.isEmpty()) this.bySection.remove(sectionKey); } } private Iterable getBlocksAt(Vec3 pos) { - HashSet sectionPositions = this.bySection.get(SectionPos.asLong( + long sectionKey = SectionPos.asLong( SectionPos.blockToSectionCoord(pos.x), SectionPos.blockToSectionCoord(pos.y), SectionPos.blockToSectionCoord(pos.z) - )); - return sectionPositions == null ? List.of() : sectionPositions; + ); + return this.bySection.containsKey(sectionKey) ? this.bySection.get(sectionKey) : List.of(); } private Iterable getBlocksAlongMovement(Vec3 start, Vec3 movement) { - return getPositionsAlongMovement(start, movement, this.bySection); + return AccelerationIndex.getPositionsAlongMovement(start, movement, this.bySection); } private Iterable getRingsAlongMovement(Vec3 start, Vec3 movement) { - return getPositionsAlongMovement(start, movement, this.ringsBySection); + return AccelerationIndex.getPositionsAlongMovement(start, movement, this.ringsBySection); } private static Iterable getPositionsAlongMovement( @@ -430,10 +432,8 @@ private static Iterable getPositionsAlongMovement( int endSectionY = SectionPos.blockToSectionCoord(end.y); int endSectionZ = SectionPos.blockToSectionCoord(end.z); if (sectionX == endSectionX && sectionY == endSectionY && sectionZ == endSectionZ) { - HashSet sectionPositions = sectionIndex.get( - SectionPos.asLong(sectionX, sectionY, sectionZ) - ); - return sectionPositions == null ? List.of() : sectionPositions; + long sectionKey = SectionPos.asLong(sectionX, sectionY, sectionZ); + return sectionIndex.containsKey(sectionKey) ? sectionIndex.get(sectionKey) : List.of(); } int stepX = Double.compare(movement.x, 0.0); @@ -466,10 +466,8 @@ private static Iterable getPositionsAlongMovement( + 1; HashSet candidates = new HashSet<>(); while (remainingSections-- > 0) { - HashSet sectionPositions = sectionIndex.get( - SectionPos.asLong(sectionX, sectionY, sectionZ) - ); - if (sectionPositions != null) candidates.addAll(sectionPositions); + long sectionKey = SectionPos.asLong(sectionX, sectionY, sectionZ); + if (sectionIndex.containsKey(sectionKey)) candidates.addAll(sectionIndex.get(sectionKey)); if (sectionX == endSectionX && sectionY == endSectionY && sectionZ == endSectionZ) break; if (nextSectionProgressX <= nextSectionProgressY diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ActiveSilencerBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ActiveSilencerBlockEntity.java index 7b2a85a083..e6052b56bf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ActiveSilencerBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ActiveSilencerBlockEntity.java @@ -96,7 +96,10 @@ public CompoundTag getUpdateTag(HolderLookup.Provider provider) { @Override public void setRemoved() { super.setRemoved(); - DistExecutor.run(Dist.CLIENT, () -> () -> SoundHelper.INSTANCE.unregister(this.level, this)); + Level level = this.level; + if (level != null) { + DistExecutor.run(Dist.CLIENT, () -> () -> SoundHelper.INSTANCE.unregister(level, this)); + } } @Override @@ -130,7 +133,7 @@ public void removeSound(Identifier soundId) { @Override public boolean shouldMute(Identifier sound, Vec3 pos) { - if (getBlockState().getValue(ActiveSilencerBlock.POWERED)) return false; + if (this.getBlockState().getValue(ActiveSilencerBlock.POWERED)) return false; boolean inRange = this.range.contains(pos); boolean inList = this.muting.contains(sound); return inRange && inList; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/AdvancedComparatorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/AdvancedComparatorBlockEntity.java index 3138ae77e9..059e5a809e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/AdvancedComparatorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/AdvancedComparatorBlockEntity.java @@ -172,7 +172,7 @@ public byte index() { } public static Mode fromIndex(int index) { - return values()[index]; + return Mode.values()[index]; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseChuteBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseChuteBlockEntity.java index bff7e9b41f..6c874559b2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseChuteBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseChuteBlockEntity.java @@ -74,7 +74,7 @@ private static final class TrackedEjectedItem { private TrackedEjectedItem(ItemEntity item) { this.item = item; this.wasOnGround = item.onGround(); - this.ticksLeft = EJECTED_ITEM_TRACK_TICKS; + this.ticksLeft = BaseChuteBlockEntity.EJECTED_ITEM_TRACK_TICKS; } } @@ -218,7 +218,7 @@ public void tick() { } // 尝试从上方容器输入 if (this.inventoryFull()) { - this.level.updateNeighbourForOutputSignal(getBlockPos(), getBlockState().getBlock()); + this.level.updateNeighbourForOutputSignal(this.getBlockPos(), this.getBlockState().getBlock()); if (resetCD) this.cooldown = AnvilCraft.CONFIG.chuteMaxCooldown; return; } @@ -253,7 +253,7 @@ public void tick() { resetCD = true; } } - this.level.updateNeighbourForOutputSignal(getBlockPos(), getBlockState().getBlock()); + this.level.updateNeighbourForOutputSignal(this.getBlockPos(), this.getBlockState().getBlock()); if (resetCD) this.cooldown = AnvilCraft.CONFIG.chuteMaxCooldown; } @@ -398,6 +398,8 @@ public void onDataPacket(Connection net, ValueInput input) { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); - Containers.dropContents(this.level, pos, this.itemHandler.getStacks()); + if (this.level != null) { + Containers.dropContents(this.level, pos, this.itemHandler.getStacks()); + } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseLaserBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseLaserBlockEntity.java index b9b216e2ca..21ee333018 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseLaserBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/BaseLaserBlockEntity.java @@ -13,6 +13,7 @@ import dev.dubhe.anvilcraft.network.LaserEmitPacket; import dev.dubhe.anvilcraft.util.BlockMiningEffect; import dev.dubhe.anvilcraft.util.BreakBlockUtil; +import dev.dubhe.anvilcraft.util.EntityUtil; import lombok.Getter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -71,8 +72,8 @@ public BaseLaserBlockEntity(BlockEntityType type, BlockPos pos, BlockState bl } protected boolean canPassThrough(Direction direction, BlockPos blockPos) { - if (level == null) return false; - BlockState blockState = level.getBlockState(blockPos); + if (this.level == null) return false; + BlockState blockState = this.level.getBlockState(blockPos); if (blockState.is(ModBlockTags.LASER_CAN_PASS_THROUGH) || blockState.is(Tags.Blocks.GLASS_BLOCKS) || blockState.is(Tags.Blocks.GLASS_PANES) @@ -89,7 +90,7 @@ protected boolean canPassThrough(Direction direction, BlockPos blockPos) { case Y -> Block.box(7, 0, 7, 9, 16, 9).bounds(); case Z -> Block.box(7, 7, 0, 9, 9, 16).bounds(); }; - return blockState.getCollisionShape(level, blockPos).toAabbs().stream().noneMatch(laseBoundingBox::intersects); + return blockState.getCollisionShape(this.level, blockPos).toAabbs().stream().noneMatch(laseBoundingBox::intersects); } public void updateIrradiateBlockPos(@Nullable BlockPos newPos) { @@ -102,7 +103,7 @@ public void updateIrradiateBlockPos(@Nullable BlockPos newPos) { this.irradiateBlockPos = newPos; return; } - if (!this.irradiateBlockPos.equals(newPos)) this.markChanged(); + if (!Objects.equals(this.irradiateBlockPos, newPos)) this.markChanged(); this.irradiateBlockPos = newPos; } @@ -152,7 +153,7 @@ public BlockMiningEffect getMiningEffect() { public void syncTo(ServerPlayer player) { PacketDistributor.sendToPlayer( player, - new LaserEmitPacket(getLaserLevel(), getBlockPos(), this.irradiateBlockPos, false) + new LaserEmitPacket(this.getLaserLevel(), this.getBlockPos(), this.irradiateBlockPos, false) ); } @@ -161,15 +162,15 @@ public void tick(Level level) { if (level instanceof ServerLevel serverLevel) { PacketDistributor.sendToPlayersTrackingChunk( serverLevel, - level.getChunkAt(getBlockPos()).getPos(), - new LaserEmitPacket(getLaserLevel(), getBlockPos(), this.irradiateBlockPos, false) + level.getChunkAt(this.getBlockPos()).getPos(), + new LaserEmitPacket(this.getLaserLevel(), this.getBlockPos(), this.irradiateBlockPos, false) ); } } if ( level instanceof ServerLevel serverLevel - && getIrradiateBlockPos() != null - && serverLevel.getBlockState(getIrradiateBlockPos()).is(ModBlockTags.HEATABLE_BLOCKS) + && this.getIrradiateBlockPos() != null + && serverLevel.getBlockState(this.getIrradiateBlockPos()).is(ModBlockTags.HEATABLE_BLOCKS) ) { HeaterManager.addProducer(this.getBlockPos(), serverLevel, ModHeaterInfos.LASER_EMITTER); } @@ -178,7 +179,8 @@ && getIrradiateBlockPos() != null /// 发射激光 public void emitLaser(Direction direction) { - if (this.level == null) return; + Level level = this.level; + if (level == null) return; BlockPos tempIrradiateBlockPos = this.getIrradiateBlockPos(this.maxTransmissionDistance, direction, this.getBlockPos()); if (this.getBlockState().getBlock() instanceof FlexibleMultiPartBlock) { tempIrradiateBlockPos = this.getIrradiateBlockPos( @@ -188,16 +190,17 @@ public void emitLaser(Direction direction) { ); } BaseLaserBlockEntity newLaserTarget = - this.level.getBlockEntity(tempIrradiateBlockPos) instanceof BaseLaserBlockEntity target ? target : null; - boolean targetChanged = !tempIrradiateBlockPos.equals(this.irradiateBlockPos); + level.getBlockEntity(tempIrradiateBlockPos) instanceof BaseLaserBlockEntity target ? target : null; + BlockPos previousIrradiateBlockPos = this.irradiateBlockPos; + boolean targetChanged = !Objects.equals(tempIrradiateBlockPos, previousIrradiateBlockPos); boolean targetEntityChanged = newLaserTarget != this.irradiatedLaserTarget; boolean targetRevisionChanged = newLaserTarget != null && newLaserTarget.laserLinkRevision != this.irradiatedLaserTargetRevision; if (targetChanged || targetEntityChanged || targetRevisionChanged) { if (this.irradiatedLaserTarget != null) { this.irradiatedLaserTarget.onCancelingIrradiation(this); - } else if (targetChanged && this.irradiateBlockPos != null) { - BlockEntity oldBlockEntity = this.level.getBlockEntity(this.irradiateBlockPos); + } else if (targetChanged && previousIrradiateBlockPos != null) { + BlockEntity oldBlockEntity = level.getBlockEntity(previousIrradiateBlockPos); if (oldBlockEntity instanceof BaseLaserBlockEntity lastIrradiatedLaserBlockEntity) { lastIrradiatedLaserBlockEntity.onCancelingIrradiation(this); } @@ -218,7 +221,7 @@ public void emitLaser(Direction direction) { || laserLevelChanged || miningEffectChanged; if (needsIrradiationUpdate && !newLaserTarget.getIgnoreFace().contains(direction)) { - this.level.updateNeighborsAt(tempIrradiateBlockPos, getBlockState().getBlock()); + level.updateNeighborsAt(tempIrradiateBlockPos, this.getBlockState().getBlock()); newLaserTarget.onIrradiated(this); this.irradiatedLaserTarget = newLaserTarget; this.irradiatedLaserTargetRevision = newLaserTarget.laserLinkRevision; @@ -227,7 +230,7 @@ public void emitLaser(Direction direction) { this.lastEmittedMiningEffect = miningEffect; this.updateIrradiateBlockPos(tempIrradiateBlockPos); - if (!(this.level instanceof ServerLevel serverLevel)) return; + if (!(level instanceof ServerLevel serverLevel)) return; int hurt = Math.min(16, this.laserLevel - 4); if (hurt > 0) { Vec3 startPos = this.getBlockPos().relative(direction).getCenter().add(-0.0625, -0.0625, -0.0625); @@ -236,53 +239,52 @@ public void emitLaser(Direction direction) { } AABB trackBoundingBox = new AABB( startPos, - Objects.requireNonNull(this.irradiateBlockPos).relative(direction.getOpposite()) + tempIrradiateBlockPos.relative(direction.getOpposite()) .getCenter() .add(0.0625, 0.0625, 0.0625) ); - // noinspection deprecation - this.level.getEntities( + level.getEntities( EntityTypeTest.forClass(LivingEntity.class), trackBoundingBox, Entity::isAlive ).forEach(livingEntity -> - livingEntity.hurtOrSimulate( - ModDamageTypes.laser(this.level), + EntityUtil.hurtOrSimulate( + livingEntity, + ModDamageTypes.laser(level), hurt ) ); } - BlockState irradiateBlock = this.level.getBlockState(Objects.requireNonNull(this.irradiateBlockPos)); - int cooldown = COOLDOWNS[Math.clamp(this.laserLevel / 4, 0, 4)]; + BlockState irradiateBlock = level.getBlockState(tempIrradiateBlockPos); + int cooldown = BaseLaserBlockEntity.COOLDOWNS[Math.clamp(this.laserLevel / 4, 0, 4)]; if (this.tickCount >= cooldown) { this.tickCount = 0; if (irradiateBlock.is(Tags.Blocks.ORES)) { List drops = BreakBlockUtil.dropForLaser( serverLevel, - this.irradiateBlockPos, + tempIrradiateBlockPos, this.getMiningEffect() ); - this.deliverItem(drops, direction, this.irradiateBlockPos); + this.deliverItem(drops, direction, tempIrradiateBlockPos); } } } public void deliverItem(List drops, Direction direction, BlockPos sourceBlockPos) { - if (this.level == null) return; - Vec3 dropPos = getBlockPos().relative(direction.getOpposite()).getCenter(); - BlockPos downStreamPos = getBlockPos().relative(this.getFacing().getOpposite()); + Level level = this.level; + if (level == null) return; + Vec3 dropPos = this.getBlockPos().relative(direction.getOpposite()).getCenter(); + BlockPos downStreamPos = this.getBlockPos().relative(this.getFacing().getOpposite()); if (this.getBlockState().getBlock() instanceof FlexibleMultiPartBlock) { dropPos = this.getBlockPos().relative(direction.getOpposite(), 2).getCenter(); downStreamPos = this.getBlockPos().relative(this.getFacing().getOpposite(), 2); } - if (getLevel() == null) return; - ResourceHandler cap = getLevel() - .getCapability( - Capabilities.Item.BLOCK, - downStreamPos, - this.getFacing() - ); - BlockState sourceBlock = this.level.getBlockState(sourceBlockPos); + ResourceHandler cap = level.getCapability( + Capabilities.Item.BLOCK, + downStreamPos, + this.getFacing() + ); + BlockState sourceBlock = level.getBlockState(sourceBlockPos); BlockPos finalDropStreamPos = downStreamPos; Vec3 finalDropPos = dropPos; drops.forEach(itemStack -> { @@ -291,8 +293,8 @@ public void deliverItem(List drops, Direction direction, BlockPos sou if (outItemStack.isEmpty()) { ItemHandlerUtil.insertItem(cap, itemStack, false); } else { - this.level.addFreshEntity(new ItemEntity( - this.level, + level.addFreshEntity(new ItemEntity( + level, finalDropPos.x, finalDropPos.y, finalDropPos.z, @@ -300,21 +302,21 @@ public void deliverItem(List drops, Direction direction, BlockPos sou )); } } else if ( - this.level.getBlockEntity(finalDropStreamPos) instanceof BaseLaserBlockEntity downStreamBlockEntity + level.getBlockEntity(finalDropStreamPos) instanceof BaseLaserBlockEntity downStreamBlockEntity && downStreamBlockEntity.getFacing() == direction ) { downStreamBlockEntity.deliverItem(drops, direction, sourceBlockPos); - } else this.level.addFreshEntity(new ItemEntity(this.level, finalDropPos.x, finalDropPos.y, finalDropPos.z, itemStack)); + } else level.addFreshEntity(new ItemEntity(level, finalDropPos.x, finalDropPos.y, finalDropPos.z, itemStack)); }); - if (this.level.getBlockEntity(downStreamPos) instanceof BaseLaserBlockEntity) return; + if (level.getBlockEntity(downStreamPos) instanceof BaseLaserBlockEntity) return; if (sourceBlock.is(Blocks.ANCIENT_DEBRIS)) { - this.level.setBlockAndUpdate(sourceBlockPos, Blocks.NETHERRACK.defaultBlockState()); + level.setBlockAndUpdate(sourceBlockPos, Blocks.NETHERRACK.defaultBlockState()); } else if (sourceBlock.is(Tags.Blocks.ORES_IN_GROUND_DEEPSLATE)) { - this.level.setBlockAndUpdate(sourceBlockPos, Blocks.DEEPSLATE.defaultBlockState()); + level.setBlockAndUpdate(sourceBlockPos, Blocks.DEEPSLATE.defaultBlockState()); } else if (sourceBlock.is(Tags.Blocks.ORES_IN_GROUND_NETHERRACK)) { - this.level.setBlockAndUpdate(sourceBlockPos, Blocks.NETHERRACK.defaultBlockState()); + level.setBlockAndUpdate(sourceBlockPos, Blocks.NETHERRACK.defaultBlockState()); } else { - this.level.setBlockAndUpdate(sourceBlockPos, Blocks.STONE.defaultBlockState()); + level.setBlockAndUpdate(sourceBlockPos, Blocks.STONE.defaultBlockState()); } /* else { if (this.level.getBlockState(sourceBlockPos).getBlock().defaultDestroyTime() >= 0 @@ -359,9 +361,9 @@ public void onCancelingIrradiation(BaseLaserBlockEntity baseLaserBlockEntity) { if (!this.irradiateSelfLaserBlockSet.isEmpty()) return; BlockPos tempIrradiateBlockPos = this.irradiateBlockPos; this.updateIrradiateBlockPos(null); - if (level == null) return; + if (this.level == null) return; if (tempIrradiateBlockPos == null) return; - if (!(level.getBlockEntity(tempIrradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity)) return; + if (!(this.level.getBlockEntity(tempIrradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity)) return; irradiateBlockEntity.onCancelingIrradiation(this); } @@ -389,16 +391,16 @@ public void resetLaserStateAfterMove() { @Override public void setRemoved() { super.setRemoved(); - if (level == null) return; + if (this.level == null) return; - if (level.isClientSide()) { + if (this.level.isClientSide()) { Objects.requireNonNull(CachedBlockEntityRenderingPipeline.getInstance()).blockRemoved(this); return; } if (this.irradiateBlockPos == null) return; - if (!level.isLoaded(this.irradiateBlockPos)) return; - if (!(level.getBlockEntity(this.irradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity)) return; + if (!this.level.isLoaded(this.irradiateBlockPos)) return; + if (!(this.level.getBlockEntity(this.irradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity)) return; irradiateBlockEntity.onCancelingIrradiation(this); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/BurningHeaterBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/BurningHeaterBlockEntity.java index e66c08cdd5..5fb00d7c73 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/BurningHeaterBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/BurningHeaterBlockEntity.java @@ -47,12 +47,12 @@ public class BurningHeaterBlockEntity extends BlockEntity implements IItemResour private final ItemStacksResourceHandler itemHandler = new ItemStacksResourceHandler(1) { @Override public void onContentsChanged(int index, ItemStack previousContents) { - setChanged(); + BurningHeaterBlockEntity.this.setChanged(); } @Override public boolean isValid(int index, ItemResource resource) { - return getItemBurnTime(resource.toStack()) > 0 || resource.toStack().is(Items.BUCKET); + return BurningHeaterBlockEntity.getItemBurnTime(resource.toStack()) > 0 || resource.toStack().is(Items.BUCKET); } }; @@ -71,9 +71,9 @@ public static BurningHeaterBlockEntity createBlockEntity( * 客户端上根据上次同步时间进行本地倒计时估算,避免频繁网络同步。 */ public int getDisplayBurnTime() { - if (level == null || !level.isClientSide()) return this.burnTime; + if (this.level == null || !this.level.isClientSide()) return this.burnTime; if (this.lastSyncGameTime <= 0) return this.burnTime; - long elapsed = level.getGameTime() - this.lastSyncGameTime; + long elapsed = this.level.getGameTime() - this.lastSyncGameTime; return Math.max(0, this.burnTime - (int) elapsed); } @@ -94,7 +94,7 @@ public void tick(Level level, BlockPos pos, BlockState state) { || oldLevel != newLevel; if (bigChange) { - setChanged(); + this.setChanged(); level.sendBlockUpdated(pos, state, state, 3); level.updateNeighbourForOutputSignal(pos, state.getBlock()); } @@ -139,8 +139,8 @@ public void tick(Level level, BlockPos pos, BlockState state) { @Override public void onLoad() { super.onLoad(); - if (level != null) { - this.lastSyncGameTime = level.getGameTime(); + if (this.level != null) { + this.lastSyncGameTime = this.level.getGameTime(); } } @@ -168,8 +168,8 @@ protected void loadAdditional(ValueInput input) { this.itemHandler.set(0, resource, stack.getCount()); } }); - if (level != null) { - this.lastSyncGameTime = level.getGameTime(); + if (this.level != null) { + this.lastSyncGameTime = this.level.getGameTime(); } } @@ -183,17 +183,17 @@ protected void loadAdditional(ValueInput input) { public void consumeBurnTime(int ticks) { if (ticks <= 0) return; this.burnTime = Math.max(0, this.burnTime - ticks); - setChanged(); - if (level != null && !level.isClientSide()) { - this.updateBurningState(level, worldPosition, getBlockState()); - level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 3); - level.updateNeighbourForOutputSignal(worldPosition, getBlockState().getBlock()); + this.setChanged(); + if (this.level != null && !this.level.isClientSide()) { + this.updateBurningState(this.level, this.worldPosition, this.getBlockState()); + this.level.sendBlockUpdated(this.worldPosition, this.getBlockState(), this.getBlockState(), 3); + this.level.updateNeighbourForOutputSignal(this.worldPosition, this.getBlockState().getBlock()); } } private void updateBurningState(Level level, BlockPos pos, BlockState state) { int targetLevel; - if (this.burnTime >= LIT_THRESHOLD) { + if (this.burnTime >= BurningHeaterBlockEntity.LIT_THRESHOLD) { targetLevel = 2; } else if (this.burnTime > 0) { targetLevel = 1; @@ -206,15 +206,15 @@ private void updateBurningState(Level level, BlockPos pos, BlockState state) { } private void tryConsumeFuel() { - if (this.burnTime >= MAX_BURN_TIME) return; + if (this.burnTime >= BurningHeaterBlockEntity.MAX_BURN_TIME) return; ItemResource fuelResource = this.itemHandler.getResource(0); if (fuelResource.isEmpty()) return; int fuelCount = this.itemHandler.getAmountAsInt(0); - int burnTimePerItem = getItemBurnTime(fuelResource.toStack()); + int burnTimePerItem = BurningHeaterBlockEntity.getItemBurnTime(fuelResource.toStack()); if (burnTimePerItem <= 0) return; - int itemsToConsume = Math.min(fuelCount, (MAX_BURN_TIME - this.burnTime) / burnTimePerItem); + int itemsToConsume = Math.min(fuelCount, (BurningHeaterBlockEntity.MAX_BURN_TIME - this.burnTime) / burnTimePerItem); if (itemsToConsume <= 0) return; this.burnTime += itemsToConsume * burnTimePerItem; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilBlockEntity.java index b2912d35e7..777edb2b80 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilBlockEntity.java @@ -32,6 +32,7 @@ import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.util.RandomSource; import net.minecraft.util.Util; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; @@ -81,16 +82,17 @@ public class CelestialForgingAnvilBlockEntity extends BlockEntity public int getRedstoneSignal() { // 客户端刚加载区块时比较器输出不一定可用,直接用同步来的缓存值 if (this.level == null || this.level.isClientSide()) return this.cachedRedstoneSignal; - long now = level.getGameTime(); - if (this.redstoneSignalCacheTick >= 0 && now - this.redstoneSignalCacheTick < REDSTONE_SIGNAL_CACHE_TICKS) { + long now = this.level.getGameTime(); + if (this.redstoneSignalCacheTick >= 0 + && now - this.redstoneSignalCacheTick < CelestialForgingAnvilBlockEntity.REDSTONE_SIGNAL_CACHE_TICKS) { return this.cachedRedstoneSignal; } int signal = 0; for (int dx = -1; dx <= 1; dx++) { for (int dy = 0; dy <= 1; dy++) { for (int dz = -1; dz <= 1; dz++) { - BlockPos partPos = worldPosition.offset(dx, dy, dz); - signal = Math.max(signal, level.getBestNeighborSignal(partPos)); + BlockPos partPos = this.worldPosition.offset(dx, dy, dz); + signal = Math.max(signal, this.level.getBestNeighborSignal(partPos)); } } } @@ -309,7 +311,7 @@ public PowerComponentInfo toPowerComponentInfo() { this.getOutputPower(), 0, 0, this.getRange(), - getShape(), + this.getShape(), type ); } @@ -350,8 +352,9 @@ public CelestialBodyData getEffectiveBodyDataForRendering() { */ public float getAnimationProgress(float partialTick) { if (this.animationTicks <= 0) return this.animationForward ? 1.0f : 0.0f; - float t = (ANIMATION_DURATION_TICKS - this.animationTicks + partialTick) / (float) ANIMATION_DURATION_TICKS; - float eased = easeInOutCubic(t); + float t = (CelestialForgingAnvilBlockEntity.ANIMATION_DURATION_TICKS - this.animationTicks + partialTick) + / (float) CelestialForgingAnvilBlockEntity.ANIMATION_DURATION_TICKS; + float eased = CelestialForgingAnvilBlockEntity.easeInOutCubic(t); return this.animationForward ? eased : (1.0f - eased); } @@ -382,11 +385,13 @@ private static float easeInOutCubic(float t) { * 必须在残骸替换天体数据前调用,才能记录爆炸恒星的中心和缩放。 */ public void startSupernovaFlash() { - this.megastructureManager.getAcceleratorHandler().setSupernovaFlashTicks(SUPERNOVA_FLASH_TICKS); + this.megastructureManager.getAcceleratorHandler().setSupernovaFlashTicks( + CelestialForgingAnvilBlockEntity.SUPERNOVA_FLASH_TICKS + ); this.supernovaCenterY = this.getBodyCenterWorldY(); this.supernovaScale = this.getBodyVisualScaleRatio(); this.setChanged(); - if (level != null && !level.isClientSide()) { + if (this.level != null && !this.level.isClientSide()) { this.syncToClient(); } } @@ -403,7 +408,7 @@ public double getBodyCenterWorldY() { if (this.isAmplify) { centerY += 19.0f * (redstoneSignal / 15.0f); } - return worldPosition.getY() + centerY; + return this.worldPosition.getY() + centerY; } /** @@ -447,7 +452,7 @@ private float advanceSmoothFactor() { this.lastSmoothNanos = now; if (dt <= 0f) return 0f; if (dt > 0.25f) dt = 0.25f; // guard against jumps after lag/pause - return 1.0f - (float) Math.exp(-dt / SMOOTH_TAU); + return 1.0f - (float) Math.exp(-dt / CelestialForgingAnvilBlockEntity.SMOOTH_TAU); } /** 使用当前目标值更新平滑后的渲染缩放和高度,由渲染器每帧调用。 */ @@ -499,20 +504,20 @@ public void setChanged() { * 根据指定重构选项配置建材槽,由服务端处理玩家的选项变更时调用。 */ public void configureMaterialSlot(int optionIndex) { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; if (this.celestialBodyData == null) return; List options = this.getClientVisibleOptions(); if (optionIndex < 0 || optionIndex >= options.size()) { - setMaterialFilter(new ItemStack(Items.BARRIER)); - setMaterialLimit(0); + this.setMaterialFilter(new ItemStack(Items.BARRIER)); + this.setMaterialLimit(0); } else { CelestialRefactorOption opt = options.get(optionIndex); if (opt.needsMaterial()) { - setMaterialFilter(opt.material().copy()); - setMaterialLimit(opt.materialCount()); + this.setMaterialFilter(opt.material().copy()); + this.setMaterialLimit(opt.materialCount()); } else { - setMaterialFilter(new ItemStack(Items.BARRIER)); - setMaterialLimit(0); + this.setMaterialFilter(new ItemStack(Items.BARRIER)); + this.setMaterialLimit(0); } } this.setChanged(); @@ -552,8 +557,8 @@ public void serverTick() { this.searchController.serverTick(this); this.gravityController.tick( - level, - worldPosition, + this.level, + this.worldPosition, this.isAmplify, this.amplifierPresent, this.celestialBodyData, @@ -573,10 +578,11 @@ public void serverTick() { /** 强制移除当前重力源,供结构拆除和方块实体卸载时立即清理缓存。 */ public void handleEntityContact(Entity entity) { - this.gravityController.handleEntityContact(level, this.celestialBodyData, entity); + this.gravityController.handleEntityContact(this.level, this.celestialBodyData, entity); } + public void removeGravitySource() { - this.gravityController.remove(level, worldPosition); + this.gravityController.remove(this.level, this.worldPosition); } private final CelestialSearchHistory searchHistory = new CelestialSearchHistory(); @@ -620,7 +626,7 @@ public void tick() { public void setAmplify(boolean amplify) { if (this.isAmplify != amplify) { this.isAmplify = amplify; - if (level != null && !level.isClientSide()) { + if (this.level != null && !this.level.isClientSide()) { if (this.celestialBodyData instanceof StarData) { if (!amplify) { this.locked = true; // Lock when amplifier removed with stellar body @@ -628,7 +634,7 @@ public void setAmplify(boolean amplify) { } } this.setChanged(); - if (level != null) { + if (this.level != null) { this.syncToClient(); } } @@ -637,8 +643,8 @@ public void setAmplify(boolean amplify) { @Override public void setRemoved() { super.setRemoved(); - if (level != null && !level.isClientSide() && !PowerGrid.isServerClosing) { - this.gravityController.remove(level, worldPosition); + if (this.level != null && !this.level.isClientSide() && !PowerGrid.isServerClosing) { + this.gravityController.remove(this.level, this.worldPosition); // 注销虫洞并清理巨构,使连接传送门及时关闭。 // 服务器关闭期间跳过,避免保存过程中访问持久化数据。 this.megastructureManager.clearAllMegastructures(this); @@ -653,7 +659,7 @@ public void setRemoved() { */ public float getDisplayOffset(int index) { if (this.bodySeed == 0) return 0f; - net.minecraft.util.RandomSource rand = net.minecraft.util.RandomSource.create(this.bodySeed + index * 7919L); + RandomSource rand = RandomSource.create(this.bodySeed + index * 7919L); return (rand.nextFloat() - 0.5f) * 0.1f; } @@ -733,7 +739,7 @@ public static void saveSnapshotToStack(ItemStack stack, CompoundTag snapshot) { @Override public void onLoad() { super.onLoad(); - if (level != null && !level.isClientSide()) { + if (this.level != null && !this.level.isClientSide()) { // 重新注册电网,确保锻星砧同时进入生产者和消费者集合。 PowerGrid.addComponent(this); // 若虫洞稳定器仍有效,其处理器会在重新建造回调中恢复网络注册。 @@ -813,7 +819,7 @@ protected void loadAdditional(ValueInput input) { .map(CelestialBodyData::fromTag).orElse(null); // 客户端在区块加载等情况下检测天体切换;恒星演化或超新星闪光期间跳过。 boolean skipAnimLoad = this.getAcceleratorStage() >= 1 || this.getSupernovaFlashTicks() > 0; - if (level != null && level.isClientSide() && !skipAnimLoad) { + if (this.level != null && this.level.isClientSide() && !skipAnimLoad) { this.detectAnimationTransition(oldBodyData, this.celestialBodyData); } // 搜索历史 @@ -851,7 +857,7 @@ protected void loadAdditional(ValueInput input) { }); // 最后读取巨构数据,使处理器能够覆盖控制器中的派生状态。 this.megastructureManager.loadAdditional(input); - if (level != null && !level.isClientSide()) { + if (this.level != null && !this.level.isClientSide()) { this.syncToClient(); } } @@ -860,22 +866,22 @@ protected void loadAdditional(ValueInput input) { * 在客户端检测天体切换并触发对应动画。 */ private void detectAnimationTransition(@Nullable CelestialBodyData oldBody, @Nullable CelestialBodyData newBody) { - if (level == null || !level.isClientSide()) return; + if (this.level == null || !this.level.isClientSide()) return; boolean hadBody = oldBody != null; boolean hasBody = newBody != null; if (!hadBody && hasBody) { // 天体出现:播放正向放大动画。 - this.animationTicks = ANIMATION_DURATION_TICKS; + this.animationTicks = CelestialForgingAnvilBlockEntity.ANIMATION_DURATION_TICKS; this.animationForward = true; this.animationPreviousBodyData = null; } else if (hadBody && !hasBody) { // 天体消失:播放反向缩小动画。 - this.animationTicks = ANIMATION_DURATION_TICKS; + this.animationTicks = CelestialForgingAnvilBlockEntity.ANIMATION_DURATION_TICKS; this.animationForward = false; this.animationPreviousBodyData = oldBody; } else if (hadBody && !oldBody.toTag().equals(newBody.toTag())) { // 天体类型变化:先缓存旧天体并播放切换动画。 - this.animationTicks = ANIMATION_DURATION_TICKS; + this.animationTicks = CelestialForgingAnvilBlockEntity.ANIMATION_DURATION_TICKS; this.animationForward = true; this.animationPreviousBodyData = oldBody; } @@ -962,7 +968,7 @@ public boolean hasNextHistory() { } public void browseHistoryPrev() { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; CelestialSearchHistory.Entry entry = this.searchHistory.previous( this.celestialBodyData, this.planetaryResourceSet ); @@ -970,7 +976,7 @@ public void browseHistoryPrev() { } public void browseHistoryNext() { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; CelestialSearchHistory.Entry entry = this.searchHistory.next(); if (entry != null) this.applyHistoryEntry(entry); } @@ -978,7 +984,7 @@ public void browseHistoryNext() { private void applyHistoryEntry(CelestialSearchHistory.Entry entry) { this.celestialBodyData = entry.body(); this.planetaryResourceSet = entry.resources(); - setChanged(); + this.setChanged(); this.syncToClient(); } @@ -1008,7 +1014,7 @@ public Packet getUpdatePacket() { * 切换天体锁定状态,由服务端处理玩家点击锁定按钮时调用。 */ public void toggleLocked() { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; if (this.isAcceleratorActive()) { // 恒星演化期间禁止解锁。 return; @@ -1077,7 +1083,7 @@ public Map getPortals() { * @param optionIndex 玩家选择的重构选项索引 */ public void buildMegastructure(int optionIndex) { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; if (this.celestialBodyData == null) return; List options = this.getClientVisibleOptions(); if (optionIndex < 0 || optionIndex >= options.size()) return; @@ -1117,11 +1123,10 @@ public void syncLogisticsOnChange(BlockPos interfacePos, int changedSlot) { /** * 在锻星砧指定侧注册传送门。 * - * @return 注册成功返回 {@code true};侧面无效或已有传送门时返回 {@code false} */ - public boolean addPortal(Cube323PartHalf side, BlockPos portalPos) { + public void addPortal(Cube323PartHalf side, BlockPos portalPos) { WormholeStabilizerHandler wh = this.megastructureManager.getWormholeHandler(); - return wh.addPortal(side, portalPos, this); + wh.addPortal(side, portalPos, this); } /** diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilFluidInterfaceBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilFluidInterfaceBlockEntity.java index 4a2b5b6bb5..c15f6e0876 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilFluidInterfaceBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilFluidInterfaceBlockEntity.java @@ -54,14 +54,17 @@ public class CelestialForgingAnvilFluidInterfaceBlockEntity extends BlockEntity public CelestialForgingAnvilFluidInterfaceBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); - this.tank = new FluidStacksResourceHandler(TANK_COUNT, CAPACITY_PER_TANK) { + this.tank = new FluidStacksResourceHandler( + CelestialForgingAnvilFluidInterfaceBlockEntity.TANK_COUNT, + CelestialForgingAnvilFluidInterfaceBlockEntity.CAPACITY_PER_TANK + ) { @Override public boolean isValid(int index, FluidResource resource) { if (resource.isEmpty()) return false; FluidStack currentStack = this.getStackFrom(this.getResource(index), this.getAmountAsInt(index)); if (!currentStack.isEmpty() && currentStack.is(resource.getFluid())) return true; if (currentStack.isEmpty()) { - for (int j = 0; j < TANK_COUNT; j++) { + for (int j = 0; j < CelestialForgingAnvilFluidInterfaceBlockEntity.TANK_COUNT; j++) { if (j != index) { FluidStack otherStack = this.getStackFrom(this.getResource(j), this.getAmountAsInt(j)); if (!otherStack.isEmpty() && otherStack.is(resource.getFluid())) { @@ -175,8 +178,8 @@ public void syncToClients() { @Override public void setChanged() { super.setChanged(); - if (level != null && !level.isClientSide()) { - level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 3); + if (this.level != null && !this.level.isClientSide()) { + this.level.sendBlockUpdated(this.worldPosition, this.getBlockState(), this.getBlockState(), 3); this.syncToClients(); } } @@ -258,8 +261,8 @@ private boolean isActive() { /// 前方是管道→沿管道追踪到远端再推送;前方是流体容器→直接推送; /// 扬程 10 米,流速随高度差放大(复用管道系统的 moveFluid)。 public void serverTick() { - if (level == null || level.isClientSide()) return; - BlockState state = getBlockState(); + if (this.level == null || this.level.isClientSide()) return; + BlockState state = this.getBlockState(); if (!state.hasProperty(CelestialForgingAnvilInterfaceBlock.ACTIVE)) return; boolean active = state.getValue(CelestialForgingAnvilInterfaceBlock.ACTIVE); @@ -269,14 +272,14 @@ public void serverTick() { if (this.grid == null || !this.grid.isWorking()) return; Direction facing = state.getValue(CelestialForgingAnvilInterfaceBlock.FACING); - BlockPos frontPos = getBlockPos().relative(facing); - BlockState frontState = level.getBlockState(frontPos); - int sourceEffectiveHeight = getBlockPos().getY() + PUMP_HEADLIFT; + BlockPos frontPos = this.getBlockPos().relative(facing); + BlockState frontState = this.level.getBlockState(frontPos); + int sourceEffectiveHeight = this.getBlockPos().getY() + CelestialForgingAnvilFluidInterfaceBlockEntity.PUMP_HEADLIFT; if (FluidNetworkScanner.isPipePart(frontState)) { - FluidPipeNetwork network = FluidNetworkScanner.scan(level, frontPos); + FluidPipeNetwork network = FluidNetworkScanner.scan(this.level, frontPos); if (network != null) { - network.pushFromExternalSource(this.tank, getBlockPos(), frontPos, sourceEffectiveHeight); + network.pushFromExternalSource(this.tank, this.getBlockPos(), frontPos, sourceEffectiveHeight); } return; } @@ -290,7 +293,7 @@ public void serverTick() { // 从前方管道沿 facing.getOpposite() 方向追踪到管道远端。 // getPipeEnd 的参数 direction 是"从管道哪一侧进入",即接口连接管道的那一侧。 AbstractPipeBlockEntity.PipeEnd pipeEnd = - AbstractPipeBlockEntity.getPipeEnd(level, frontPos, facing.getOpposite()); + AbstractPipeBlockEntity.getPipeEnd(this.level, frontPos, facing.getOpposite()); if (pipeEnd == null) return; // pipeEnd.direction() = 从管道末端指向接收方的方向 targetPos = pipeEnd.pos().relative(pipeEnd.direction()); @@ -302,15 +305,15 @@ public void serverTick() { } // 计算有效高度差(含 10m 扬程,扣除管道累计等效高度) - int sourceY = getBlockPos().getY(); + int sourceY = this.getBlockPos().getY(); int targetY = targetPos.getY() - pipeHeight; - int heightDiff = PUMP_HEADLIFT + sourceY - targetY; + int heightDiff = CelestialForgingAnvilFluidInterfaceBlockEntity.PUMP_HEADLIFT + sourceY - targetY; if (heightDiff <= 0) return; // 复用管道系统的流体传输:源端为接口自身(内部储罐,通过 Fluid.BLOCK 能力查询)。 AbstractPipeBlockEntity.moveFluid( - level, - getBlockPos(), // sourcePos = 接口自身(内部储罐) + this.level, + this.getBlockPos(), // sourcePos = 接口自身(内部储罐) facing, // sourceQueryDir(能力忽略 side,任意方向均可) targetPos, // 接收方位置 targetQueryDir, // 从接收方面向源 diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilLaserInterfaceBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilLaserInterfaceBlockEntity.java index abfc7a3cde..fda947ad60 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilLaserInterfaceBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilLaserInterfaceBlockEntity.java @@ -99,7 +99,7 @@ public static CelestialForgingAnvilLaserInterfaceBlockEntity createBlockEntity( @Override public Direction getFacing() { - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); if (state.hasProperty(CelestialForgingAnvilInterfaceBlock.FACING)) { return state.getValue(CelestialForgingAnvilInterfaceBlock.FACING); } @@ -108,7 +108,7 @@ public Direction getFacing() { @Override protected int getBaseLaserLevel() { - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); if (state.hasProperty(CelestialForgingAnvilInterfaceBlock.ACTIVE) && state.getValue(CelestialForgingAnvilInterfaceBlock.ACTIVE)) { return this.wormholeOutputLevel; @@ -120,13 +120,13 @@ protected int getBaseLaserLevel() { public void syncTo(ServerPlayer player) { PacketDistributor.sendToPlayer( player, - new LaserEmitPacket(getLaserLevel(), getBlockPos(), this.irradiateBlockPos, this.emittingGamma) + new LaserEmitPacket(this.getLaserLevel(), this.getBlockPos(), this.irradiateBlockPos, this.emittingGamma) ); } /// 此激光接口是否处于主动模式(由铁砧锤切换的 ACTIVE 属性,而非红石信号)。 public boolean isActive() { - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); return state.hasProperty(CelestialForgingAnvilInterfaceBlock.ACTIVE) && state.getValue(CelestialForgingAnvilInterfaceBlock.ACTIVE); } @@ -239,8 +239,8 @@ public void emitGammaLaser(int level) { * 方块 ticker 调用的服务端逻辑。 */ public void serverTick() { - if (level == null || level.isClientSide()) return; - BlockState state = getBlockState(); + if (this.level == null || this.level.isClientSide()) return; + BlockState state = this.getBlockState(); if (!state.hasProperty(CelestialForgingAnvilInterfaceBlock.ACTIVE)) return; boolean active = state.getValue(CelestialForgingAnvilInterfaceBlock.ACTIVE); @@ -248,15 +248,15 @@ public void serverTick() { // 只要正在接收外部激光,就始终以接收为优先,不再发射任何激光。 if (this.receivedLaserLevel > 0) { // 清除已有输出,避免同一接口同时收发。 - if (irradiateBlockPos != null) { - BlockEntity oldBe = level.getBlockEntity(irradiateBlockPos); + if (this.irradiateBlockPos != null) { + BlockEntity oldBe = this.level.getBlockEntity(this.irradiateBlockPos); if (oldBe instanceof BaseLaserBlockEntity lastIrradiated) { lastIrradiated.onCancelingIrradiation(this); } - updateIrradiateBlockPos(null); + this.updateIrradiateBlockPos(null); } - irradiateSelfLaserBlockSet.clear(); - updateLaserLevel(0); // clear stale emission level for HUD + this.irradiateSelfLaserBlockSet.clear(); + this.updateLaserLevel(0); // clear stale emission level for HUD } else if (this.emittingGamma && this.gammaLevel > 0) { // 输出彭罗斯球产生的伽马激光。 Direction facing = this.getFacing(); @@ -275,24 +275,24 @@ public void serverTick() { // 主动模式仅在存在虫洞普通激光输出时发射,不再自发产生 1 级激光。 Direction facing = this.getFacing(); // 尚未加入其他激光链时才创建输出链。 - if (irradiateSelfLaserBlockSet.isEmpty()) { - emitLaser(facing); + if (this.irradiateSelfLaserBlockSet.isEmpty()) { + this.emitLaser(facing); } } else { // 被动模式或主动但无虫洞输出时,清理残留激光。 - if (irradiateBlockPos != null) { - BlockEntity oldBe = level.getBlockEntity(irradiateBlockPos); + if (this.irradiateBlockPos != null) { + BlockEntity oldBe = this.level.getBlockEntity(this.irradiateBlockPos); if (oldBe instanceof BaseLaserBlockEntity lastIrradiated) { lastIrradiated.onCancelingIrradiation(this); } - updateIrradiateBlockPos(null); + this.updateIrradiateBlockPos(null); } - irradiateSelfLaserBlockSet.clear(); - updateLaserLevel(0); // clear stale emission level for HUD + this.irradiateSelfLaserBlockSet.clear(); + this.updateLaserLevel(0); // clear stale emission level for HUD } // 发送包含伽马标记的激光同步包。 - this.tickWithGamma(level); + this.tickWithGamma(this.level); // 同步完成后清除本刻的伽马输出标记。 if (this.emittingGamma) { @@ -300,10 +300,10 @@ public void serverTick() { } // 命中可加热方块时注册热源。服务端未调用父类 tick,因此需要在此手动处理。 - if (level instanceof ServerLevel serverLevel - && irradiateBlockPos != null - && serverLevel.getBlockState(irradiateBlockPos).is(ModBlockTags.HEATABLE_BLOCKS)) { - HeaterManager.addProducer(getBlockPos(), serverLevel, ModHeaterInfos.LASER_EMITTER); + if (this.level instanceof ServerLevel serverLevel + && this.irradiateBlockPos != null + && serverLevel.getBlockState(this.irradiateBlockPos).is(ModBlockTags.HEATABLE_BLOCKS)) { + HeaterManager.addProducer(this.getBlockPos(), serverLevel, ModHeaterInfos.LASER_EMITTER); } } @@ -322,12 +322,12 @@ public void tick(Level level) { * 发送带伽马类型标记的激光网络包。 */ private void tickWithGamma(Level level) { - if (changed) { + if (this.changed) { if (level instanceof ServerLevel serverLevel) { PacketDistributor.sendToPlayersTrackingChunk( serverLevel, - level.getChunkAt(getBlockPos()).getPos(), - new LaserEmitPacket(getLaserLevel(), getBlockPos(), this.irradiateBlockPos, this.emittingGamma) + level.getChunkAt(this.getBlockPos()).getPos(), + new LaserEmitPacket(this.getLaserLevel(), this.getBlockPos(), this.irradiateBlockPos, this.emittingGamma) ); } } @@ -393,12 +393,12 @@ private void emitGammaLaserBeam(Direction direction) { && !this.isInIrradiateSelfLaserBlockSet(irradiatedLaserBlockEntity) ) { if (irradiatedLaserBlockEntity.getIgnoreFace().isEmpty()) { - this.level.updateNeighborsAt(tempIrradiateBlockPos, getBlockState().getBlock()); + this.level.updateNeighborsAt(tempIrradiateBlockPos, this.getBlockState().getBlock()); irradiatedLaserBlockEntity.onIrradiated(this); } else { for (Direction dir : irradiatedLaserBlockEntity.getIgnoreFace()) { if (direction != dir) { - this.level.updateNeighborsAt(tempIrradiateBlockPos, getBlockState().getBlock()); + this.level.updateNeighborsAt(tempIrradiateBlockPos, this.getBlockState().getBlock()); irradiatedLaserBlockEntity.onIrradiated(this); } } @@ -418,7 +418,7 @@ private void emitGammaLaserBeam(Direction direction) { // 按方块位置累计连续照射时间,达到阈值后破坏。 BlockState irradiateBlock = this.level.getBlockState(this.irradiateBlockPos); - int requiredExposure = GAMMA_EXPOSURE_TICKS[Math.clamp(this.gammaLevel / 4, 0, 4)]; + int requiredExposure = CelestialForgingAnvilLaserInterfaceBlockEntity.GAMMA_EXPOSURE_TICKS[Math.clamp(this.gammaLevel / 4, 0, 4)]; // 照射目标变化时重新计时。 BlockPos currentTarget = this.irradiateBlockPos.immutable(); @@ -479,7 +479,7 @@ protected void loadAdditional(ValueInput input) { super.loadAdditional(input); this.receivedLaserLevel = input.getIntOr("receivedLaserLevel", 0); this.receivedGamma = input.getBooleanOr("receivedGamma", false); - this.receivedMiningEffect = readMiningEffect(input); + this.receivedMiningEffect = CelestialForgingAnvilLaserInterfaceBlockEntity.readMiningEffect(input); this.requiredLaserLevel = input.getIntOr("requiredLaserLevel", 0); this.requiredGamma = input.getBooleanOr("requiredGamma", false); this.laserValid = input.getBooleanOr("laserValid", false); @@ -538,7 +538,7 @@ public void syncToClients() { @Override public void setChanged() { super.setChanged(); - if (level != null && !level.isClientSide()) { + if (this.level != null && !this.level.isClientSide()) { this.syncToClients(); } } @@ -551,7 +551,7 @@ public void setChanged() { @Override public void onLoad() { super.onLoad(); - if (level != null && level.isClientSide()) { + if (this.level != null && this.level.isClientSide()) { CachedBlockEntityRenderingPipeline.getInstance().update(this, true); } } @@ -559,7 +559,7 @@ public void onLoad() { @Override public void setRemoved() { super.setRemoved(); - if (this.level != null && level.isClientSide()) { + if (this.level != null && this.level.isClientSide()) { CachedBlockEntityRenderingPipeline.getInstance().update(this, true); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilPortalBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilPortalBlockEntity.java index 56e48f57db..871ca8ea5c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilPortalBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CelestialForgingAnvilPortalBlockEntity.java @@ -14,6 +14,7 @@ import dev.dubhe.anvilcraft.network.LaserEmitPacket; import dev.dubhe.anvilcraft.saved.WormholeNetwork; import dev.dubhe.anvilcraft.util.BreakBlockUtil; +import dev.dubhe.anvilcraft.util.EntityUtil; import lombok.Getter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -166,12 +167,11 @@ public void emitLaser(Direction direction) { Objects.requireNonNull(this.irradiateBlockPos).relative(direction.getOpposite()).getCenter() .add(0.0625, 0.0625, 0.0625) ); - // noinspection deprecation serverLevel.getEntities( EntityTypeTest.forClass(LivingEntity.class), trackBoundingBox, Entity::isAlive - ).forEach(le -> le.hurtOrSimulate(ModDamageTypes.laser(this.level), hurt)); + ).forEach(le -> EntityUtil.hurtOrSimulate(le, ModDamageTypes.laser(this.level), hurt)); } BlockState irradiateBlock = this.level.getBlockState(Objects.requireNonNull(this.irradiateBlockPos)); int cooldown = COOLDOWNS[Math.clamp(this.laserLevel / 4, 0, 4)]; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGammaLaserEffects.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGammaLaserEffects.java index fdc4d461ca..365a149257 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGammaLaserEffects.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGammaLaserEffects.java @@ -5,6 +5,7 @@ import dev.dubhe.anvilcraft.block.laser.RubyPrismBlock; import dev.dubhe.anvilcraft.init.block.ModBlocks; import dev.dubhe.anvilcraft.init.entity.ModDamageTypes; +import dev.dubhe.anvilcraft.util.EntityUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.tags.BlockTags; @@ -28,11 +29,11 @@ private CfaGammaLaserEffects() { } static BlockPos findTarget(Level level, BlockPos origin, Direction direction) { - for (int distance = 1; distance <= MAX_DISTANCE; distance++) { + for (int distance = 1; distance <= CfaGammaLaserEffects.MAX_DISTANCE; distance++) { BlockPos candidate = origin.relative(direction, distance); if (!level.getBlockState(candidate).is(BlockTags.REPLACEABLE)) return candidate; } - return origin.relative(direction, MAX_DISTANCE); + return origin.relative(direction, CfaGammaLaserEffects.MAX_DISTANCE); } static void destroyPrisms(Level level, BlockPos origin, Direction direction, BlockPos target) { @@ -52,8 +53,7 @@ static void damageEntities(Level level, BlockPos origin, BlockPos target, Direct Vec3 end = target.relative(direction.getOpposite()).getCenter().add(0.0625, 0.0625, 0.0625); level.getEntities(EntityTypeTest.forClass(LivingEntity.class), new AABB(start, end), Entity::isAlive) .forEach(entity -> { - // noinspection deprecation - entity.hurtOrSimulate(ModDamageTypes.gammaLaser(level), damage); + EntityUtil.hurtOrSimulate(entity, ModDamageTypes.gammaLaser(level), damage); }); } @@ -83,7 +83,7 @@ static void heatEmberMetal( BlockPos depthPos = target.relative(direction, depth); for (int first = -halfSize; first <= halfSize; first++) { for (int second = -halfSize; second <= halfSize; second++) { - heatEmberMetalAt(level, depthPos + CfaGammaLaserEffects.heatEmberMetalAt(level, depthPos .relative(perpendiculars[0], first) .relative(perpendiculars[1], second), updateFlags); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGravityController.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGravityController.java index dbcd50e890..f3b5bf77e7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGravityController.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaGravityController.java @@ -7,6 +7,7 @@ import dev.dubhe.anvilcraft.entity.ThrownHeavyHalberdEntity; import dev.dubhe.anvilcraft.init.entity.ModDamageTypes; import dev.dubhe.anvilcraft.init.item.ModComponents; +import dev.dubhe.anvilcraft.util.EntityUtil; import dev.dubhe.anvilcraft.util.GravityManager; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; @@ -47,12 +48,12 @@ void tick( } int signal = Math.max(0, Math.min(15, redstoneSignal)); - double targetBodyRadius = calculateBodyRadius(body, signal); - int targetRadius = calculateGravityRadius(body, amplified, signal); - double targetStrength = calculateStrength(body, stellarMass, targetBodyRadius); + double targetBodyRadius = CfaGravityController.calculateBodyRadius(body, signal); + int targetRadius = CfaGravityController.calculateGravityRadius(body, amplified, signal); + double targetStrength = CfaGravityController.calculateStrength(body, stellarMass, targetBodyRadius); Vec3 center = new Vec3( controllerPos.getX() + 0.5, - controllerPos.getY() + calculateVisualCenterY(body, amplified, signal), + controllerPos.getY() + CfaGravityController.calculateVisualCenterY(body, amplified, signal), controllerPos.getZ() + 0.5 ); GravityManager.GravitySourceType type = new GravityManager.GravitySourceType( @@ -86,7 +87,7 @@ private static int calculateGravityRadius(CelestialBodyData body, boolean amplif + (fullRingScale - CelestialBodyData.BASE_RING_SCALE) * redstoneFactor; return Math.max( 1, - Math.round(BASE_GRAVITY_RADIUS * ringScale / CelestialBodyData.BASE_RING_SCALE) + Math.round(CfaGravityController.BASE_GRAVITY_RADIUS * ringScale / CelestialBodyData.BASE_RING_SCALE) ); } @@ -118,11 +119,11 @@ void handleEntityContact(@Nullable Level level, @Nullable CelestialBodyData body || body == null || entity.level() != level || entity.isRemoved() - || isEternal(entity)) { + || CfaGravityController.isEternal(entity)) { return; } if (entity instanceof LivingEntity living) { - applyCelestialDamage(level, body, living); + CfaGravityController.applyCelestialDamage(level, body, living); } else { entity.discard(); } @@ -140,15 +141,20 @@ private static boolean isEternal(Entity entity) { private static void applyCelestialDamage(Level level, CelestialBodyData body, LivingEntity living) { if (body instanceof StarData star) { if (star.bodyClass() == CelestialBodyClass.BLACK_HOLE) { - // noinspection deprecation - living.hurtOrSimulate(ModDamageTypes.lostInTime(level), Float.MAX_VALUE); + EntityUtil.hurtOrSimulate(living, ModDamageTypes.lostInTime(level), Float.MAX_VALUE); } else { - // noinspection deprecation - living.hurtOrSimulate(level.damageSources().inFire(), STAR_CONTACT_DAMAGE); + EntityUtil.hurtOrSimulate( + living, + level.damageSources().inFire(), + CfaGravityController.STAR_CONTACT_DAMAGE + ); } } else { - // noinspection deprecation - living.hurtOrSimulate(level.damageSources().fall(), PLANET_CONTACT_DAMAGE); + EntityUtil.hurtOrSimulate( + living, + level.damageSources().fall(), + CfaGravityController.PLANET_CONTACT_DAMAGE + ); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInterfaceScanner.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInterfaceScanner.java index d93fe402d2..b2b57be374 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInterfaceScanner.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInterfaceScanner.java @@ -32,7 +32,7 @@ public int size() { private CfaInterfaceScanner() { } - public static void scanAdjacentBlocks(BlockPos controllerPos, Level level, Consumer consumer) { + public static void scanAdjacentBlocks(BlockPos controllerPos, @Nullable Level level, Consumer consumer) { if (level == null) return; int y = controllerPos.getY(); int cx = controllerPos.getX(); @@ -52,12 +52,12 @@ public static void scanAdjacentBlocks(BlockPos controllerPos, Level level, Consu } public static List findLaserInterfaces( - Level level, BlockPos controllerPos + @Nullable Level level, BlockPos controllerPos ) { List result = new ArrayList<>(); if (level == null) return result; - scanAdjacentBlocks(controllerPos, level, (checkPos) -> { - BlockEntity be = getLoadedBlockEntity(level, checkPos); + CfaInterfaceScanner.scanAdjacentBlocks(controllerPos, level, (checkPos) -> { + BlockEntity be = CfaInterfaceScanner.getLoadedBlockEntity(level, checkPos); if (be instanceof CelestialForgingAnvilLaserInterfaceBlockEntity laserBe) { result.add(laserBe); } @@ -65,11 +65,14 @@ public static List findLaserInte return result; } - public static List> findLogisticsInterfaces(Level level, BlockPos controllerPos) { + public static List> findLogisticsInterfaces( + @Nullable Level level, + BlockPos controllerPos + ) { List> result = new ArrayList<>(); if (level == null) return result; - scanAdjacentBlocks(controllerPos, level, (checkPos) -> { - BlockEntity be = getLoadedBlockEntity(level, checkPos); + CfaInterfaceScanner.scanAdjacentBlocks(controllerPos, level, (checkPos) -> { + BlockEntity be = CfaInterfaceScanner.getLoadedBlockEntity(level, checkPos); if (be instanceof CelestialForgingAnvilLogisticsInterfaceBlockEntity logisticsBe) { result.add(logisticsBe.getItemHandler()); } @@ -78,27 +81,27 @@ public static List> findLogisticsInterfaces(Level } public static PrioritizedInterfaces> findPrioritizedLogisticsInterfaces( - Level level, BlockPos controllerPos + @Nullable Level level, BlockPos controllerPos ) { List> active = new ArrayList<>(); List> passive = new ArrayList<>(); if (level == null) return new PrioritizedInterfaces<>(active, passive); - scanAdjacentBlocks(controllerPos, level, (checkPos) -> { - BlockEntity be = getLoadedBlockEntity(level, checkPos); + CfaInterfaceScanner.scanAdjacentBlocks(controllerPos, level, (checkPos) -> { + BlockEntity be = CfaInterfaceScanner.getLoadedBlockEntity(level, checkPos); if (be instanceof CelestialForgingAnvilLogisticsInterfaceBlockEntity logisticsBe) { - (isActive(logisticsBe) ? active : passive).add(logisticsBe.getItemHandler()); + (CfaInterfaceScanner.isActive(logisticsBe) ? active : passive).add(logisticsBe.getItemHandler()); } }); return new PrioritizedInterfaces<>(active, passive); } public static List findFluidInterfaces( - Level level, BlockPos controllerPos + @Nullable Level level, BlockPos controllerPos ) { List result = new ArrayList<>(); if (level == null) return result; - scanAdjacentBlocks(controllerPos, level, (checkPos) -> { - BlockEntity be = getLoadedBlockEntity(level, checkPos); + CfaInterfaceScanner.scanAdjacentBlocks(controllerPos, level, (checkPos) -> { + BlockEntity be = CfaInterfaceScanner.getLoadedBlockEntity(level, checkPos); if (be instanceof CelestialForgingAnvilFluidInterfaceBlockEntity fluidBe) { result.add(fluidBe); } @@ -107,14 +110,14 @@ public static List findFluidInte } public static PrioritizedInterfaces - findPrioritizedFluidInterfaces(Level level, BlockPos controllerPos) { + findPrioritizedFluidInterfaces(@Nullable Level level, BlockPos controllerPos) { List active = new ArrayList<>(); List passive = new ArrayList<>(); if (level == null) return new PrioritizedInterfaces<>(active, passive); - scanAdjacentBlocks(controllerPos, level, (checkPos) -> { - BlockEntity be = getLoadedBlockEntity(level, checkPos); + CfaInterfaceScanner.scanAdjacentBlocks(controllerPos, level, (checkPos) -> { + BlockEntity be = CfaInterfaceScanner.getLoadedBlockEntity(level, checkPos); if (be instanceof CelestialForgingAnvilFluidInterfaceBlockEntity fluidBe) { - (isActive(fluidBe) ? active : passive).add(fluidBe); + (CfaInterfaceScanner.isActive(fluidBe) ? active : passive).add(fluidBe); } }); return new PrioritizedInterfaces<>(active, passive); @@ -127,12 +130,12 @@ private static boolean isActive(BlockEntity blockEntity) { } public static Map getInterfacesMap( - Class type, Level level, BlockPos controllerPos + Class type, @Nullable Level level, BlockPos controllerPos ) { Map result = new HashMap<>(); if (level == null) return result; - scanAdjacentBlocks(controllerPos, level, (checkPos) -> { - BlockEntity be = getLoadedBlockEntity(level, checkPos); + CfaInterfaceScanner.scanAdjacentBlocks(controllerPos, level, (checkPos) -> { + BlockEntity be = CfaInterfaceScanner.getLoadedBlockEntity(level, checkPos); if (type.isInstance(be)) { BlockPos relOffset = new BlockPos( checkPos.getX() - controllerPos.getX(), 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInventoryCodec.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInventoryCodec.java index 72bb350729..fc6c7dfa7c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInventoryCodec.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CfaInventoryCodec.java @@ -19,7 +19,7 @@ static CompoundTag save(SimpleContainer container) { for (int slot = 0; slot < container.getContainerSize(); slot++) { ItemStack stack = container.getItem(slot); if (!stack.isEmpty()) { - tag.put(key(slot), ItemStack.CODEC.encodeStart(NbtOps.INSTANCE, stack).getOrThrow()); + tag.put(CfaInventoryCodec.key(slot), ItemStack.CODEC.encodeStart(NbtOps.INSTANCE, stack).getOrThrow()); } } return tag; @@ -27,8 +27,9 @@ static CompoundTag save(SimpleContainer container) { static void load(CompoundTag tag, SimpleContainer container) { for (int slot = 0; slot < container.getContainerSize(); slot++) { - ItemStack stack = tag.contains(key(slot)) - ? ItemStack.CODEC.parse(NbtOps.INSTANCE, Objects.requireNonNull(tag.get(key(slot)))).result().orElse(ItemStack.EMPTY) + ItemStack stack = tag.contains(CfaInventoryCodec.key(slot)) + ? ItemStack.CODEC.parse(NbtOps.INSTANCE, Objects.requireNonNull(tag.get( + CfaInventoryCodec.key(slot)))).result().orElse(ItemStack.EMPTY) : ItemStack.EMPTY; container.setItem(slot, stack); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargeCollectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargeCollectorBlockEntity.java index 9bd89aa605..016a8024b5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargeCollectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargeCollectorBlockEntity.java @@ -115,15 +115,15 @@ protected void saveAdditional(ValueOutput output) { @Override public void gridTick() { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; if (this.inputCooldownCount-- <= 1) { - this.inputCooldownCount = INPUT_COOLDOWN; + this.inputCooldownCount = ChargeCollectorBlockEntity.INPUT_COOLDOWN; this.charges.add((int) Math.floor(this.chargeCount)); this.chargeCount = 0; this.time++; } if (this.outputCooldownCount-- <= 1) { - this.outputCooldownCount = OUTPUT_COOLDOWN; + this.outputCooldownCount = ChargeCollectorBlockEntity.OUTPUT_COOLDOWN; final int oldPower = this.power; this.power = 0; for (Integer charge : this.charges) { @@ -142,14 +142,14 @@ public void gridTick() { /// @param num 添加至收集器的电荷数 /// @return 溢出的电荷数(即未被添加至收集器的电荷数) public double incomingCharge(double num, BlockPos srcPos) { - double overflow = num - (MAX_POWER_PER_INCOMING - this.chargeCount); + double overflow = num - (ChargeCollectorBlockEntity.MAX_POWER_PER_INCOMING - this.chargeCount); if (overflow < 0) { overflow = 0; } double acceptableChargeCount = num - overflow; PacketDistributor.sendToPlayersTrackingChunk( (ServerLevel) this.level, - ChunkPos.containing(worldPosition), + ChunkPos.containing(this.worldPosition), new ChargeCollectorIncomingChargePacket( srcPos, this.worldPosition, diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargerBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargerBlockEntity.java index 44061d0726..cff629501b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargerBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ChargerBlockEntity.java @@ -387,7 +387,7 @@ private void dropItemStack(ItemStack stack) { /// 充电器逻辑 public void tick(Level level, BlockPos blockPos) { - flushState(level, blockPos); + this.flushState(level, blockPos); BlockState state = level.getBlockState(blockPos); boolean powered = state.getValue(ChargerBlock.POWERED); if (this.grid == null) return; @@ -468,6 +468,9 @@ public PowerComponentInfo toPowerComponentInfo() { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); - Containers.dropContents(this.level, pos, this.getFilteredItemStackHandler().getStacks()); + Level level = this.level; + if (level != null) { + Containers.dropContents(level, pos, this.getFilteredItemStackHandler().getStacks()); + } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ChuteBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ChuteBlockEntity.java index 0030998399..e8d7135afa 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ChuteBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ChuteBlockEntity.java @@ -2,7 +2,6 @@ import dev.dubhe.anvilcraft.api.block.entity.IConvertableBlockEntity; import dev.dubhe.anvilcraft.api.itemhandler.FilteredItemStackHandler; -import dev.dubhe.anvilcraft.api.itemhandler.ItemHandlerUtil; import dev.dubhe.anvilcraft.block.logistics.chute.ChuteBlock; import dev.dubhe.anvilcraft.init.ModMenuTypes; import dev.dubhe.anvilcraft.init.block.ModBlockEntities; @@ -14,11 +13,11 @@ import net.minecraft.core.Direction; import net.minecraft.core.Holder; import net.minecraft.network.chat.Component; -import net.minecraft.world.Containers; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -53,7 +52,7 @@ protected EnumProperty getFacingProperty() { @Override protected Direction getOutputDirection() { - return getDirection(); + return this.getDirection(); } @Override @@ -63,7 +62,7 @@ protected Direction getInputDirection() { @Override protected boolean isEnabled() { - return getBlockState().getValue(ChuteBlock.ENABLED); + return this.getBlockState().getValue(ChuteBlock.ENABLED); } public static ChuteBlockEntity createBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { @@ -110,6 +109,9 @@ public void convertTo(SimpleChuteBlockEntity newBe) { transaction.commit(); } } - AnvilUtil.dropItems(drops, this.level, newBe.getBlockPos().getCenter()); + Level level = this.level; + if (level != null) { + AnvilUtil.dropItems(drops, level, newBe.getBlockPos().getCenter()); + } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ConfinementChamberBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ConfinementChamberBlockEntity.java index 63fe41b92f..fbb2ddccb7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ConfinementChamberBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ConfinementChamberBlockEntity.java @@ -8,6 +8,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.Containers; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; @@ -26,7 +27,7 @@ public class ConfinementChamberBlockEntity extends BlockEntity implements IItemR public ConfinementChamberBlockEntity(BlockPos pos, BlockState blockState) { super(ModBlockEntities.CONFINEMENT_CHAMBER.get(), pos, blockState); - this.id = COUNTER.incrementAndGet(); + this.id = ConfinementChamberBlockEntity.COUNTER.incrementAndGet(); } private ConfinementChamberBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { @@ -71,6 +72,9 @@ protected void loadAdditional(ValueInput input) { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); - Containers.dropContents(this.level, pos, this.itemHandler.copyToList()); + Level level = this.level; + if (level != null) { + Containers.dropContents(level, pos, this.itemHandler.copyToList()); + } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CorruptedBeaconBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CorruptedBeaconBlockEntity.java index b6442fb937..bf5509a976 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CorruptedBeaconBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CorruptedBeaconBlockEntity.java @@ -107,24 +107,24 @@ public static void tick(Level level, BlockPos pos, BlockState state, CorruptedBe // 每 80 tick 检查一次:更新基座等级、同步 LIT 状态、应用效果 if (level.getGameTime() % 80L == 0L) { int lastLevel = blockEntity.levels; - blockEntity.levels = updateBase(level, posX, posY, posZ); + blockEntity.levels = CorruptedBeaconBlockEntity.updateBase(level, posX, posY, posZ); if (!level.isClientSide()) { boolean shouldLit = blockEntity.levels > 0; boolean isCurrentlyLit = state.hasProperty(CorruptedBeaconBlock.LIT) && state.getValue(CorruptedBeaconBlock.LIT); if (shouldLit && !isCurrentlyLit) { - setBeaconStatus(level, pos, state, blockEntity, true); + CorruptedBeaconBlockEntity.setBeaconStatus(level, pos, state, blockEntity, true); } else if (lastLevel > 0 && !shouldLit) { blockEntity.levels = 0; - setBeaconStatus(level, pos, state, blockEntity, false); + CorruptedBeaconBlockEntity.setBeaconStatus(level, pos, state, blockEntity, false); } } // 信标有效时播放音效并影响实体 if (blockEntity.levels > 0) { - playSound(level, pos, SoundEvents.BEACON_AMBIENT); - affectEntities(level, pos, blockEntity.checkingBeamHeight); + CorruptedBeaconBlockEntity.playSound(level, pos, SoundEvents.BEACON_AMBIENT); + CorruptedBeaconBlockEntity.affectEntities(level, pos, blockEntity.checkingBeamHeight); } } @@ -139,7 +139,7 @@ public static void setBeaconStatus(Level level, BlockPos pos, BlockState state, level.setBlockAndUpdate(pos, state.setValue(CorruptedBeaconBlock.LIT, status)); if (status) { - playSound(level, pos, SoundEvents.BEACON_ACTIVATE); + CorruptedBeaconBlockEntity.playSound(level, pos, SoundEvents.BEACON_ACTIVATE); List players = level.getEntitiesOfClass( ServerPlayer.class, new AABB(pos).inflate(0.0, -4.0, 0.0).inflate(10.0, 5.0, 10.0) @@ -149,7 +149,7 @@ public static void setBeaconStatus(Level level, BlockPos pos, BlockState state, CriteriaTriggers.CONSTRUCT_BEACON.trigger(serverplayer, entity.levels); } } else { - playSound(level, pos, SoundEvents.BEACON_DEACTIVATE); + CorruptedBeaconBlockEntity.playSound(level, pos, SoundEvents.BEACON_DEACTIVATE); } } @@ -176,7 +176,7 @@ private static int updateBase(Level level, int x, int y, int z) { @Override public void setRemoved() { if (this.level == null) return; - playSound(this.level, this.worldPosition, SoundEvents.BEACON_DEACTIVATE); + CorruptedBeaconBlockEntity.playSound(this.level, this.worldPosition, SoundEvents.BEACON_DEACTIVATE); super.setRemoved(); } @@ -224,7 +224,7 @@ private static void affectEntities(Level level, BlockPos pos, int beamTopY) { for (LivingEntity livingEntity : list) { if (!livingEntity.isAlive()) return; livingEntity.addEffect(new MobEffectInstance(MobEffects.WITHER, 120, 0, true, true)); - tryTransformEntity(livingEntity, (ServerLevel) level, manager); + CorruptedBeaconBlockEntity.tryTransformEntity(livingEntity, (ServerLevel) level, manager); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeCrateBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeCrateBlockEntity.java index c12b967fc8..83ea4bbfa4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeCrateBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeCrateBlockEntity.java @@ -111,7 +111,7 @@ public boolean onPlayerUse(Player player) { if (held.isEmpty()) return false; if (!this.level.isClientSide()) { this.itemHandler.setStack(held.copyWithCount(1)); - setChanged(); + this.setChanged(); this.sendUpdate(); } return true; @@ -121,7 +121,7 @@ public boolean onPlayerUse(Player player) { if (!this.level.isClientSide()) { player.getInventory().placeItemBackInInventory(this.itemHandler.getStack()); this.itemHandler.setStack(ItemStack.EMPTY); - setChanged(); + this.setChanged(); this.sendUpdate(); } return true; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeGeneratorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeGeneratorBlockEntity.java index fd5bb138e5..e54fc216f6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeGeneratorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/CreativeGeneratorBlockEntity.java @@ -28,7 +28,7 @@ @Getter public class CreativeGeneratorBlockEntity extends BlockEntity implements IPowerProducer, IPowerConsumer, MenuProvider { - private PowerGrid grid = null; + private @Nullable PowerGrid grid; private int power = 16; @@ -108,7 +108,7 @@ public AbstractContainerMenu createMenu(int i, Inventory inventory, Player playe public void setPower(int power) { this.power = power; - if (level instanceof ServerLevel) { + if (this.level instanceof ServerLevel) { if (this.grid != null) { this.grid.markChanged(); return; @@ -118,7 +118,7 @@ public void setPower(int power) { } public void tick() { - if (level instanceof ServerLevel) { + if (this.level instanceof ServerLevel) { if (this.previousSyncFailed && this.grid != null) { this.previousSyncFailed = false; this.grid.markChanged(); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/DeflectionRingBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/DeflectionRingBlockEntity.java index 6552aef9e0..f4f170b3cd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/DeflectionRingBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/DeflectionRingBlockEntity.java @@ -53,7 +53,7 @@ public class DeflectionRingBlockEntity extends BlockEntity implements IPowerCons private static final HashMap LEVEL_DEFLECTION_BLOCK_MAP = new HashMap<>(); @Getter @Setter - private PowerGrid grid; + private @Nullable PowerGrid grid; @Setter @Getter @@ -77,13 +77,13 @@ public static DeflectionRingBlockEntity createBlockEntity(BlockEntityType typ } public static Iterable getAllBlocks(Level level) { - RingIndex index = LEVEL_DEFLECTION_BLOCK_MAP.get(level); + RingIndex index = DeflectionRingBlockEntity.LEVEL_DEFLECTION_BLOCK_MAP.get(level); return index == null ? List.of() : index.positions; } public static boolean isInsideWorkingRing(Entity entity) { Level level = entity.level(); - RingIndex index = LEVEL_DEFLECTION_BLOCK_MAP.get(level); + RingIndex index = DeflectionRingBlockEntity.LEVEL_DEFLECTION_BLOCK_MAP.get(level); if (index == null) return false; AABB boundingBox = entity.getBoundingBox(); int minChunkX = Mth.floor(boundingBox.minX) >> 4; @@ -92,8 +92,9 @@ public static boolean isInsideWorkingRing(Entity entity) { int maxChunkZ = Mth.floor(boundingBox.maxZ) >> 4; for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) { for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) { - HashSet positions = index.byChunk.get(ChunkPos.pack(chunkX, chunkZ)); - if (positions == null) continue; + long chunkKey = ChunkPos.pack(chunkX, chunkZ); + if (!index.byChunk.containsKey(chunkKey)) continue; + HashSet positions = index.byChunk.get(chunkKey); for (BlockPos pos : positions) { BlockState state = level.getBlockState(pos); if (!(state.getBlock() instanceof DeflectionRingBlock)) continue; @@ -112,7 +113,7 @@ public static boolean isInsideWorkingRing(Entity entity) { public static BlockPos findFirstRing(Entity entity, Vec3 start, Vec3 movement) { double movementSqr = movement.lengthSqr(); if (!Double.isFinite(movementSqr) || movementSqr < 1.0E-12) return null; - RingIndex index = LEVEL_DEFLECTION_BLOCK_MAP.get(entity.level()); + RingIndex index = DeflectionRingBlockEntity.LEVEL_DEFLECTION_BLOCK_MAP.get(entity.level()); if (index == null) return null; BlockPos nearestRing = null; @@ -147,8 +148,8 @@ public static BlockPos findFirstRing(Entity entity, Vec3 start, Vec3 movement) { for (int candidateChunkZ = chunkZ - 1; candidateChunkZ <= chunkZ + 1; candidateChunkZ++) { long chunkKey = ChunkPos.pack(candidateChunkX, candidateChunkZ); if (checkedChunks != null && !checkedChunks.add(chunkKey)) continue; + if (!index.byChunk.containsKey(chunkKey)) continue; HashSet positions = index.byChunk.get(chunkKey); - if (positions == null) continue; for (BlockPos pos : positions) { BlockState state = entity.level().getBlockState(pos); if (!(state.getBlock() instanceof DeflectionRingBlock) @@ -160,7 +161,7 @@ public static BlockPos findFirstRing(Entity entity, Vec3 start, Vec3 movement) { double progress = toCenter.dot(movement) / movementSqr; if (progress <= 0 || progress > 1 || progress >= nearestProgress) continue; Vec3 closest = start.add(movement.scale(progress)); - if (closest.distanceToSqr(pos.getCenter()) <= DEFLECTION_RADIUS_SQR) { + if (closest.distanceToSqr(pos.getCenter()) <= DeflectionRingBlockEntity.DEFLECTION_RADIUS_SQR) { nearestProgress = progress; nearestRing = pos; } @@ -185,34 +186,43 @@ public static BlockPos findFirstRing(Entity entity, Vec3 start, Vec3 movement) { } public static void clear(Level level) { - LEVEL_DEFLECTION_BLOCK_MAP.remove(level); + DeflectionRingBlockEntity.LEVEL_DEFLECTION_BLOCK_MAP.remove(level); } private void addSelfToMap() { + Level level = this.level; if (level == null) return; - LEVEL_DEFLECTION_BLOCK_MAP.computeIfAbsent(level, ignored -> new RingIndex()).add(getBlockPos()); + DeflectionRingBlockEntity.LEVEL_DEFLECTION_BLOCK_MAP + .computeIfAbsent(level, ignored -> new RingIndex()) + .add(this.getBlockPos()); } private void removeSelfFromMap() { + Level level = this.level; if (level == null) return; - RingIndex index = LEVEL_DEFLECTION_BLOCK_MAP.get(level); + RingIndex index = DeflectionRingBlockEntity.LEVEL_DEFLECTION_BLOCK_MAP.get(level); if (index == null) return; - index.remove(getBlockPos()); - if (index.positions.isEmpty()) LEVEL_DEFLECTION_BLOCK_MAP.remove(level); + index.remove(this.getBlockPos()); + if (index.positions.isEmpty()) DeflectionRingBlockEntity.LEVEL_DEFLECTION_BLOCK_MAP.remove(level); } private void updateLastEntitySpeed(Double speed) { this.resetEntitySpeedTickCounter = 0; this.lastEntitySpeed = speed; - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); + Level level = this.level; if (level == null) return; if (!(state.getBlock() instanceof DeflectionRingBlock block)) return; - block.forEachPart(level, getBlockPos(), it -> level.updateNeighbourForOutputSignal(it, level.getBlockState(it).getBlock())); + block.forEachPart( + level, + this.getBlockPos(), + it -> level.updateNeighbourForOutputSignal(it, level.getBlockState(it).getBlock()) + ); if (!(level instanceof ServerLevel serverLevel)) return; PacketDistributor.sendToPlayersTrackingChunk( serverLevel, - ChunkPos.containing(getBlockPos()), - new DeflectionRingUpdateLastSpeedPacket(getBlockPos(), this.lastEntitySpeed) + ChunkPos.containing(this.getBlockPos()), + new DeflectionRingUpdateLastSpeedPacket(this.getBlockPos(), this.lastEntitySpeed) ); } @@ -235,19 +245,19 @@ public void loadAdditional(ValueInput input) { @Override public @Nullable Level getCurrentLevel() { - return level; + return this.level; } @Override public BlockPos getPos() { - return getBlockPos(); + return this.getBlockPos(); } @Override public PowerComponentType getComponentType() { - if (level == null) return PowerComponentType.INVALID; - if (!level.getBlockState(getBlockPos()).hasProperty(DeflectionRingBlock.HALF)) return PowerComponentType.INVALID; - if (level.getBlockState(getBlockPos()).getValue(DeflectionRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) { + if (this.level == null) return PowerComponentType.INVALID; + if (!this.level.getBlockState(this.getBlockPos()).hasProperty(DeflectionRingBlock.HALF)) return PowerComponentType.INVALID; + if (this.level.getBlockState(this.getBlockPos()).getValue(DeflectionRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) { return PowerComponentType.CONSUMER; } return PowerComponentType.INVALID; @@ -259,38 +269,44 @@ public int getRange() { } public boolean isWork() { - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); return state.getValue(DeflectionRingBlock.SWITCH) == Switch.ON && !state.getValue(DeflectionRingBlock.OVERLOAD); } public void tick() { - if (level == null) return; - if (this.resetEntitySpeedTickCounter >= 40 && !level.isClientSide()) this.updateLastEntitySpeed(0.0); + if (this.level == null) return; + if (this.resetEntitySpeedTickCounter >= 40 && !this.level.isClientSide()) this.updateLastEntitySpeed(0.0); else this.resetEntitySpeedTickCounter++; if (this.overSpeed && this.overSpeedTick > 1) { this.overSpeed = false; this.overSpeedTick = 0; - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); if (!(state.getBlock() instanceof DeflectionRingBlock block)) return; - block.updateState(level, getBlockPos(), DeflectionRingBlock.OVERLOAD, state.getValue(DeflectionRingBlock.OVERLOAD), 3); + block.updateState( + this.level, + this.getBlockPos(), + DeflectionRingBlock.OVERLOAD, + state.getValue(DeflectionRingBlock.OVERLOAD), + 3 + ); } else if (this.overSpeed) { this.overSpeedTick++; } - if (level.isClientSide()) { - if (!getBlockState().getValue(DeflectionRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) return; + if (this.level.isClientSide()) { + if (!this.getBlockState().getValue(DeflectionRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) return; if (this.isWork()) { this.addSelfToMap(); this.accelerate(); } else this.removeSelfFromMap(); } if (this.grid == null) return; - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); if (!state.getValue(DeflectionRingBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) return; if (!(state.getBlock() instanceof DeflectionRingBlock block)) return; if (this.grid.isWorking() && state.getValue(DeflectionRingBlock.OVERLOAD)) { - block.updateState(level, getBlockPos(), DeflectionRingBlock.OVERLOAD, false, 3); + block.updateState(this.level, this.getBlockPos(), DeflectionRingBlock.OVERLOAD, false, 3); } else if (!this.grid.isWorking() && !state.getValue(DeflectionRingBlock.OVERLOAD)) { - block.updateState(level, getBlockPos(), DeflectionRingBlock.OVERLOAD, true, 3); + block.updateState(this.level, this.getBlockPos(), DeflectionRingBlock.OVERLOAD, true, 3); } if (!this.isWork()) { this.removeSelfFromMap(); @@ -309,19 +325,25 @@ public void accelerate() { && block.isChannelWaterlogged(this.level, this.getBlockPos(), ringState); List entities2 = this.level.getEntitiesOfClass( Entity.class, - new AABB(getBlockPos()), + new AABB(this.getBlockPos()), AccelerateManager::canBeAccelerated ); for (Entity entity : entities2) { entity.setDeltaMovement(AccelerateManager.clampMovement(entity, entity.getDeltaMovement())); if (entity.getDeltaMovement().length() > Integer.MAX_VALUE * 0.99f) { this.overSpeed = true; - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); if (!(state.getBlock() instanceof DeflectionRingBlock block)) return; - block.updateState(this.level, getBlockPos(), DeflectionRingBlock.OVERLOAD, state.getValue(DeflectionRingBlock.OVERLOAD), 3); + block.updateState( + this.level, + this.getBlockPos(), + DeflectionRingBlock.OVERLOAD, + state.getValue(DeflectionRingBlock.OVERLOAD), + 3 + ); } Vec3 v = entity.getDeltaMovement(); - Direction facing = getBlockState().getValue(DeflectionRingBlock.FACING); + Direction facing = this.getBlockState().getValue(DeflectionRingBlock.FACING); v = switch (facing) { case UP -> new Vec3(v.z, 0, -v.x); case DOWN -> new Vec3(-v.z, 0, v.x); @@ -332,7 +354,7 @@ public void accelerate() { }; if (waterloggedChannel) v = AccelerateManager.limitAnvilSpeed(entity, v); Vec3 fixedPos = v.normalize() - .scale(DEFLECTION_EXIT_OFFSET) + .scale(DeflectionRingBlockEntity.DEFLECTION_EXIT_OFFSET) .subtract(AccelerateManager.getMovementOffset(entity)); entity.setDeltaMovement(AccelerateManager.clampMovement(entity, v)); if (entity instanceof Player) { @@ -344,16 +366,16 @@ public void accelerate() { entity.setYRot(Mth.wrapDegrees((float) (Mth.atan2(d2, d0) * 180.0F / (float) Math.PI) - 90.0F)); entity.setYHeadRot(entity.getYRot()); } - Vec3 blockCenter = getBlockPos().getCenter(); + Vec3 blockCenter = this.getBlockPos().getCenter(); entity.setPos(fixedPos.add(blockCenter)); } - Direction.Axis axis = getBlockState().getValue(DeflectionRingBlock.FACING).getAxis(); - BlockPos min = getBlockPos().offset(axis == Direction.Axis.X ? 0 : -1, axis == Direction.Axis.Y ? 0 : -1, + Direction.Axis axis = this.getBlockState().getValue(DeflectionRingBlock.FACING).getAxis(); + BlockPos min = this.getBlockPos().offset(axis == Direction.Axis.X ? 0 : -1, axis == Direction.Axis.Y ? 0 : -1, axis == Direction.Axis.Z ? 0 : -1); - BlockPos max = getBlockPos().offset(axis == Direction.Axis.X ? 0 : 1, axis == Direction.Axis.Y ? 0 : 1, + BlockPos max = this.getBlockPos().offset(axis == Direction.Axis.X ? 0 : 1, axis == Direction.Axis.Y ? 0 : 1, axis == Direction.Axis.Z ? 0 : 1); AABB accelerationArea = AABB.encapsulatingFullBlocks(min, max); - List entities = level.getEntitiesOfClass( + List entities = this.level.getEntitiesOfClass( Entity.class, accelerationArea, AccelerateManager::canBeAccelerated @@ -368,25 +390,25 @@ public void accelerate() { acceleratedMovement = AccelerateManager.limitAnvilSpeed(entity, acceleratedMovement); } entity.setDeltaMovement(acceleratedMovement); - if (level.isClientSide()) continue; + if (this.level.isClientSide()) continue; this.updateLastEntitySpeed(entity.getDeltaMovement().length()); } } @SuppressWarnings("DuplicatedCode") public void attractGianAnvil() { - assert level != null; + assert this.level != null; if ( - level.getBlockState(getBlockPos().below(2)).hasProperty(GiantAnvilBlock.HALF) - && level.getBlockState(getBlockPos().below(2)).getValue(GiantAnvilBlock.HALF) == Cube3x3PartHalf.TOP_CENTER + this.level.getBlockState(this.getBlockPos().below(2)).hasProperty(GiantAnvilBlock.HALF) + && this.level.getBlockState(this.getBlockPos().below(2)).getValue(GiantAnvilBlock.HALF) == Cube3x3PartHalf.TOP_CENTER ) { return; } BlockPos giantAnvilPos = null; BlockPos.MutableBlockPos checkPos = new BlockPos.MutableBlockPos(); - checkPos.set(getBlockPos().below(2)); + checkPos.set(this.getBlockPos().below(2)); for (int y = 0; y < 11; y++) { - BlockState checkState = level.getBlockState(checkPos); + BlockState checkState = this.level.getBlockState(checkPos); if (!checkState.hasProperty(GiantAnvilBlock.HALF)) { checkPos.move(Direction.DOWN); continue; @@ -398,23 +420,23 @@ public void attractGianAnvil() { } checkPos.move(Direction.DOWN); } - Vector2d vector2d = new Vector2d(getBlockPos().getCenter().x, getBlockPos().getCenter().z); - Optional fallingGiantAnvilEntity = level.getEntitiesOfClass(FallingGiantAnvilEntity.class, new AABB( - getBlockPos().getX(), - getBlockPos().getY() - 2, - getBlockPos().getZ(), - getBlockPos().getX() + 1, - getBlockPos().getY() - 12, - getBlockPos().getZ() + 1 + Vector2d vector2d = new Vector2d(this.getBlockPos().getCenter().x, this.getBlockPos().getCenter().z); + Optional fallingGiantAnvilEntity = this.level.getEntitiesOfClass(FallingGiantAnvilEntity.class, new AABB( + this.getBlockPos().getX(), + this.getBlockPos().getY() - 2, + this.getBlockPos().getZ(), + this.getBlockPos().getX() + 1, + this.getBlockPos().getY() - 12, + this.getBlockPos().getZ() + 1 )).stream() - .sorted((e1, e2) -> new DistanceComparator(getBlockPos().getCenter()).compare(e1.position(), e2.position())) + .sorted((e1, e2) -> new DistanceComparator(this.getBlockPos().getCenter()).compare(e1.position(), e2.position())) .filter(entity -> vector2d.distance(entity.position().x, entity.position().z) <= 0.25) .findFirst(); if (fallingGiantAnvilEntity.isPresent()) { if ( giantAnvilPos != null - && fallingGiantAnvilEntity.get().position().distanceTo(getBlockPos().getCenter()) - < giantAnvilPos.getCenter().distanceTo(getBlockPos().getCenter()) + && fallingGiantAnvilEntity.get().position().distanceTo(this.getBlockPos().getCenter()) + < giantAnvilPos.getCenter().distanceTo(this.getBlockPos().getCenter()) ) { giantAnvilPos = BlockPos.containing(fallingGiantAnvilEntity.get().position()); } else if (giantAnvilPos == null) { @@ -424,10 +446,10 @@ public void attractGianAnvil() { if (giantAnvilPos == null) return; checkPos.set(giantAnvilPos); checkPos.move(-1, 2, -1); - while (checkPos.getY() < getBlockPos().getY() - 1) { + while (checkPos.getY() < this.getBlockPos().getY() - 1) { for (int x = -1; x < 2; x++) { for (int z = -1; z < 2; z++) { - BlockState checked = level.getBlockState(checkPos); + BlockState checked = this.level.getBlockState(checkPos); if (!checked.canBeReplaced()) return; checkPos.move(0, 0, 1); } @@ -436,13 +458,13 @@ public void attractGianAnvil() { } checkPos.move(-3, 1, 0); } - Block block = level.getBlockState(giantAnvilPos.below()).getBlock(); + Block block = this.level.getBlockState(giantAnvilPos.below()).getBlock(); if (block instanceof GiantAnvilBlock giantAnvilBlock) { - giantAnvilBlock.removePartsAndUpdate(level, giantAnvilPos.below()); + giantAnvilBlock.removePartsAndUpdate(this.level, giantAnvilPos.below()); } - BlockPos newPos = getBlockPos().below(4); + BlockPos newPos = this.getBlockPos().below(4); for (Cube3x3PartHalf part : Cube3x3PartHalf.values()) { - level.setBlockAndUpdate(newPos.offset(part.getOffset()), ModBlocks.GIANT_ANVIL.getDefaultState() + this.level.setBlockAndUpdate(newPos.offset(part.getOffset()), ModBlocks.GIANT_ANVIL.getDefaultState() .setValue(GiantAnvilBlock.HALF, part) .setValue(GiantAnvilBlock.CUBE, part.equals(Cube3x3PartHalf.MID_CENTER) ? GiantAnvilCube.CENTER : GiantAnvilCube.CORNER) ); @@ -452,7 +474,7 @@ public void attractGianAnvil() { @Override public int getInputPower() { - return getBlockState().getValue(DeflectionRingBlock.SWITCH) == Switch.ON ? 256 : 0; + return this.getBlockState().getValue(DeflectionRingBlock.SWITCH) == Switch.ON ? 256 : 0; } @Override @@ -475,8 +497,8 @@ private void add(BlockPos pos) { private void remove(BlockPos pos) { if (!this.positions.remove(pos)) return; long chunkKey = ChunkPos.pack(pos.getX() >> 4, pos.getZ() >> 4); + if (!this.byChunk.containsKey(chunkKey)) return; HashSet chunkPositions = this.byChunk.get(chunkKey); - if (chunkPositions == null) return; chunkPositions.remove(pos); if (chunkPositions.isEmpty()) this.byChunk.remove(chunkKey); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/DischargerBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/DischargerBlockEntity.java index f9e48c9085..c7f7b016a1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/DischargerBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/DischargerBlockEntity.java @@ -130,7 +130,7 @@ public boolean containsValidItem(ItemResource resource) { // 检查FE放电能力 ItemStack stack = resource.toStack(); if (stack.isEmpty()) return false; - EnergyHandler energyHandler = Capabilities.Energy.ITEM.getCapability(stack, ItemAccess.forStack(stack)); + EnergyHandler energyHandler = stack.getCapability(Capabilities.Energy.ITEM, ItemAccess.forStack(stack)); if (energyHandler == null) return false; return energyHandler.getAmountAsInt() > 0; } @@ -173,7 +173,7 @@ private void moveItemToTransformingSlot() { // FE放电:物品有可抽取的FE时开始放电 ItemStack stack = this.itemHandler.getStacks().get(0).copy(); - EnergyHandler energyHandler = Capabilities.Energy.ITEM.getCapability(stack, ItemAccess.forStack(stack)); + EnergyHandler energyHandler = stack.getCapability(Capabilities.Energy.ITEM, ItemAccess.forStack(stack)); if (energyHandler != null && energyHandler.getAmountAsInt() > 0) { this.isFeDischarging = true; this.itemHandler.set(0, ItemResource.EMPTY, 0); @@ -387,8 +387,8 @@ public void tick(Level level, BlockPos blockPos) { if (this.isFeDischarging) { ItemStack processingStack = this.itemHandler.getStacks().get(1); if (!processingStack.isEmpty()) { - EnergyHandler storage = Capabilities.Energy.ITEM.getCapability( - processingStack, ItemAccess.forStack(processingStack)); + EnergyHandler storage = processingStack.getCapability( + Capabilities.Energy.ITEM, ItemAccess.forStack(processingStack)); if (storage != null) { int currentEnergy = storage.getAmountAsInt(); if (currentEnergy <= 0) { @@ -399,7 +399,7 @@ public void tick(Level level, BlockPos blockPos) { } else { try (var transaction = Transaction.openRoot()) { int extracted = storage.extract( - Math.min(FE_EXTRACT_PER_TICK, currentEnergy), transaction); + Math.min(DischargerBlockEntity.FE_EXTRACT_PER_TICK, currentEnergy), transaction); transaction.commit(); this.powerValue = (int) (extracted * (1 - AnvilCraft.CONFIG.powerConverter.powerConverterLoss) @@ -442,6 +442,9 @@ public PowerComponentInfo toPowerComponentInfo() { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); - Containers.dropContents(this.level, pos, this.getFilteredItemStackHandler().getStacks()); + Level level = this.level; + if (level != null) { + Containers.dropContents(level, pos, this.getFilteredItemStackHandler().getStacks()); + } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ExpCollectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ExpCollectorBlockEntity.java index 412b4420f4..89db9b109c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ExpCollectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ExpCollectorBlockEntity.java @@ -91,7 +91,7 @@ public class ExpCollectorBlockEntity extends BlockEntity 10, 60 ); - private final CapacityModifiableFluidHandler tank = new CapacityModifiableFluidHandler(1, CAPACITY) { + private final CapacityModifiableFluidHandler tank = new CapacityModifiableFluidHandler(1, ExpCollectorBlockEntity.CAPACITY) { @Override public boolean isValid(int index, FluidResource resource) { return resource.getFluid() == ModFluids.EXP_FLUID.get(); @@ -177,7 +177,7 @@ public void setRemoved() { if (this.level != null && !this.level.isClientSide()) { FluidNetworkManager.INSTANCE.removeContainer(this.level, this.getBlockPos()); } - removePoachingCollector(this); + ExpCollectorBlockEntity.removePoachingCollector(this); super.setRemoved(); } @@ -305,9 +305,9 @@ public void tick(Level level, BlockPos blockPos) { if (this.cooldown.get() != this.oldCooldown) { this.oldCooldown = this.cooldown.get(); if (this.oldCooldown == 0) { - addPoachingCollector(this); + ExpCollectorBlockEntity.addPoachingCollector(this); } else { - removePoachingCollector(this); + ExpCollectorBlockEntity.removePoachingCollector(this); } } if (this.rangeRadius.get() != this.oldRange || this.boundingBox == null) { @@ -349,7 +349,7 @@ public BlockPos getPos() { @Override public int getInputPower() { - int power = POWER_CONSUMPTION[this.cooldown.index()][this.rangeRadius.index()]; + int power = ExpCollectorBlockEntity.POWER_CONSUMPTION[this.cooldown.index()][this.rangeRadius.index()]; if (this.level == null) return power; return this.getBlockState().getValue(ExpCollectorBlock.POWERED) ? 0 : power; } @@ -394,7 +394,7 @@ public List getDiskCompatibleGroups() { public int getRedstoneSignal() { int amount = this.tank.getAmountAsInt(0); - int strength = amount == 0 ? 0 : amount * 14 / CAPACITY + 1; + int strength = amount == 0 ? 0 : amount * 14 / ExpCollectorBlockEntity.CAPACITY + 1; return Mth.clamp(strength, 0, 15); } @@ -412,35 +412,43 @@ public AABB shape() { } public static void clearPoachingCollectors() { - POACHING_COLLECTORS.clear(); - } - - private static Set getOrCreateCollectorList(ExpCollectorBlockEntity collector) { - return getOrCreateCollectorList(collector.level, ChunkPos.containing(collector.worldPosition)); + ExpCollectorBlockEntity.POACHING_COLLECTORS.clear(); } private static Set getOrCreateCollectorList(Level level, ChunkPos chunkPos) { - Set collectors = POACHING_COLLECTORS.get(level, chunkPos); + Set collectors = ExpCollectorBlockEntity.POACHING_COLLECTORS.get(level, chunkPos); if (collectors == null) { collectors = new HashSet<>(); - POACHING_COLLECTORS.put(level, chunkPos, collectors); + ExpCollectorBlockEntity.POACHING_COLLECTORS.put(level, chunkPos, collectors); } return collectors; } private static void addPoachingCollector(ExpCollectorBlockEntity collector) { - if (collector.level != null) getOrCreateCollectorList(collector).add(collector); + Level level = collector.level; + if (level != null) { + ExpCollectorBlockEntity.getOrCreateCollectorList( + level, + ChunkPos.containing(collector.worldPosition) + ).add(collector); + } } private static void removePoachingCollector(ExpCollectorBlockEntity collector) { - if (collector.level != null) getOrCreateCollectorList(collector).remove(collector); + Level level = collector.level; + if (level != null) { + ExpCollectorBlockEntity.getOrCreateCollectorList( + level, + ChunkPos.containing(collector.worldPosition) + ).remove(collector); + } } public static boolean poachExperienceOrb(ExperienceOrb orb) { ChunkPos currentPos = ChunkPos.containing(orb.blockPosition()); for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { - Set collectors = POACHING_COLLECTORS.get( + Set collectors = ExpCollectorBlockEntity.POACHING_COLLECTORS.get( orb.level(), new ChunkPos(currentPos.x() + x, currentPos.z() + z) ); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/FeCollectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/FeCollectorBlockEntity.java index 4246835f93..284e8a144d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/FeCollectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/FeCollectorBlockEntity.java @@ -110,7 +110,7 @@ public void onDataPacket(Connection connection, ValueInput input) { } Direction[] getConnectedSides() { - Direction.Axis a = getBlockState().getValue(BlockStateProperties.HORIZONTAL_AXIS); + Direction.Axis a = this.getBlockState().getValue(BlockStateProperties.HORIZONTAL_AXIS); return a == Direction.Axis.X ? new Direction[]{Direction.EAST, Direction.WEST} : new Direction[]{Direction.NORTH, Direction.SOUTH}; @@ -136,43 +136,43 @@ public static void tick(Level level, BlockPos pos, BlockState state, FeCollector } void serverTick() { - if (level == null) return; + if (this.level == null) return; - if (this.energy >= PRODUCE_THRESHOLD) { + if (this.energy >= FeCollectorBlockEntity.PRODUCE_THRESHOLD) { this.producing = true; - } else if (this.energy < STOP_THRESHOLD) { + } else if (this.energy < FeCollectorBlockEntity.STOP_THRESHOLD) { this.producing = false; } - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); if (state.getValue(FeCollectorBlock.POWERED) != this.producing) { - level.setBlockAndUpdate(getBlockPos(), state.setValue(FeCollectorBlock.POWERED, this.producing)); + this.level.setBlockAndUpdate(this.getBlockPos(), state.setValue(FeCollectorBlock.POWERED, this.producing)); } if (this.producing) { - this.energy -= FE_PER_TICK; + this.energy -= FeCollectorBlockEntity.FE_PER_TICK; this.time++; - setChanged(); + this.setChanged(); this.clientSyncDirty = true; } - if (this.energy > TRANSFER_THRESHOLD) { + if (this.energy > FeCollectorBlockEntity.TRANSFER_THRESHOLD) { this.pushExcess(); } - if (this.clientSyncDirty && level.getGameTime() % 20 == 0) { - level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); + if (this.clientSyncDirty && this.level.getGameTime() % 20 == 0) { + this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), Block.UPDATE_ALL); this.clientSyncDirty = false; } } void pushExcess() { - if (level == null) return; - int excess = this.energy - TRANSFER_THRESHOLD; + if (this.level == null) return; + int excess = this.energy - FeCollectorBlockEntity.TRANSFER_THRESHOLD; if (excess <= 0) return; for (Direction side : this.getConnectedSides()) { if (excess <= 0) break; - EnergyHandler target = level.getCapability( - Capabilities.Energy.BLOCK, getBlockPos().relative(side), side.getOpposite() + EnergyHandler target = this.level.getCapability( + Capabilities.Energy.BLOCK, this.getBlockPos().relative(side), side.getOpposite() ); if (target != null) { try (Transaction transaction = Transaction.openRoot()) { @@ -181,7 +181,7 @@ Capabilities.Energy.BLOCK, getBlockPos().relative(side), side.getOpposite() if (accepted > 0) { excess -= accepted; this.energy -= accepted; - setChanged(); + this.setChanged(); this.clientSyncDirty = true; } } @@ -230,13 +230,13 @@ public AABB shape() { @Override public void gridTick() { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; final int prev = this.outputPower; if (this.producing) { - this.outputPower = (int) (FE_PER_TICK * 20 - * (1 - AnvilCraft.CONFIG.powerConverter.powerConverterLoss) - / AnvilCraft.CONFIG.powerConverter.powerConverterEfficiency); + this.outputPower = (int) (FeCollectorBlockEntity.FE_PER_TICK * 20 + * (1 - AnvilCraft.CONFIG.powerConverter.powerConverterLoss) + / AnvilCraft.CONFIG.powerConverter.powerConverterEfficiency); if (this.outputPower != prev && this.grid != null) this.grid.markChanged(); } else if (this.outputPower > 0) { this.outputPower = 0; @@ -268,14 +268,14 @@ public long getAmountAsLong() { @Override public long getCapacityAsLong() { - return MAX_ENERGY; + return FeCollectorBlockEntity.MAX_ENERGY; } @Override public int insert(int maxInsert, TransactionContext transaction) { if (!this.isInputSide()) return 0; - if (FeCollectorBlockEntity.this.energy >= MAX_ENERGY) return 0; - int r = Math.min(MAX_ENERGY - FeCollectorBlockEntity.this.energy, maxInsert); + if (FeCollectorBlockEntity.this.energy >= FeCollectorBlockEntity.MAX_ENERGY) return 0; + int r = Math.min(FeCollectorBlockEntity.MAX_ENERGY - FeCollectorBlockEntity.this.energy, maxInsert); if (r > 0) { FeCollectorBlockEntity.this.energy += r; if (this.side != null @@ -283,7 +283,7 @@ public int insert(int maxInsert, TransactionContext transaction) { ) { FeCollectorBlockEntity.this.lastInputSide = this.side; } - setChanged(); + FeCollectorBlockEntity.this.setChanged(); FeCollectorBlockEntity.this.clientSyncDirty = true; } return r; @@ -296,7 +296,7 @@ public int extract(int maxExtract, TransactionContext transaction) { int r = Math.min(FeCollectorBlockEntity.this.energy, maxExtract); if (r > 0) { FeCollectorBlockEntity.this.energy -= r; - setChanged(); + FeCollectorBlockEntity.this.setChanged(); FeCollectorBlockEntity.this.clientSyncDirty = true; } return r; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/FishTankBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/FishTankBlockEntity.java index 7072bbbf81..f6309173e4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/FishTankBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/FishTankBlockEntity.java @@ -127,7 +127,7 @@ public void clear() { super.clear(); } }; - private AABB fluidContentArea = new AABB(FLUID_CONTENT_AREA_MIN, FLUID_CONTENT_AREA_MAX); + private AABB fluidContentArea = new AABB(FishTankBlockEntity.FLUID_CONTENT_AREA_MIN, FishTankBlockEntity.FLUID_CONTENT_AREA_MAX); private final FluidStackResourceHandler fluidHandler = new FluidStackResourceHandler() { @Override protected void onContentChanged(FluidStack original) { @@ -145,7 +145,7 @@ protected void onContentChanged(FluidStack original) { private void updateContentArea() { double diffY = FishTankBlockEntity.FLUID_CONTENT_AREA_HEIGHT * (1.0 - (double) this.getFill()); - Vec3 pos = getBlockPos().getBottomCenter().subtract(0.5, 0, 0.5); + Vec3 pos = FishTankBlockEntity.this.getBlockPos().getBottomCenter().subtract(0.5, 0, 0.5); FishTankBlockEntity.this.fluidContentArea = new AABB( FishTankBlockEntity.FLUID_CONTENT_AREA_MIN.add(pos), FishTankBlockEntity.FLUID_CONTENT_AREA_MAX.subtract(0, diffY, 0).add(pos) @@ -223,7 +223,7 @@ public int insert(int index, ItemResource resource, int amount, TransactionConte @Override public int extract(int index, ItemResource resource, int amount, TransactionContext transaction) { - Objects.checkIndex(index, size()); + Objects.checkIndex(index, this.size()); TransferPreconditions.checkNonEmptyNonNegative(resource, amount); if (resource.equals(this.getResource(index))) { @@ -450,7 +450,7 @@ public ResourceHandler getInput() { @Override public ResourceHandler getOutput() { // 复用输出槽做原料时,配方缓存不能同时把同一个容器当成输出,否则快照会互相覆盖 - return this.processingOutput ? EMPTY_RECIPE_OUTPUT : this.output; + return this.processingOutput ? FishTankBlockEntity.EMPTY_RECIPE_OUTPUT : this.output; } public PollableItemHandler getInputHandler() { @@ -463,10 +463,10 @@ public ItemStacksResourceHandler getOutputHandler() { /// 输入槽为空时,允许本 tick 把输出槽中的产物当作原料再加工一次 public void beginRecipeProcessing() { - boolean hasInput = !isEmpty(this.input); + boolean hasInput = !FishTankBlockEntity.isEmpty(this.input); long gameTime = this.level == null ? Long.MIN_VALUE + 1 : this.level.getGameTime(); this.processingOutput = !hasInput - && !isEmpty(this.output) + && !FishTankBlockEntity.isEmpty(this.output) && gameTime != this.lastRecipeProcessingGameTime; if (hasInput || this.processingOutput) this.lastRecipeProcessingGameTime = gameTime; } @@ -495,7 +495,10 @@ protected void saveAdditional(ValueOutput output) { this.output.serialize(output.child("Outputs")); output.putBoolean("ignited", this.ignited); - ValueOutput.TypedOutputList list = output.list(TAG_TROPICAL_FISH_DATA, TropicalFishData.CODEC.codec()); + ValueOutput.TypedOutputList list = output.list( + FishTankBlockEntity.TAG_TROPICAL_FISH_DATA, + TropicalFishData.CODEC.codec() + ); for (TropicalFishData fishTag : this.fishes) { list.add(fishTag); } @@ -510,7 +513,7 @@ protected void loadAdditional(ValueInput input) { this.ignited = input.getBooleanOr("ignited", false); this.fishes.clear(); - for (TropicalFishData fishTag : input.listOrEmpty(TAG_TROPICAL_FISH_DATA, TropicalFishData.CODEC.codec())) { + for (TropicalFishData fishTag : input.listOrEmpty(FishTankBlockEntity.TAG_TROPICAL_FISH_DATA, TropicalFishData.CODEC.codec())) { this.fishes.add(fishTag); } } @@ -525,7 +528,10 @@ public CompoundTag getUpdateTag(HolderLookup.Provider registries) { this.output.serialize(output.child("Outputs")); output.putBoolean("ignited", this.ignited); - ValueOutput.TypedOutputList list = output.list(TAG_TROPICAL_FISH_DATA, TropicalFishData.CODEC.codec()); + ValueOutput.TypedOutputList list = output.list( + FishTankBlockEntity.TAG_TROPICAL_FISH_DATA, + TropicalFishData.CODEC.codec() + ); for (TropicalFishData fishTag : this.fishes) { list.add(fishTag); } @@ -684,7 +690,7 @@ public void tryAutoOutputResults() { ); if (targets == null || targets.isEmpty()) { // 开口被有碰撞的方块堵住时不输出,物品留在输出槽等待下次重试 - if (isOutletBlocked(level, pos, outletDir)) return; + if (FishTankBlockEntity.isOutletBlocked(level, pos, outletDir)) return; for (int i = 0; i < 8; i++) { try (Transaction transaction = Transaction.openRoot()) { ItemResource resource = this.output.getResource(i); @@ -1055,7 +1061,7 @@ public void updateFishState() { if (this.isEmptyOfFish() && this.getBlockState().getValue(FishTankBlock.TROPICAL)) { this.level.setBlock(this.getBlockPos(), this.getBlockState().setValue(FishTankBlock.TROPICAL, false), 18); - } else if (!this.isEmptyOfFish() && !getBlockState().getValue(FishTankBlock.TROPICAL)) { + } else if (!this.isEmptyOfFish() && !this.getBlockState().getValue(FishTankBlock.TROPICAL)) { this.level.setBlock(this.getBlockPos(), this.getBlockState().setValue(FishTankBlock.TROPICAL, true), 18); } } @@ -1072,7 +1078,7 @@ public void dropAllFishes() { } public boolean isFullOfFish() { - return this.fishes.size() >= MAX_TROPICAL_FISH; + return this.fishes.size() >= FishTankBlockEntity.MAX_TROPICAL_FISH; } public boolean isEmptyOfFish() { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/FluidTankBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/FluidTankBlockEntity.java index c9995f40c4..4e37051a7a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/FluidTankBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/FluidTankBlockEntity.java @@ -43,8 +43,8 @@ public class FluidTankBlockEntity extends BlockEntity implements IFluidResourceH private static final int CHECK_INTERVAL = 100; private final SingleFluidTankHandler tank = new SingleFluidTankHandler( - BASE_CAPACITY, - INFINITY_THRESHOLD, + FluidTankBlockEntity.BASE_CAPACITY, + FluidTankBlockEntity.INFINITY_THRESHOLD, this::onTankChanged ); private int tickCounter; @@ -78,7 +78,7 @@ public void onUnformed() { } public static void serverTick(Level level, BlockPos pos, BlockState state, FluidTankBlockEntity entity) { - if (level.isClientSide() || ++entity.tickCounter % CHECK_INTERVAL != 0) return; + if (level.isClientSide() || ++entity.tickCounter % FluidTankBlockEntity.CHECK_INTERVAL != 0) return; boolean valid = TankUtil.isMengerStructure(level, pos, 3); if (entity.tank.isEnhanced() && !valid) { entity.onUnformed(); @@ -131,6 +131,7 @@ public Packet getUpdatePacket() { } @Override + @SuppressWarnings("deprecation") public void removeComponentsFromTag(ValueOutput output) { super.removeComponentsFromTag(output); output.discard("Tank"); @@ -149,15 +150,15 @@ public void saveToDrop(ItemStack stack, HolderLookup.Provider registries) { public static boolean isEmptyItem(ItemStack stack, HolderLookup.Provider registries) { if (!stack.is(ModBlocks.FLUID_TANK.asItem())) return false; - return readItemTank(stack, registries).getFluid().isEmpty(); + return FluidTankBlockEntity.readItemTank(stack, registries).getFluid().isEmpty(); } public static ItemStack fillItem(ItemStack stack, FluidStack fluid, HolderLookup.Provider registries) { - if (fluid.isEmpty() || !isEmptyItem(stack, registries)) return ItemStack.EMPTY; + if (fluid.isEmpty() || !FluidTankBlockEntity.isEmptyItem(stack, registries)) return ItemStack.EMPTY; SingleFluidTankHandler itemTank = new SingleFluidTankHandler( - BASE_CAPACITY, - INFINITY_THRESHOLD, + FluidTankBlockEntity.BASE_CAPACITY, + FluidTankBlockEntity.INFINITY_THRESHOLD, () -> {} ); try (Transaction transaction = Transaction.openRoot()) { @@ -175,11 +176,11 @@ public static ItemStack fillItem(ItemStack stack, FluidStack fluid, HolderLookup private static SingleFluidTankHandler readItemTank(ItemStack stack, HolderLookup.Provider registries) { SingleFluidTankHandler itemTank = new SingleFluidTankHandler( - BASE_CAPACITY, - INFINITY_THRESHOLD, + FluidTankBlockEntity.BASE_CAPACITY, + FluidTankBlockEntity.INFINITY_THRESHOLD, () -> {} ); - itemTank.deserialize(TagValueInput.create(ProblemReporter.DISCARDING, registries, getTankData(stack))); + itemTank.deserialize(TagValueInput.create(ProblemReporter.DISCARDING, registries, FluidTankBlockEntity.getTankData(stack))); return itemTank; } @@ -213,6 +214,6 @@ public boolean isInfinite() { } public boolean containsInfiniteFluid() { - return this.tank.getFluidAmount() >= INFINITY_THRESHOLD; + return this.tank.getFluidAmount() >= FluidTankBlockEntity.INFINITY_THRESHOLD; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/HasMobBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/HasMobBlockEntity.java index 0fae59a9c2..d39d65ef36 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/HasMobBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/HasMobBlockEntity.java @@ -81,6 +81,7 @@ private void getEntity(Level level) { Entity entity; if (this.entity == null) { entity = this.createDefaultEntity(level); + if (entity == null) return; this.entity = SavedEntity.fromEntity(entity); } else { entity = this.entity.toEntity(level); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/HeatCollectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/HeatCollectorBlockEntity.java index b144f1ad67..4a8b51583e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/HeatCollectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/HeatCollectorBlockEntity.java @@ -101,7 +101,7 @@ public void setRemoved() { public void clientTick() { if (!this.isWorking()) return; - this.rotation += (float) (Math.log(getServerPower() + 1) * 2.5); + this.rotation += (float) (Math.log(this.getServerPower() + 1) * 2.5); } public boolean isWorking() { @@ -114,7 +114,7 @@ public boolean isWorking() { /// @return 溢出的热能(即未被添加至该收集器的热能) public int inputtingHeat(int num) { if (!this.isWorking()) return num; - int overflow = num - (MAX_OUTPUT_POWER - this.inputtingPower); + int overflow = num - (HeatCollectorBlockEntity.MAX_OUTPUT_POWER - this.inputtingPower); if (overflow < 0) { overflow = 0; } @@ -160,7 +160,7 @@ public BlockPos getPos() { @Override public AABB shape() { - return AABB.ofSize(getBlockPos().getCenter(), 5, 5, 5); + return AABB.ofSize(this.getBlockPos().getCenter(), 5, 5, 5); } public enum WorkResult { @@ -179,7 +179,7 @@ public String getTranslateKey() { } public boolean isWorking() { - return this == SUCCESS; + return this == WorkResult.SUCCESS; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/HeliostatsBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/HeliostatsBlockEntity.java index a32f34c221..a34935e37d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/HeliostatsBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/HeliostatsBlockEntity.java @@ -213,7 +213,7 @@ public String getTranslateKey() { } public boolean isWorking() { - return this == SUCCESS; + return this == WorkResult.SUCCESS; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/InductionLightBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/InductionLightBlockEntity.java index 88a5c6f9ab..7cb504aaec 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/InductionLightBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/InductionLightBlockEntity.java @@ -25,9 +25,9 @@ public class InductionLightBlockEntity extends BlockEntity implements IPowerConsumer, IHasAffectRange { @Getter(AccessLevel.NONE) private int ripeningRangeCache = AnvilCraft.CONFIG.inductionLightBlockRipeningRange; - private AABB ripeningArea; - private AABB blockingArea; - private PowerGrid grid; + private @Nullable AABB ripeningArea; + private @Nullable AABB blockingArea; + private @Nullable PowerGrid grid; public InductionLightBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/InfiniteCollectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/InfiniteCollectorBlockEntity.java index 3fc40675b3..eece10969c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/InfiniteCollectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/InfiniteCollectorBlockEntity.java @@ -51,7 +51,7 @@ public class InfiniteCollectorBlockEntity extends BlockEntity implements IPowerP public InfiniteCollectorBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { super(type, pos, blockState); - for (int i = 0; i < CHARGE_HISTORY_SIZE; i++) { + for (int i = 0; i < InfiniteCollectorBlockEntity.CHARGE_HISTORY_SIZE; i++) { this.charges.add(0); } } @@ -66,7 +66,7 @@ public static InfiniteCollectorBlockEntity createBlockEntity(BlockEntityType @Override public int getRange() { - return RANGE; + return InfiniteCollectorBlockEntity.RANGE; } @Override @@ -95,8 +95,8 @@ protected void loadAdditional(ValueInput input) { for (int charge : input.getIntArray("Charges").orElse(new int[0])) { this.charges.add(charge); } - while (this.charges.size() < CHARGE_HISTORY_SIZE) this.charges.add(0); - while (this.charges.size() > CHARGE_HISTORY_SIZE) this.charges.removeFirst(); + while (this.charges.size() < InfiniteCollectorBlockEntity.CHARGE_HISTORY_SIZE) this.charges.add(0); + while (this.charges.size() > InfiniteCollectorBlockEntity.CHARGE_HISTORY_SIZE) this.charges.removeFirst(); } @Override @@ -116,7 +116,7 @@ public void gridTick() { this.chargeCount = 0; this.refreshChargePower(); } - this.outputPower = BASE_OUTPUT_POWER + this.inputtingHeatPower + this.chargePower; + this.outputPower = InfiniteCollectorBlockEntity.BASE_OUTPUT_POWER + this.inputtingHeatPower + this.chargePower; if (this.outputPower > 0 && this.getBlockState().getBlock() instanceof InfiniteCollectorBlock collector) { collector.activate(this.level, this.getBlockPos(), this.getBlockState()); } @@ -127,7 +127,7 @@ public void gridTick() { private void addCharge(int charge) { this.charges.add(charge); - while (this.charges.size() > CHARGE_HISTORY_SIZE) { + while (this.charges.size() > InfiniteCollectorBlockEntity.CHARGE_HISTORY_SIZE) { this.charges.removeFirst(); } } @@ -166,7 +166,7 @@ public void setRemoved() { public void clientTick() { if (!this.isWorking()) return; - this.rotation += (float) (Math.log(getServerPower() + 1) * 0.5); + this.rotation += (float) (Math.log(this.getServerPower() + 1) * 0.5); } public boolean isWorking() { @@ -217,7 +217,8 @@ public BlockPos getPos() { @Override public AABB shape() { - return AABB.ofSize(getBlockPos().getCenter(), RANGE * 2 + 1, RANGE * 2 + 1, RANGE * 2 + 1); + int diameter = InfiniteCollectorBlockEntity.RANGE * 2 + 1; + return AABB.ofSize(this.getBlockPos().getCenter(), diameter, diameter, diameter); } @Override @@ -261,7 +262,7 @@ public String getTranslateKey() { } public boolean isWorking() { - return this == SUCCESS; + return this == WorkResult.SUCCESS; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemCollectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemCollectorBlockEntity.java index 9d63941313..9dd8318dbb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemCollectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemCollectorBlockEntity.java @@ -101,9 +101,9 @@ public class ItemCollectorBlockEntity extends BlockEntity private final FilteredItemStackHandler itemHandler = new FilteredItemStackHandler(9) { @Override protected void onContentsChanged(int index, ItemStack previousContents) { - if (level == null || level.isClientSide()) return; - flushState(level, getBlockPos()); - level.blockEntityChanged(worldPosition); + if (ItemCollectorBlockEntity.this.level == null || ItemCollectorBlockEntity.this.level.isClientSide()) return; + ItemCollectorBlockEntity.this.flushState(ItemCollectorBlockEntity.this.level, ItemCollectorBlockEntity.this.getBlockPos()); + ItemCollectorBlockEntity.this.level.blockEntityChanged(ItemCollectorBlockEntity.this.worldPosition); ItemCollectorBlockEntity.this.needFlush = true; } }; @@ -127,7 +127,7 @@ public BlockPos getPos() { @Override public void setGrid(@Nullable PowerGrid grid) { if (grid == null && this.grid != null && this.grid.isWorking() && this.level != null) { - this.poachingPowerGraceEndTick = this.level.getGameTime() + POACHING_POWER_GRACE_TICKS; + this.poachingPowerGraceEndTick = this.level.getGameTime() + ItemCollectorBlockEntity.POACHING_POWER_GRACE_TICKS; } this.grid = grid; } @@ -138,14 +138,14 @@ public boolean canPoach() { } public int getPowerConsumption() { - return POWER_CONSUMPTION[this.cooldown.index()][this.rangeRadius.index()]; + return ItemCollectorBlockEntity.POWER_CONSUMPTION[this.cooldown.index()][this.rangeRadius.index()]; } @Override public int getInputPower() { int power = this.getPowerConsumption(); - if (level == null) return power; - return getBlockState().getValue(ItemCollectorBlock.POWERED) ? 0 : power; + if (this.level == null) return power; + return this.getBlockState().getValue(ItemCollectorBlock.POWERED) ? 0 : power; } @Override @@ -156,7 +156,10 @@ public FilteredItemStackHandler getFilteredItemStackHandler() { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); - Containers.dropContents(this.level, pos, this.itemHandler.getStacks()); + Level level = this.level; + if (level != null) { + Containers.dropContents(level, pos, this.itemHandler.getStacks()); + } } @Override @@ -208,14 +211,14 @@ public CompoundTag getUpdateTag(HolderLookup.Provider registries) { @Override public void setRemoved() { super.setRemoved(); - removePoachingCollector(this); + ItemCollectorBlockEntity.removePoachingCollector(this); } @Override public void gridTick() { - if (level == null || level.isClientSide()) return; + if (this.level == null || this.level.isClientSide()) return; - BlockState state = level.getBlockState(getBlockPos()); + BlockState state = this.level.getBlockState(this.getBlockPos()); if (!this.isGridWorking() || state.hasProperty(ItemCollectorBlock.POWERED) && state.getValue(ItemCollectorBlock.POWERED)) { this.resetCooldown(); @@ -226,7 +229,7 @@ public void gridTick() { return; } if (this.boundingBox == null) return; - List itemEntities = level.getEntitiesOfClass(ItemEntity.class, this.boundingBox); + List itemEntities = this.level.getEntitiesOfClass(ItemEntity.class, this.boundingBox); for (ItemEntity itemEntity : itemEntities) { this.acceptItemEntity(itemEntity); } @@ -242,7 +245,7 @@ private void resetCooldown() { } public TriState acceptItemEntity(ItemEntity itemEntity) { - if (!this.canPoach() || getBlockState().getValue(ItemCollectorBlock.POWERED)) { + if (!this.canPoach() || this.getBlockState().getValue(ItemCollectorBlock.POWERED)) { return TriState.FALSE; } ItemStack itemStack = itemEntity.getItem(); @@ -277,14 +280,14 @@ public void tick(Level level, BlockPos blockPos) { if (this.cooldown.get() != this.oldCooldown) { this.oldCooldown = this.cooldown.get(); if (this.oldCooldown == 0) { - addPoachingCollector(this); + ItemCollectorBlockEntity.addPoachingCollector(this); } else { - removePoachingCollector(this); + ItemCollectorBlockEntity.removePoachingCollector(this); } } if (this.rangeRadius.get() != this.oldRange || this.boundingBox == null) { this.boundingBox = AABB.ofSize( - Vec3.atCenterOf(getBlockPos()), + Vec3.atCenterOf(this.getBlockPos()), this.rangeRadius.get() * 2.0 + 1, this.rangeRadius.get() * 2.0 + 1, this.rangeRadius.get() * 2.0 + 1 @@ -321,7 +324,7 @@ public void applyDiskData(ValueInput input) { input.getInt("cd").ifPresent(cd -> this.cd = cd); this.setChanged(); Vec3 center = this.getPos().getCenter(); - MinecraftServer server = level.getServer(); + MinecraftServer server = this.level.getServer(); if (server == null) return; Packet packet = this.getUpdatePacket(); if (packet == null) return; @@ -337,7 +340,7 @@ public List getDiskCompatibleGroups() { public AABB shape() { if (this.boundingBox == null) { this.boundingBox = AABB.ofSize( - Vec3.atCenterOf(getBlockPos()), + Vec3.atCenterOf(this.getBlockPos()), this.rangeRadius.get() * 2.0 + 1, this.rangeRadius.get() * 2.0 + 1, this.rangeRadius.get() * 2.0 + 1 @@ -347,24 +350,24 @@ public AABB shape() { } public static void clearPoachingCollectors() { - POACHING_COLLECTORS.clear(); + ItemCollectorBlockEntity.POACHING_COLLECTORS.clear(); } @SuppressWarnings("DataFlowIssue") public static Set getOrCreateCollectorList(ItemCollectorBlockEntity blockEntity) { ChunkPos chunkPos = ChunkPos.containing(blockEntity.worldPosition); Level level = blockEntity.level; - return getOrCreateCollectorList(level, chunkPos); + return ItemCollectorBlockEntity.getOrCreateCollectorList(level, chunkPos); } public static Set getOrCreateCollectorList(Level level, ChunkPos chunkPos) { - Set collectors = POACHING_COLLECTORS.get( + Set collectors = ItemCollectorBlockEntity.POACHING_COLLECTORS.get( level, chunkPos ); if (collectors == null) { collectors = new HashSet<>(); - POACHING_COLLECTORS.put( + ItemCollectorBlockEntity.POACHING_COLLECTORS.put( level, chunkPos, collectors @@ -374,11 +377,11 @@ public static Set getOrCreateCollectorList(Level level } public static void addPoachingCollector(ItemCollectorBlockEntity blockEntity) { - getOrCreateCollectorList(blockEntity).add(blockEntity); + ItemCollectorBlockEntity.getOrCreateCollectorList(blockEntity).add(blockEntity); } public static void removePoachingCollector(ItemCollectorBlockEntity blockEntity) { - getOrCreateCollectorList(blockEntity).remove(blockEntity); + ItemCollectorBlockEntity.getOrCreateCollectorList(blockEntity).remove(blockEntity); } public static void poachItemEntity(ItemEntity itemEntity) { @@ -386,7 +389,7 @@ public static void poachItemEntity(ItemEntity itemEntity) { for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { ChunkPos chunkPos = new ChunkPos(currentPos.x() + x, currentPos.z() + z); - Set collectors = POACHING_COLLECTORS.get( + Set collectors = ItemCollectorBlockEntity.POACHING_COLLECTORS.get( itemEntity.level(), chunkPos ); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemDetectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemDetectorBlockEntity.java index 8509886e4f..94e01a66cd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemDetectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ItemDetectorBlockEntity.java @@ -62,14 +62,14 @@ public class ItemDetectorBlockEntity extends BlockEntity implements MenuProvider @Getter private int range = 0; private boolean rangeChanged = true; - private AABB detectionRange; + private @Nullable AABB detectionRange; @Getter private final ContainerData dataAccess = new ContainerData() { @Override public int get(int index) { return switch (index) { - case DATASLOT_ID_RANGE -> ItemDetectorBlockEntity.this.range; - case DATASLOT_ID_FILTER_MODE -> ItemDetectorBlockEntity.this.filterMode.ordinal(); + case ItemDetectorBlockEntity.DATASLOT_ID_RANGE -> ItemDetectorBlockEntity.this.range; + case ItemDetectorBlockEntity.DATASLOT_ID_FILTER_MODE -> ItemDetectorBlockEntity.this.filterMode.ordinal(); default -> 0; }; } @@ -77,10 +77,10 @@ public int get(int index) { @Override public void set(int index, int value) { switch (index) { - case DATASLOT_ID_RANGE: + case ItemDetectorBlockEntity.DATASLOT_ID_RANGE: ItemDetectorBlockEntity.this.setRange(value); break; - case DATASLOT_ID_FILTER_MODE: + case ItemDetectorBlockEntity.DATASLOT_ID_FILTER_MODE: if (value < 0 || value >= Mode.values().length) return; ItemDetectorBlockEntity.this.setFilterMode(Mode.values()[value]); break; @@ -197,7 +197,7 @@ private int getOutput(List itemEntities, Level level, AABB aabb) { } } for (BlockPos p : blocksInRange) matchCount += this.scanContainer(level, p, filterItem); - int lerpedOutput = lerpOutput(matchCount, targetCount); + int lerpedOutput = ItemDetectorBlockEntity.lerpOutput(matchCount, targetCount); if (lerpedOutput > 0) { minNonZeroOutput = Math.min(minNonZeroOutput, lerpedOutput); } else if (this.filterMode == Mode.ALL) { @@ -210,7 +210,7 @@ private int getOutput(List itemEntities, Level level, AABB aabb) { int totalCount = 0; for (ItemEntity itemEntity : itemEntities) totalCount += itemEntity.getItem().getCount(); for (BlockPos p : blocksInRange) totalCount += this.scanContainer(level, p, null); - output = lerpOutput(totalCount, 1); + output = ItemDetectorBlockEntity.lerpOutput(totalCount, 1); } return output; } @@ -234,15 +234,15 @@ public void setFilterMode(Mode filterMode) { } public void increaseRange() { - this.range = Mth.clamp(this.range + 1, MIN_RANGE, MAX_RANGE); + this.range = Mth.clamp(this.range + 1, ItemDetectorBlockEntity.MIN_RANGE, ItemDetectorBlockEntity.MAX_RANGE); } public void decreaseRange() { - this.range = Mth.clamp(this.range - 1, MIN_RANGE, MAX_RANGE); + this.range = Mth.clamp(this.range - 1, ItemDetectorBlockEntity.MIN_RANGE, ItemDetectorBlockEntity.MAX_RANGE); } public void setRange(int range) { - range = Mth.clamp(range, MIN_RANGE, MAX_RANGE); + range = Mth.clamp(range, ItemDetectorBlockEntity.MIN_RANGE, ItemDetectorBlockEntity.MAX_RANGE); if (this.range == range) return; this.range = range; this.recalcDetectionRange(); @@ -267,7 +267,7 @@ public Component getDisplayName() { @Override public FilteredItemStackHandler getFilteredItemStackHandler() { - return DUMMY_HANDLER; + return ItemDetectorBlockEntity.DUMMY_HANDLER; } @Override @@ -370,7 +370,7 @@ public enum Mode { } public Mode cycle() { - return this == ANY ? ALL : ANY; + return this == Mode.ANY ? Mode.ALL : Mode.ANY; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeCauldronBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeCauldronBlockEntity.java index 4137590c1d..e67b7a211a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeCauldronBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeCauldronBlockEntity.java @@ -36,6 +36,7 @@ import dev.dubhe.anvilcraft.recipe.anvil.wrap.ItemCompressRecipe; import dev.dubhe.anvilcraft.recipe.sync.RecipesRecord; import dev.dubhe.anvilcraft.util.CauldronUtil; +import dev.dubhe.anvilcraft.util.EntityUtil; import dev.dubhe.anvilcraft.util.FireReforgingUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -96,6 +97,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Predicate; public class LargeCauldronBlockEntity extends BlockEntity implements IItemResourceHandlerHolder, ItemResourceHandlerCache, IFluidResourceHandlerHolder { @@ -114,7 +116,7 @@ public class LargeCauldronBlockEntity extends BlockEntity private static final Identifier FLUID_RECIPE_ACCEPTOR = AnvilCraft.of("large_cauldron_fluid_acceptor"); private final LargeCauldronInputHandler input = new LargeCauldronInputHandler(this::contentsChanged); - private final ItemStacksResourceHandler output = new ItemStacksResourceHandler(OUTPUT_SLOTS) { + private final ItemStacksResourceHandler output = new ItemStacksResourceHandler(LargeCauldronBlockEntity.OUTPUT_SLOTS) { @Override protected void onContentsChanged(int slot, ItemStack previousContents) { LargeCauldronBlockEntity.this.contentsChanged(); @@ -137,9 +139,9 @@ public LargeCauldronBlockEntity(BlockEntityType type, BlockPos pos, BlockStat } public static int inputSlotForPart(Cube3x3PartHalf part) { - for (int i = 0; i < INPUT_SLOT_OFFSETS.length; i++) { - if (INPUT_SLOT_OFFSETS[i][0] == part.getOffsetX() - && INPUT_SLOT_OFFSETS[i][1] == part.getOffsetZ()) return i; + for (int i = 0; i < LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS.length; i++) { + if (LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[i][0] == part.getOffsetX() + && LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[i][1] == part.getOffsetZ()) return i; } return -1; } @@ -198,8 +200,8 @@ public static void serverTick( private void absorbFluidSources(Level level) { BlockPos intakeCenter = this.worldPosition.above(2); - for (int slot = 0; slot < FOOTPRINT_OFFSETS.length; slot++) { - BlockPos sourcePos = positionForFootprint(intakeCenter, slot); + for (int slot = 0; slot < LargeCauldronBlockEntity.FOOTPRINT_OFFSETS.length; slot++) { + BlockPos sourcePos = LargeCauldronBlockEntity.positionForFootprint(intakeCenter, slot); FluidState fluidState = level.getFluidState(sourcePos); if (fluidState.isEmpty() || !fluidState.isSource()) continue; BlockState sourceState = level.getBlockState(sourcePos); @@ -225,14 +227,14 @@ public ResourceHandler getItemHandler() { @Override public ResourceHandler getInput() { LargeCauldronBlockEntity main = this.getMainPart(); - return main.processingSlot < 0 ? EMPTY_HANDLER : main.selectedInput; + return main.processingSlot < 0 ? LargeCauldronBlockEntity.EMPTY_HANDLER : main.selectedInput; } @Override public ResourceHandler getOutput() { LargeCauldronBlockEntity main = this.getMainPart(); // Keep recipe input and output caches from snapshotting the same inventory during output reprocessing. - return main.processingOutput ? EMPTY_HANDLER : main.output; + return main.processingOutput ? LargeCauldronBlockEntity.EMPTY_HANDLER : main.output; } @Override @@ -278,7 +280,7 @@ public ResourceHandler getAutomationItemHandler(@Nullable Directio boolean extractPreferred = side != null && side.getAxis().isHorizontal() && part.getOffsetY() > 0; - return new PreferredInputHandler(main.input, inputSlotForPart(part), extractPreferred); + return new PreferredInputHandler(main.input, LargeCauldronBlockEntity.inputSlotForPart(part), extractPreferred); } public ResourceHandler getAutomationFluidHandler(@Nullable Direction side) { @@ -318,7 +320,7 @@ public boolean clearFluids() { } public boolean insertFromHand(ItemStack held, int preferredSlot) { - ItemStack remainder = insertItem(new PreferredInputHandler(this.input, preferredSlot), held.copy()); + ItemStack remainder = LargeCauldronBlockEntity.insertItem(new PreferredInputHandler(this.input, preferredSlot), held.copy()); int inserted = held.getCount() - remainder.getCount(); if (inserted <= 0) return false; held.shrink(inserted); @@ -335,13 +337,13 @@ public boolean extractItemsToHand(Player player, InteractionHand hand, int input if (extractOutputs) { for (int slot = 0; slot < main.output.size(); slot++) { ItemStack stack; - while (!(stack = extractItem(main.output, slot, Integer.MAX_VALUE)).isEmpty()) { + while (!(stack = LargeCauldronBlockEntity.extractItem(main.output, slot, Integer.MAX_VALUE)).isEmpty()) { extracted.add(stack); } } } else { ItemStack stack; - while (!(stack = extractItem(main.input, inputSlot, Integer.MAX_VALUE)).isEmpty()) { + while (!(stack = LargeCauldronBlockEntity.extractItem(main.input, inputSlot, Integer.MAX_VALUE)).isEmpty()) { extracted.add(stack); } } @@ -355,7 +357,7 @@ public boolean extractItemsToHand(Player player, InteractionHand hand, int input private boolean outputIsEmpty() { for (int slot = 0; slot < this.output.size(); slot++) { - if (!getStack(this.output, slot).isEmpty()) return false; + if (!LargeCauldronBlockEntity.getStack(this.output, slot).isEmpty()) return false; } return true; } @@ -363,7 +365,7 @@ private boolean outputIsEmpty() { public void absorbItem(ItemEntity entity, int preferredSlot) { if (!entity.anvilcraft$isAdsorbable() || entity.isRemoved()) return; ItemStack stack = entity.getItem(); - ItemStack remainder = insertItem( + ItemStack remainder = LargeCauldronBlockEntity.insertItem( new PreferredInputHandler(this.getMainPart().input, preferredSlot), stack.copy() ); @@ -377,16 +379,16 @@ public void absorbItem(ItemEntity entity, int preferredSlot) { public ItemStack insertRecipeOutput(ItemStack stack) { LargeCauldronBlockEntity main = this.getMainPart(); - if (!main.processingOutput) return insertItem(main.output, stack); + if (!main.processingOutput) return LargeCauldronBlockEntity.insertItem(main.output, stack); ItemStack remainder = stack; for (int slot = 0; slot < main.output.size() && !remainder.isEmpty(); slot++) { if (main.processingOutputInputs.contains(slot)) continue; - remainder = insertItem(main.output, slot, remainder); + remainder = LargeCauldronBlockEntity.insertItem(main.output, slot, remainder); } return remainder; } - public boolean hasInputMatching(java.util.function.Predicate predicate) { + public boolean hasInputMatching(Predicate predicate) { LargeCauldronInputHandler handler = this.getMainPart().input; for (int slot = 0; slot < handler.size(); slot++) { ItemStack stack = handler.getStackInSlot(slot); @@ -401,12 +403,12 @@ public void dropContents() { main.droppedContents = true; for (int slot = 0; slot < main.input.size(); slot++) { ItemStack stack; - while (!(stack = extractItem(main.input, slot, Integer.MAX_VALUE)).isEmpty()) { + while (!(stack = LargeCauldronBlockEntity.extractItem(main.input, slot, Integer.MAX_VALUE)).isEmpty()) { Block.popResource(main.level, main.worldPosition, stack); } } for (int slot = 0; slot < main.output.size(); slot++) { - ItemStack stack = extractItem(main.output, slot, Integer.MAX_VALUE); + ItemStack stack = LargeCauldronBlockEntity.extractItem(main.output, slot, Integer.MAX_VALUE); if (!stack.isEmpty()) Block.popResource(main.level, main.worldPosition, stack); } } @@ -497,11 +499,11 @@ public boolean handleGiantAnvilImpact(AnvilEvent.OnLand event) { List initialFluids = main.fluids.copyFluids(); List initialOutputSlots = new ArrayList<>(); for (int slot = 0; slot < main.output.size(); slot++) { - if (!getStack(main.output, slot).isEmpty()) initialOutputSlots.add(slot); + if (!LargeCauldronBlockEntity.getStack(main.output, slot).isEmpty()) initialOutputSlots.add(slot); } int processed = 0; Set specialRecipeSlots = new HashSet<>(); - for (int slot = 0; slot < main.input.size() && processed < MAX_PROCESS_EFFICIENCY; slot++) { + for (int slot = 0; slot < main.input.size() && processed < LargeCauldronBlockEntity.MAX_PROCESS_EFFICIENCY; slot++) { if (!main.tryProcessLiquidEnchantmentRecipe(serverLevel, base, slot)) continue; specialRecipeSlots.add(slot); processed++; @@ -511,13 +513,13 @@ public boolean handleGiantAnvilImpact(AnvilEvent.OnLand event) { do { madeProgress = false; // Slot order must not override recipe priority when ingredients occupy different cauldron cells. - for (int slot : orderedInputSlots(serverLevel, main.input, recipePass)) { - if (processed >= MAX_PROCESS_EFFICIENCY) break; + for (int slot : LargeCauldronBlockEntity.orderedInputSlots(serverLevel, main.input, recipePass)) { + if (processed >= LargeCauldronBlockEntity.MAX_PROCESS_EFFICIENCY) break; if (specialRecipeSlots.contains(slot)) continue; - BlockPos slotPos = positionForInputSlot(base, slot); + BlockPos slotPos = LargeCauldronBlockEntity.positionForInputSlot(base, slot); List candidates = helpers.isEmpty() ? List.of(slotPos.below()) - : orderedHelpers(slotPos, helpers, base); + : LargeCauldronBlockEntity.orderedHelpers(slotPos, helpers, base); RecipeExecution execution = main.tryProcessItemGroup( serverLevel, base, @@ -532,17 +534,17 @@ public boolean handleGiantAnvilImpact(AnvilEvent.OnLand event) { processed++; madeProgress = true; } - } while (madeProgress && processed < MAX_PROCESS_EFFICIENCY); - if (processed >= MAX_PROCESS_EFFICIENCY) break; + } while (madeProgress && processed < LargeCauldronBlockEntity.MAX_PROCESS_EFFICIENCY); + if (processed >= LargeCauldronBlockEntity.MAX_PROCESS_EFFICIENCY) break; } List centerCandidates = helpers.isEmpty() ? List.of(base.below()) - : orderedHelpers(base, helpers, base); + : LargeCauldronBlockEntity.orderedHelpers(base, helpers, base); for (RecipePass recipePass : itemRecipePasses) { for (int slot : initialOutputSlots) { - if (processed >= MAX_PROCESS_EFFICIENCY) break; - if (getStack(main.output, slot).isEmpty()) continue; + if (processed >= LargeCauldronBlockEntity.MAX_PROCESS_EFFICIENCY) break; + if (LargeCauldronBlockEntity.getStack(main.output, slot).isEmpty()) continue; RecipeExecution execution = main.tryProcessItemGroup( serverLevel, base, @@ -556,11 +558,11 @@ public boolean handleGiantAnvilImpact(AnvilEvent.OnLand event) { if (execution.damageAnvil()) event.setAnvilDamage(true); processed++; } - if (processed >= MAX_PROCESS_EFFICIENCY) break; + if (processed >= LargeCauldronBlockEntity.MAX_PROCESS_EFFICIENCY) break; } - if (sameFluids(initialFluids, main.fluids.copyFluids())) { - while (processed < MAX_PROCESS_EFFICIENCY) { + if (LargeCauldronBlockEntity.sameFluids(initialFluids, main.fluids.copyFluids())) { + while (processed < LargeCauldronBlockEntity.MAX_PROCESS_EFFICIENCY) { if (main.tryProcessFluidMixingRecipe(serverLevel)) { processed++; continue; @@ -581,13 +583,13 @@ public boolean handleGiantAnvilImpact(AnvilEvent.OnLand event) { } private boolean tryProcessLiquidEnchantmentRecipe(ServerLevel level, BlockPos base, int slot) { - ItemStack starting = getStack(this.input, slot); + ItemStack starting = LargeCauldronBlockEntity.getStack(this.input, slot); if (starting.isEmpty()) return false; int itemBudget = starting.getMaxStackSize(); int consumed = 0; boolean processed = false; while (consumed < itemBudget) { - ItemStack item = getStack(this.input, slot); + ItemStack item = LargeCauldronBlockEntity.getStack(this.input, slot); if (item.isEmpty()) break; var heatingHelper = this.findActiveHeatingHelper(base, slot); var matched = LiquidEnchantmentCauldronRecipe.match( @@ -597,17 +599,17 @@ private boolean tryProcessLiquidEnchantmentRecipe(ServerLevel level, BlockPos ba ); if (matched.isEmpty()) break; LiquidEnchantmentCauldronRecipe.Result result = matched.get(); - if (!result.itemResult().isEmpty() && !canInsertItem(this.output, result.itemResult())) { + if (!result.itemResult().isEmpty() && !LargeCauldronBlockEntity.canInsertItem(this.output, result.itemResult())) { break; } this.fluids.setFluids(result.fluids()); - extractItem(this.input, slot, result.itemCost()); + LargeCauldronBlockEntity.extractItem(this.input, slot, result.itemCost()); if (!result.itemResult().isEmpty()) { - insertItem(this.output, result.itemResult()); + LargeCauldronBlockEntity.insertItem(this.output, result.itemResult()); } if (result.consumesHeat()) { - consumeHeatingFuel(level, heatingHelper.orElseThrow()); + LargeCauldronBlockEntity.consumeHeatingFuel(level, heatingHelper.orElseThrow()); } consumed += result.itemCost(); processed = true; @@ -616,13 +618,15 @@ private boolean tryProcessLiquidEnchantmentRecipe(ServerLevel level, BlockPos ba } private Optional findActiveHeatingHelper(BlockPos base, int inputSlot) { + Level level = this.level; + if (level == null) return Optional.empty(); List heaters = new ArrayList<>(); - for (int slot = 0; slot < FOOTPRINT_OFFSETS.length; slot++) { - BlockPos helper = positionForFootprint(base, slot).below(); - if (isActiveHeatingHelper(this.level.getBlockState(helper))) heaters.add(helper); + for (int slot = 0; slot < LargeCauldronBlockEntity.FOOTPRINT_OFFSETS.length; slot++) { + BlockPos helper = LargeCauldronBlockEntity.positionForFootprint(base, slot).below(); + if (LargeCauldronBlockEntity.isActiveHeatingHelper(level.getBlockState(helper))) heaters.add(helper); } - BlockPos inputPos = positionForInputSlot(base, inputSlot); - return orderedHelpers(inputPos, heaters, base).stream().findFirst(); + BlockPos inputPos = LargeCauldronBlockEntity.positionForInputSlot(base, inputSlot); + return LargeCauldronBlockEntity.orderedHelpers(inputPos, heaters, base).stream().findFirst(); } private static boolean isActiveHeatingHelper(BlockState state) { @@ -644,18 +648,18 @@ private boolean tryProcessFluidMixingRecipe(ServerLevel level) { int maximumBatches = recipe.getMaximumBatches(storedFluids); if (maximumBatches <= 0) continue; List mixedFluids = recipe.consumesMaximum() - ? findLargestFluidMixingResult(recipe, storedFluids, maximumBatches) - : simulateFluidMixing(recipe, storedFluids, 1); + ? LargeCauldronBlockEntity.findLargestFluidMixingResult(recipe, storedFluids, maximumBatches) + : LargeCauldronBlockEntity.simulateFluidMixing(recipe, storedFluids, 1); if (mixedFluids == null) continue; ItemStacksResourceHandler simulatedOutput = new ItemStacksResourceHandler(this.output.size()); for (int slot = 0; slot < this.output.size(); slot++) { - ItemStack stack = getStack(this.output, slot); + ItemStack stack = LargeCauldronBlockEntity.getStack(this.output, slot); simulatedOutput.set(slot, ItemResource.of(stack), stack.getCount()); } boolean fits = true; for (ItemStack result : recipe.getItemResults()) { - if (!insertItem(simulatedOutput, result.copy()).isEmpty()) { + if (!LargeCauldronBlockEntity.insertItem(simulatedOutput, result.copy()).isEmpty()) { fits = false; break; } @@ -664,7 +668,7 @@ private boolean tryProcessFluidMixingRecipe(ServerLevel level) { this.fluids.setFluids(mixedFluids); for (ItemStack result : recipe.getItemResults()) { - insertItem(this.output, result.copy()); + LargeCauldronBlockEntity.insertItem(this.output, result.copy()); } return true; } @@ -681,7 +685,7 @@ private boolean tryProcessFluidMixingRecipe(ServerLevel level) { List best = null; while (low <= high) { int middle = low + (high - low) / 2; - List candidate = simulateFluidMixing(recipe, storedFluids, middle); + List candidate = LargeCauldronBlockEntity.simulateFluidMixing(recipe, storedFluids, middle); if (candidate == null) { high = middle - 1; } else { @@ -704,7 +708,7 @@ private boolean tryProcessFluidMixingRecipe(ServerLevel level) { LargeCauldronFluidHandler simulatedFluids = new LargeCauldronFluidHandler(() -> {}); simulatedFluids.setFluids(remainingFluids.get()); for (FluidStack result : fluidResults.get()) { - int filled = insertFluid(simulatedFluids, result); + int filled = LargeCauldronBlockEntity.insertFluid(simulatedFluids, result); if (filled != result.getAmount()) return null; } return simulatedFluids.copyFluids(); @@ -726,7 +730,7 @@ private RecipeExecution tryProcessItemGroup( this.processingOutputInputs.clear(); if (outputSource) { for (int outputSlot = 0; outputSlot < this.output.size(); outputSlot++) { - if (!getStack(this.output, outputSlot).isEmpty()) { + if (!LargeCauldronBlockEntity.getStack(this.output, outputSlot).isEmpty()) { this.processingOutputInputs.add(outputSlot); } } @@ -761,7 +765,7 @@ private RecipeExecution tryProcessFluidRecipe( for (BlockPos helper : candidates) { Vec3 contextPos = new Vec3(helper.getX() + 0.5, base.getY() + 1.0, helper.getZ() + 0.5); InWorldRecipeContext context = new InWorldRecipeContext(level, contextPos, anvil); - RecipeExecution execution = triggerOneRecipe(level, context, ItemStack.EMPTY, recipePass); + RecipeExecution execution = LargeCauldronBlockEntity.triggerOneRecipe(level, context, ItemStack.EMPTY, recipePass); if (execution.executed()) return execution; } return RecipeExecution.EMPTY; @@ -776,17 +780,17 @@ private RecipeExecution triggerRecipeGroup( RecipePass recipePass ) { ResourceHandler source = outputSource ? this.output : this.input; - ItemStack starting = getStack(source, slot); + ItemStack starting = LargeCauldronBlockEntity.getStack(source, slot); if (starting.isEmpty()) return new RecipeExecution(false, false); int itemBudget = starting.getMaxStackSize(); int consumed = 0; boolean executed = false; boolean damageAnvil = false; while (consumed < itemBudget) { - ItemStack processingInput = getStack(source, slot); + ItemStack processingInput = LargeCauldronBlockEntity.getStack(source, slot); if (processingInput.isEmpty()) break; InWorldRecipeContext context = new InWorldRecipeContext(level, contextPos, anvil); - RecipeExecution current = triggerOneRecipe( + RecipeExecution current = LargeCauldronBlockEntity.triggerOneRecipe( level, context, processingInput, @@ -795,7 +799,7 @@ private RecipeExecution triggerRecipeGroup( if (!current.executed()) break; executed = true; damageAnvil |= current.damageAnvil(); - int consumedNow = processingInput.getCount() - getStack(source, slot).getCount(); + int consumedNow = processingInput.getCount() - LargeCauldronBlockEntity.getStack(source, slot).getCount(); if (consumedNow <= 0) break; consumed += consumedNow; } @@ -813,8 +817,8 @@ private static RecipeExecution triggerOneRecipe( InWorldRecipe recipe = holder.value(); if (!recipePass.accepts(recipe)) continue; if (processingInput.isEmpty()) { - if (!isFluidOnlyRecipe(recipe)) continue; - } else if (!recipeAnchoredByInput(recipe, processingInput)) { + if (!LargeCauldronBlockEntity.isFluidOnlyRecipe(recipe)) continue; + } else if (!LargeCauldronBlockEntity.recipeAnchoredByInput(recipe, processingInput)) { continue; } if (!recipe.matches(context, level)) continue; @@ -842,13 +846,13 @@ private static List orderedInputSlots( ) { List slots = new ArrayList<>(); for (int slot = 0; slot < input.size(); slot++) { - if (!getStack(input, slot).isEmpty()) slots.add(slot); + if (!LargeCauldronBlockEntity.getStack(input, slot).isEmpty()) slots.add(slot); } InWorldRecipeManager manager = level.recipeAccess().anvillib$getInWorldRecipeManager(); slots.sort( - Comparator.comparingInt((Integer slot) -> highestAnchoredRecipePriority( + Comparator.comparingInt((Integer slot) -> LargeCauldronBlockEntity.highestAnchoredRecipePriority( manager, - getStack(input, slot), + LargeCauldronBlockEntity.getStack(input, slot), recipePass )).reversed().thenComparingInt(Integer::intValue) ); @@ -865,7 +869,7 @@ private static int highestAnchoredRecipePriority( : manager.recipeHolders.get(ModRecipeTriggers.ON_ANVIL_FALL_ON.get())) { InWorldRecipe recipe = holder.value(); if (!recipePass.accepts(recipe)) continue; - if (recipeAnchoredByInput(recipe, stack)) priority = Math.max(priority, recipe.priority()); + if (LargeCauldronBlockEntity.recipeAnchoredByInput(recipe, stack)) priority = Math.max(priority, recipe.priority()); } return priority; } @@ -937,13 +941,13 @@ public List getRecipePreviews() { } List previews = new ArrayList<>(); - for (int slot = 0; slot < INPUT_SLOT_OFFSETS.length; slot++) { + for (int slot = 0; slot < LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS.length; slot++) { ItemStack stack = this.input.getStackInSlot(slot); if (stack.isEmpty()) continue; - BlockPos slotPos = positionForInputSlot(base, slot); + BlockPos slotPos = LargeCauldronBlockEntity.positionForInputSlot(base, slot); List candidates = helpers.isEmpty() ? List.of(slotPos.below()) - : orderedHelpers(slotPos, helpers, base); + : LargeCauldronBlockEntity.orderedHelpers(slotPos, helpers, base); for (BlockPos helper : candidates) { RecipePreview preview = this.previewFirstRecipe( recipes, @@ -960,9 +964,9 @@ public List getRecipePreviews() { } List centerCandidates = helpers.isEmpty() ? List.of(base.below()) - : orderedHelpers(base, helpers, base); + : LargeCauldronBlockEntity.orderedHelpers(base, helpers, base); for (int slot = 0; slot < this.output.size(); slot++) { - if (getStack(this.output, slot).isEmpty()) continue; + if (LargeCauldronBlockEntity.getStack(this.output, slot).isEmpty()) continue; for (BlockPos helper : centerCandidates) { RecipePreview preview = this.previewFirstRecipe( recipes, @@ -994,11 +998,13 @@ public List getRecipePreviews() { @SuppressWarnings("unchecked") private List> getPreviewRecipes(boolean itemCompressionLast) { + Level level = this.level; + if (level == null) return List.of(); List> recipes = new ArrayList<>(); - for (RecipeHolder holder : RecipesRecord.getRecipes(this.level).values()) { + for (RecipeHolder holder : RecipesRecord.getRecipes(level).values()) { if (!(holder.value() instanceof InWorldRecipe recipe)) continue; if (!recipe.trigger().equals(ModRecipeTriggers.ON_ANVIL_FALL_ON.get())) continue; - recipes.add((RecipeHolder) (RecipeHolder) holder); + recipes.add((RecipeHolder) holder); } recipes.sort( Comparator.>comparingInt( @@ -1023,9 +1029,9 @@ private List> getPreviewRecipes(boolean itemCompress Vec3 contextPos = new Vec3(helper.getX() + 0.5, base.getY() + 1.0, helper.getZ() + 0.5); for (RecipeHolder holder : recipes) { InWorldRecipe recipe = holder.value(); - if (!recipeUsesInput(recipe, getStack(source, slot))) continue; + if (!LargeCauldronBlockEntity.recipeUsesInput(recipe, LargeCauldronBlockEntity.getStack(source, slot))) continue; PreviewState state = new PreviewState( - copyItemStacks(source), + LargeCauldronBlockEntity.copyItemStacks(source), slot, new HashSet<>(), this.fluids.copyFluids(), @@ -1040,7 +1046,7 @@ private List> getPreviewRecipes(boolean itemCompress outputSource ? -1 : slot, outputSource ? slot : -1, holder.id().identifier(), - categoryPath(holder), + LargeCauldronBlockEntity.categoryPath(holder), List.copyOf(state.fluidPredicates) ); } @@ -1055,9 +1061,9 @@ private List> getPreviewRecipes(boolean itemCompress Vec3 contextPos = new Vec3(helper.getX() + 0.5, base.getY() + 1.0, helper.getZ() + 0.5); for (RecipeHolder holder : recipes) { InWorldRecipe recipe = holder.value(); - if (!isFluidOnlyRecipe(recipe)) continue; + if (!LargeCauldronBlockEntity.isFluidOnlyRecipe(recipe)) continue; PreviewState state = new PreviewState( - copyItemStacks(this.input), + LargeCauldronBlockEntity.copyItemStacks(this.input), -1, new HashSet<>(), this.fluids.copyFluids(), @@ -1072,7 +1078,7 @@ private List> getPreviewRecipes(boolean itemCompress -1, -1, holder.id().identifier(), - categoryPath(holder), + LargeCauldronBlockEntity.categoryPath(holder), List.copyOf(state.fluidPredicates) ); } @@ -1082,7 +1088,7 @@ private List> getPreviewRecipes(boolean itemCompress private static List copyItemStacks(ResourceHandler source) { List result = new ArrayList<>(source.size()); for (int slot = 0; slot < source.size(); slot++) { - result.add(getStack(source, slot)); + result.add(LargeCauldronBlockEntity.getStack(source, slot)); } return result; } @@ -1139,6 +1145,8 @@ private boolean applyPreviewPredicate( PreviewState state, Vec3 contextPos ) { + Level level = this.level; + if (level == null) return false; switch (predicate) { case HasItemIngredient itemIngredient -> { int slot = state.findItem(itemIngredient); @@ -1151,18 +1159,18 @@ private boolean applyPreviewPredicate( if ((cauldron.ignited() && !this.ignited) || !this.targetsThisCauldron(cauldron, contextPos)) { return false; } - if (!applyFluidPredicate(state.fluids, cauldron)) return false; + if (!LargeCauldronBlockEntity.applyFluidPredicate(state.fluids, cauldron)) return false; state.fluidPredicates.add(cauldron); return true; } case HasBlockBase block -> { BlockPos pos = BlockPos.containing(contextPos.add(block.getOffset())); - return block.getPredicate().test(this.level, this.level.getBlockState(pos), this.level.getBlockEntity(pos)); + return block.getPredicate().test(level, level.getBlockState(pos), level.getBlockEntity(pos)); } case HasAnvil anvil -> { BlockState giantAnvil = ModBlocks.GIANT_ANVIL.getDefaultState(); boolean matches = anvil.anvil() - .map(anvilPredicate -> anvilPredicate.test(this.level, giantAnvil, null)) + .map(anvilPredicate -> anvilPredicate.test(level, giantAnvil, null)) .orElse(giantAnvil.is(BlockTags.ANVIL)); return matches != anvil.inverted(); } @@ -1173,8 +1181,10 @@ private boolean applyPreviewPredicate( } private boolean targetsThisCauldron(HasCauldron predicate, Vec3 contextPos) { + Level level = this.level; + if (level == null) return false; BlockPos pos = BlockPos.containing(contextPos.add(predicate.offset())); - BlockState state = this.level.getBlockState(pos); + BlockState state = level.getBlockState(pos); return state.getBlock() instanceof LargeCauldronBlock block && block.getMainPartPos(pos, state).equals(this.worldPosition); } @@ -1188,10 +1198,12 @@ private static String categoryPath(RecipeHolder holder) { } private List findActiveHelpers(BlockPos base) { + Level level = this.level; + if (level == null) return List.of(); List result = new ArrayList<>(); - for (int slot = 0; slot < FOOTPRINT_OFFSETS.length; slot++) { - BlockPos helper = positionForFootprint(base, slot).below(); - if (isActiveRecipeHelper(this.level.getBlockState(helper))) result.add(helper); + for (int slot = 0; slot < LargeCauldronBlockEntity.FOOTPRINT_OFFSETS.length; slot++) { + BlockPos helper = LargeCauldronBlockEntity.positionForFootprint(base, slot).below(); + if (LargeCauldronBlockEntity.isActiveRecipeHelper(level.getBlockState(helper))) result.add(helper); } return result; } @@ -1206,9 +1218,9 @@ private static boolean isActiveRecipeHelper(BlockState state) { private static List orderedHelpers(BlockPos slotPos, List helpers, BlockPos base) { return helpers.stream().sorted(Comparator - .comparingInt((BlockPos pos) -> horizontalDistanceSquared(pos, slotPos)) - .thenComparingInt(pos -> horizontalDistanceSquared(pos, base)) - .thenComparingInt(pos -> slotForPosition(base, pos.above()))) + .comparingInt((BlockPos pos) -> LargeCauldronBlockEntity.horizontalDistanceSquared(pos, slotPos)) + .thenComparingInt(pos -> LargeCauldronBlockEntity.horizontalDistanceSquared(pos, base)) + .thenComparingInt(pos -> LargeCauldronBlockEntity.slotForPosition(base, pos.above()))) .toList(); } @@ -1221,18 +1233,21 @@ private static int horizontalDistanceSquared(BlockPos first, BlockPos second) { private static int slotForPosition(BlockPos base, BlockPos pos) { int dx = pos.getX() - base.getX(); int dz = pos.getZ() - base.getZ(); - for (int slot = 0; slot < FOOTPRINT_OFFSETS.length; slot++) { - if (FOOTPRINT_OFFSETS[slot][0] == dx && FOOTPRINT_OFFSETS[slot][1] == dz) return slot; + for (int slot = 0; slot < LargeCauldronBlockEntity.FOOTPRINT_OFFSETS.length; slot++) { + if (LargeCauldronBlockEntity.FOOTPRINT_OFFSETS[slot][0] == dx + && LargeCauldronBlockEntity.FOOTPRINT_OFFSETS[slot][1] == dz) { + return slot; + } } - return FOOTPRINT_OFFSETS.length; + return LargeCauldronBlockEntity.FOOTPRINT_OFFSETS.length; } private static BlockPos positionForInputSlot(BlockPos base, int slot) { - return base.offset(INPUT_SLOT_OFFSETS[slot][0], 0, INPUT_SLOT_OFFSETS[slot][1]); + return base.offset(LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[slot][0], 0, LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[slot][1]); } private static BlockPos positionForFootprint(BlockPos base, int slot) { - return base.offset(FOOTPRINT_OFFSETS[slot][0], 0, FOOTPRINT_OFFSETS[slot][1]); + return base.offset(LargeCauldronBlockEntity.FOOTPRINT_OFFSETS[slot][0], 0, LargeCauldronBlockEntity.FOOTPRINT_OFFSETS[slot][1]); } private void applyFluidEffects(ServerLevel level) { @@ -1242,7 +1257,7 @@ private void applyFluidEffects(ServerLevel level) { AABB contentArea = this.contentArea(); double fluidTop = contentArea.minY - + CONTENT_HEIGHT * totalAmount / LargeCauldronFluidHandler.TOTAL_CAPACITY; + + LargeCauldronBlockEntity.CONTENT_HEIGHT * totalAmount / LargeCauldronFluidHandler.TOTAL_CAPACITY; AABB fluidArea = new AABB( contentArea.minX, contentArea.minY, @@ -1257,7 +1272,7 @@ private void applyFluidEffects(ServerLevel level) { entity.setRemainingFireTicks(entity.getRemainingFireTicks() + 1); if (entity.getRemainingFireTicks() == 0) entity.igniteForSeconds(8.0F); } - entity.hurt(level.damageSources().inFire(), 4.0F); + EntityUtil.hurt(entity, level.damageSources().inFire(), 4.0F); continue; } boolean touchesLava = false; @@ -1266,7 +1281,7 @@ private void applyFluidEffects(ServerLevel level) { for (FluidStack fluid : layers) { if (fluid.isEmpty()) continue; double layerMaxY = layerMinY - + CONTENT_HEIGHT * fluid.getAmount() / LargeCauldronFluidHandler.TOTAL_CAPACITY; + + LargeCauldronBlockEntity.CONTENT_HEIGHT * fluid.getAmount() / LargeCauldronFluidHandler.TOTAL_CAPACITY; AABB layerArea = new AABB( contentArea.minX, layerMinY, @@ -1289,7 +1304,7 @@ private void applyFluidEffects(ServerLevel level) { entity.clearFire(); boolean creativePlayer = entity instanceof Player player && player.isCreative(); if (!creativePlayer && entity.mayInteract(level, this.worldPosition)) { - extractFluid(this.fluids, extinguishingFluid, 250); + LargeCauldronBlockEntity.extractFluid(this.fluids, extinguishingFluid, 250); } } } @@ -1339,7 +1354,7 @@ private void refreshIgnited() { for (int slot = 0; slot < this.input.size(); slot++) { ItemStack stack = this.input.getStackInSlot(slot); if (stack.is(ModItemTags.FIRE_STARTER)) { - extractItem(this.input, slot, 1); + LargeCauldronBlockEntity.extractItem(this.input, slot, 1); this.setIgnited(true); return; } @@ -1358,8 +1373,8 @@ private void hurtEntitiesInsideFromCampfire(ServerLevel level) { BlockPos base = this.worldPosition.below(); boolean normalCampfire = false; boolean soulCampfire = false; - for (int slot = 0; slot < FOOTPRINT_OFFSETS.length; slot++) { - BlockState state = level.getBlockState(positionForFootprint(base, slot).below()); + for (int slot = 0; slot < LargeCauldronBlockEntity.FOOTPRINT_OFFSETS.length; slot++) { + BlockState state = level.getBlockState(LargeCauldronBlockEntity.positionForFootprint(base, slot).below()); if (CampfireBlock.isLitCampfire(state)) { soulCampfire |= state.is(Blocks.SOUL_CAMPFIRE); normalCampfire |= state.is(Blocks.CAMPFIRE); @@ -1370,48 +1385,48 @@ private void hurtEntitiesInsideFromCampfire(ServerLevel level) { AABB inside = this.contentArea(); for (LivingEntity living : level.getEntitiesOfClass(LivingEntity.class, inside)) { if (living.fireImmune() || living.isSteppingCarefully()) continue; - living.hurt(level.damageSources().inFire(), soulCampfire ? 2.0F : 1.0F); + EntityUtil.hurt(living, level.damageSources().inFire(), soulCampfire ? 2.0F : 1.0F); } } public boolean testFluidRecipe(InWorldRecipeContext context, HasCauldron predicate) { LargeCauldronBlockEntity main = this.getMainPart(); if (predicate.ignited() && !main.ignited) return false; - FluidRecipeState state = fluidState(context, main); - List simulated = copyFluids(state.fluids); - return applyFluidPredicate(simulated, predicate); + FluidRecipeState state = LargeCauldronBlockEntity.fluidState(context, main); + List simulated = LargeCauldronBlockEntity.copyFluids(state.fluids); + return LargeCauldronBlockEntity.applyFluidPredicate(simulated, predicate); } public void snapshotFluidRecipe(InWorldRecipeContext context, HasCauldron predicate) { LargeCauldronBlockEntity main = this.getMainPart(); - FluidRecipeState state = fluidState(context, main); - state.rollback.push(copyFluids(state.fluids)); + FluidRecipeState state = LargeCauldronBlockEntity.fluidState(context, main); + state.rollback.push(LargeCauldronBlockEntity.copyFluids(state.fluids)); if (context.getLevel().getRandom().nextFloat() <= predicate.chance()) { - applyFluidPredicate(state.fluids, predicate); + LargeCauldronBlockEntity.applyFluidPredicate(state.fluids, predicate); } } public void rollbackFluidRecipe(InWorldRecipeContext context) { - FluidRecipeState state = fluidState(context, this.getMainPart()); + FluidRecipeState state = LargeCauldronBlockEntity.fluidState(context, this.getMainPart()); if (!state.rollback.isEmpty()) state.fluids = state.rollback.pop(); } public void clearFluidRecipeStack(InWorldRecipeContext context) { - fluidState(context, this.getMainPart()).rollback.clear(); + LargeCauldronBlockEntity.fluidState(context, this.getMainPart()).rollback.clear(); } public void acceptFluidRecipe(InWorldRecipeContext context) { - context.putAcceptor(FLUID_RECIPE_ACCEPTOR, LargeCauldronBlockEntity::commitFluidRecipes); + context.putAcceptor(LargeCauldronBlockEntity.FLUID_RECIPE_ACCEPTOR, LargeCauldronBlockEntity::commitFluidRecipes); } private static FluidRecipeState fluidState(InWorldRecipeContext context, LargeCauldronBlockEntity cauldron) { - Map states = context.computeIfAbsent(FLUID_RECIPE_STATES); + Map states = context.computeIfAbsent(LargeCauldronBlockEntity.FLUID_RECIPE_STATES); return states.computeIfAbsent(cauldron.worldPosition.asLong(), ignored -> new FluidRecipeState(cauldron.fluids.copyFluids())); } private static void commitFluidRecipes(InWorldRecipeContext context) { - Map states = context.computeIfAbsent(FLUID_RECIPE_STATES); + Map states = context.computeIfAbsent(LargeCauldronBlockEntity.FLUID_RECIPE_STATES); for (Map.Entry entry : states.entrySet()) { BlockEntity entity = context.getLevel().getBlockEntity(BlockPos.of(entry.getKey())); if (entity instanceof LargeCauldronBlockEntity cauldron) { @@ -1421,28 +1436,33 @@ private static void commitFluidRecipes(InWorldRecipeContext context) { } private static boolean applyFluidPredicate(List fluids, HasCauldron predicate) { - int source = findSourceTank(fluids, predicate); + int source = LargeCauldronBlockEntity.findSourceTank(fluids, predicate); if (predicate.fluid().equals(HasCauldron.EMPTY) && source < 0) return false; if (predicate.hasCheck() && !predicate.fluid().equals(HasCauldron.EMPTY) && source < 0) return false; int sourceAmount = source < 0 ? 0 : fluids.get(source).getAmount(); if (predicate.consume() > sourceAmount) return false; - Identifier sourceId = source < 0 - ? null - : BuiltInRegistries.FLUID.getKey(fluids.get(source).getFluid()); - Identifier targetId = HasCauldron.isNotEmpty(predicate.transform()) - ? predicate.transform() - : sourceId != null ? sourceId : HasCauldron.isNotEmpty(predicate.fluid()) ? predicate.fluid() : null; + Optional sourceId = source < 0 + ? Optional.empty() + : Optional.of(BuiltInRegistries.FLUID.getKey(fluids.get(source).getFluid())); + Optional targetId = HasCauldron.isNotEmpty(predicate.transform()) + ? Optional.of(predicate.transform()) + : sourceId.isPresent() + ? sourceId + : HasCauldron.isNotEmpty(predicate.fluid()) + ? Optional.of(predicate.fluid()) + : Optional.empty(); if (predicate.consume() == 0 && predicate.produce() == 0) { - if (source < 0 || targetId == null || targetId.equals(sourceId)) return true; - int target = findTank(fluids, targetId); + if (source < 0 || targetId.isEmpty() || targetId.equals(sourceId)) return true; + Identifier targetIdentifier = targetId.orElseThrow(); + int target = LargeCauldronBlockEntity.findTank(fluids, targetIdentifier); int targetAmount = target < 0 ? 0 : fluids.get(target).getAmount(); if (targetAmount + sourceAmount > LargeCauldronFluidHandler.TANK_CAPACITY) return false; - if (target < 0) target = findEmptyTankAfterRemoving(fluids, source); + if (target < 0) target = LargeCauldronBlockEntity.findEmptyTankAfterRemoving(fluids, source); if (target < 0) return false; FluidStack transformed = fluids.get(target).isEmpty() - ? new FluidStack(BuiltInRegistries.FLUID.getValue(targetId), targetAmount + sourceAmount) + ? new FluidStack(BuiltInRegistries.FLUID.getValue(targetIdentifier), targetAmount + sourceAmount) : fluids.get(target).copyWithAmount(targetAmount + sourceAmount); fluids.set(source, FluidStack.EMPTY); fluids.set(target, transformed); @@ -1454,15 +1474,16 @@ private static boolean applyFluidPredicate(List fluids, HasCauldron fluids.set(source, remaining == 0 ? FluidStack.EMPTY : fluids.get(source).copyWithAmount(remaining)); } if (predicate.produce() == 0) return true; - if (targetId == null) return false; + if (targetId.isEmpty()) return false; - int target = findTank(fluids, targetId); + Identifier targetIdentifier = targetId.orElseThrow(); + int target = LargeCauldronBlockEntity.findTank(fluids, targetIdentifier); int targetAmount = target < 0 ? 0 : fluids.get(target).getAmount(); if (targetAmount + predicate.produce() > LargeCauldronFluidHandler.TANK_CAPACITY) return false; - if (target < 0) target = findEmptyTank(fluids); + if (target < 0) target = LargeCauldronBlockEntity.findEmptyTank(fluids); if (target < 0) return false; FluidStack produced = fluids.get(target).isEmpty() - ? new FluidStack(BuiltInRegistries.FLUID.getValue(targetId), targetAmount + predicate.produce()) + ? new FluidStack(BuiltInRegistries.FLUID.getValue(targetIdentifier), targetAmount + predicate.produce()) : fluids.get(target).copyWithAmount(targetAmount + predicate.produce()); fluids.set(target, produced); return true; @@ -1502,7 +1523,7 @@ private static int findEmptyTank(List fluids) { } private static int findEmptyTankAfterRemoving(List fluids, int source) { - int empty = findEmptyTank(fluids); + int empty = LargeCauldronBlockEntity.findEmptyTank(fluids); return empty >= 0 ? empty : source; } @@ -1568,7 +1589,7 @@ private PreviewState copy() { copiedItems, this.primarySlot, new HashSet<>(this.usedItemSlots), - copyFluids(this.fluids), + LargeCauldronBlockEntity.copyFluids(this.fluids), new ArrayList<>(this.fluidPredicates) ); } @@ -1594,7 +1615,7 @@ private static class FluidRecipeState { private final Deque> rollback = new ArrayDeque<>(); private FluidRecipeState(List fluids) { - this.fluids = copyFluids(fluids); + this.fluids = LargeCauldronBlockEntity.copyFluids(fluids); } } @@ -1722,16 +1743,16 @@ private PreferredInputHandler(LargeCauldronInputHandler delegate, int preferred, List slots = new ArrayList<>(); for (int i = 0; i < delegate.size(); i++) slots.add(i); slots.sort(Comparator - .comparingInt((Integer slot) -> distanceFromPreferred(slot, preferred)) + .comparingInt((Integer slot) -> PreferredInputHandler.distanceFromPreferred(slot, preferred)) .thenComparingInt(Integer::intValue)); this.order = slots.stream().mapToInt(Integer::intValue).toArray(); } private static int distanceFromPreferred(int slot, int preferred) { - int preferredX = preferred < 0 ? 0 : INPUT_SLOT_OFFSETS[preferred][0]; - int preferredZ = preferred < 0 ? 0 : INPUT_SLOT_OFFSETS[preferred][1]; - int dx = INPUT_SLOT_OFFSETS[slot][0] - preferredX; - int dz = INPUT_SLOT_OFFSETS[slot][1] - preferredZ; + int preferredX = preferred < 0 ? 0 : LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[preferred][0]; + int preferredZ = preferred < 0 ? 0 : LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[preferred][1]; + int dx = LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[slot][0] - preferredX; + int dz = LargeCauldronBlockEntity.INPUT_SLOT_OFFSETS[slot][1] - preferredZ; return dx * dx + dz * dz; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeFluidTankBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeFluidTankBlockEntity.java index 8e3ccdb9e1..32604c0011 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeFluidTankBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeFluidTankBlockEntity.java @@ -47,8 +47,8 @@ public class LargeFluidTankBlockEntity extends BlockEntity implements IFluidReso private static final int CHECK_INTERVAL = 100; private final MultiFluidTankHandler tank = new MultiFluidTankHandler( - BASE_CAPACITY, - INFINITY_THRESHOLD, + LargeFluidTankBlockEntity.BASE_CAPACITY, + LargeFluidTankBlockEntity.INFINITY_THRESHOLD, this::onTankChanged ); private int tickCounter; @@ -95,7 +95,7 @@ private void setChangedForAllParts() { public void tick() { if (!this.isMainPart()) return; - if (++this.tickCounter % CHECK_INTERVAL == 0 && this.level != null && !this.level.isClientSide()) { + if (++this.tickCounter % LargeFluidTankBlockEntity.CHECK_INTERVAL == 0 && this.level != null && !this.level.isClientSide()) { boolean valid = TankUtil.isMengerStructure(this.level, this.getBlockPos(), 9); if (this.tank.isEnhanced() && !valid) { this.onUnformed(); @@ -124,7 +124,9 @@ private int computeLightLevel() { for (FluidStack stack : this.tank.copyFluids()) { lightLevel = Math.max(lightLevel, stack.getFluidType().getLightLevel(stack)); } - long renderCapacity = this.tank.isEnhanced() ? INFINITY_THRESHOLD : BASE_CAPACITY; + long renderCapacity = this.tank.isEnhanced() + ? LargeFluidTankBlockEntity.INFINITY_THRESHOLD + : LargeFluidTankBlockEntity.BASE_CAPACITY; double fill = Math.min(1.0, (double) this.tank.getTotalAmount() / renderCapacity); return (int) Math.ceil(lightLevel * fill); } @@ -156,6 +158,7 @@ public Packet getUpdatePacket() { } @Override + @SuppressWarnings("deprecation") public void removeComponentsFromTag(ValueOutput output) { super.removeComponentsFromTag(output); output.discard("Tank"); @@ -174,7 +177,7 @@ public void saveToDrop(ItemStack stack, HolderLookup.Provider registries) { public static boolean isEmptyItem(ItemStack stack, HolderLookup.Provider registries) { if (!stack.is(ModBlocks.LARGE_FLUID_TANK.asItem())) return false; - return readItemTank(stack, registries).getTotalAmount() == 0; + return LargeFluidTankBlockEntity.readItemTank(stack, registries).getTotalAmount() == 0; } public static ItemStack fillItem( @@ -182,11 +185,11 @@ public static ItemStack fillItem( List fluids, HolderLookup.Provider registries ) { - if (fluids.isEmpty() || !isEmptyItem(stack, registries)) return ItemStack.EMPTY; + if (fluids.isEmpty() || !LargeFluidTankBlockEntity.isEmptyItem(stack, registries)) return ItemStack.EMPTY; MultiFluidTankHandler itemTank = new MultiFluidTankHandler( - BASE_CAPACITY, - INFINITY_THRESHOLD, + LargeFluidTankBlockEntity.BASE_CAPACITY, + LargeFluidTankBlockEntity.INFINITY_THRESHOLD, () -> {} ); try (Transaction transaction = Transaction.openRoot()) { @@ -207,11 +210,11 @@ public static ItemStack fillItem( private static MultiFluidTankHandler readItemTank(ItemStack stack, HolderLookup.Provider registries) { MultiFluidTankHandler itemTank = new MultiFluidTankHandler( - BASE_CAPACITY, - INFINITY_THRESHOLD, + LargeFluidTankBlockEntity.BASE_CAPACITY, + LargeFluidTankBlockEntity.INFINITY_THRESHOLD, () -> {} ); - itemTank.deserialize(TagValueInput.create(ProblemReporter.DISCARDING, registries, getTankData(stack))); + itemTank.deserialize(TagValueInput.create(ProblemReporter.DISCARDING, registries, LargeFluidTankBlockEntity.getTankData(stack))); return itemTank; } @@ -231,7 +234,7 @@ public boolean onPlayerUse(Player player, InteractionHand hand) { public int getRedstoneSignal() { MultiFluidTankHandler mainTank = this.getMainPart().tank; long amount = mainTank.getTotalAmount(); - int capacity = mainTank.isEnhanced() ? INFINITY_THRESHOLD : BASE_CAPACITY; + int capacity = mainTank.isEnhanced() ? LargeFluidTankBlockEntity.INFINITY_THRESHOLD : LargeFluidTankBlockEntity.BASE_CAPACITY; int strength = amount == 0 ? 0 : (int) (Math.min(amount, capacity) * (Redstone.SIGNAL_MAX - 1) / capacity) + 1; @@ -265,7 +268,7 @@ public boolean isInfinite(FluidStack fluid) { public boolean containsInfiniteFluid() { return this.getMainPart().tank.copyFluids().stream() - .anyMatch(fluid -> fluid.getAmount() >= INFINITY_THRESHOLD); + .anyMatch(fluid -> fluid.getAmount() >= LargeFluidTankBlockEntity.INFINITY_THRESHOLD); } public List getStoredFluids() { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeLaserBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeLaserBlockEntity.java index 6371b6b333..590fedd8e7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeLaserBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/LargeLaserBlockEntity.java @@ -38,29 +38,29 @@ public void tick(Level level) { if (this.grid == null) { return; } - if (!getBlockState().getValue(LargeLaserBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) return; - if (!(getBlockState().getBlock() instanceof LargeLaserBlock block)) return; - if (this.grid.isWorking() && getBlockState().getValue(LargeLaserBlock.OVERLOAD)) { - block.updateState(this.level, getBlockPos(), LargeLaserBlock.OVERLOAD, false, 3); - } else if (!this.grid.isWorking() && !getBlockState().getValue(LargeLaserBlock.OVERLOAD)) { - block.updateState(this.level, getBlockPos(), LargeLaserBlock.OVERLOAD, true, 3); + if (!this.getBlockState().getValue(LargeLaserBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) return; + if (!(this.getBlockState().getBlock() instanceof LargeLaserBlock block)) return; + if (this.grid.isWorking() && this.getBlockState().getValue(LargeLaserBlock.OVERLOAD)) { + block.updateState(this.level, this.getBlockPos(), LargeLaserBlock.OVERLOAD, false, 3); + } else if (!this.grid.isWorking() && !this.getBlockState().getValue(LargeLaserBlock.OVERLOAD)) { + block.updateState(this.level, this.getBlockPos(), LargeLaserBlock.OVERLOAD, true, 3); } if (this.isSwitchedOn()) { - emitLaser(this.getFacing()); + this.emitLaser(this.getFacing()); } else { - if (irradiateBlockPos != null - && level.getBlockEntity(irradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity + if (this.irradiateBlockPos != null + && level.getBlockEntity(this.irradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity ) { irradiateBlockEntity.onCancelingIrradiation(this); } - updateIrradiateBlockPos(null); + this.updateIrradiateBlockPos(null); } super.tick(level); } public boolean isSwitchedOn() { - return getBlockState().getValue(LargeLaserBlock.SWITCH) == Switch.ON - && !getBlockState().getValue(LargeLaserBlock.OVERLOAD); + return this.getBlockState().getValue(LargeLaserBlock.SWITCH) == Switch.ON + && !this.getBlockState().getValue(LargeLaserBlock.OVERLOAD); } @Override @@ -79,8 +79,8 @@ public BlockPos getPos() { @Override public int getInputPower() { - if (level == null) return 256; - return getBlockState().getValue(LargeLaserBlock.SWITCH) == Switch.OFF ? 0 : 256; + if (this.level == null) return 256; + return this.getBlockState().getValue(LargeLaserBlock.SWITCH) == Switch.OFF ? 0 : 256; } @Override @@ -91,10 +91,10 @@ public Direction getFacing() { @Override public PowerComponentType getComponentType() { if (this.level == null) return PowerComponentType.INVALID; - if (!this.level.getBlockState(getBlockPos()).hasProperty(LargeLaserBlock.HALF)) { + if (!this.level.getBlockState(this.getBlockPos()).hasProperty(LargeLaserBlock.HALF)) { return PowerComponentType.INVALID; } - if (this.level.getBlockState(getBlockPos()).getValue(LargeLaserBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) { + if (this.level.getBlockState(this.getBlockPos()).getValue(LargeLaserBlock.HALF).equals(DirectionCube3x3PartHalf.MID_CENTER)) { return PowerComponentType.CONSUMER; } else { return PowerComponentType.INVALID; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/LaserReceiverBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/LaserReceiverBlockEntity.java index c74f35efb9..aaedc66fa5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/LaserReceiverBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/LaserReceiverBlockEntity.java @@ -34,19 +34,19 @@ public int getOutputPower() { @Override public void tick(Level level) { - updateLaserLevel(calculateLaserLevel()); - if (changed) { - if (laserLevel > 0) { - level.setBlockAndUpdate(getBlockPos(), getBlockState().setValue(LaserReceiverBlock.ACTIVE, true)); + this.updateLaserLevel(this.calculateLaserLevel()); + if (this.changed) { + if (this.laserLevel > 0) { + level.setBlockAndUpdate(this.getBlockPos(), this.getBlockState().setValue(LaserReceiverBlock.ACTIVE, true)); } else { - level.setBlockAndUpdate(getBlockPos(), getBlockState().setValue(LaserReceiverBlock.ACTIVE, false)); + level.setBlockAndUpdate(this.getBlockPos(), this.getBlockState().setValue(LaserReceiverBlock.ACTIVE, false)); } this.efficiency = 0; this.tempEfficiency = 0; this.delay = 0; - this.power = laserLevel * 15; + this.power = this.laserLevel * 15; } - if (getBlockState().getValue(LaserReceiverBlock.ACTIVE) && !changed) { + if (this.getBlockState().getValue(LaserReceiverBlock.ACTIVE) && !this.changed) { if (this.efficiency < this.power) { this.delay++; this.tempEfficiency += this.power * 0.005; @@ -57,7 +57,7 @@ public void tick(Level level) { } } super.tick(level); - resetState(); + this.resetState(); } @Override @@ -72,7 +72,7 @@ public Direction getFacing() { @Override public Set getIgnoreFace() { - return Set.of(getBlockState().getValue(LaserReceiverBlock.FACING)); + return Set.of(this.getBlockState().getValue(LaserReceiverBlock.FACING)); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/LensBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/LensBlockEntity.java index 0fe8a8c2c4..8861ac2667 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/LensBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/LensBlockEntity.java @@ -6,6 +6,7 @@ import dev.dubhe.anvilcraft.init.entity.ModDamageTypes; import dev.dubhe.anvilcraft.util.BlockMiningEffect; import dev.dubhe.anvilcraft.util.BreakBlockUtil; +import dev.dubhe.anvilcraft.util.EntityUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; @@ -22,6 +23,7 @@ import net.neoforged.neoforge.common.Tags; import java.util.List; +import java.util.Objects; public class LensBlockEntity extends BaseLaserBlockEntity { private boolean enabled = false; @@ -33,12 +35,12 @@ public LensBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockSt @Override public Direction getFacing() { - if (irradiateBlockPos != null) { - Direction.Axis axis = getBlockState().getValue(LensBlock.AXIS); + if (this.irradiateBlockPos != null) { + Direction.Axis axis = this.getBlockState().getValue(LensBlock.AXIS); int diff = switch (axis) { - case X -> irradiateBlockPos.getX() - getBlockPos().getX(); - case Y -> irradiateBlockPos.getY() - getBlockPos().getY(); - case Z -> irradiateBlockPos.getZ() - getBlockPos().getZ(); + case X -> this.irradiateBlockPos.getX() - this.getBlockPos().getX(); + case Y -> this.irradiateBlockPos.getY() - this.getBlockPos().getY(); + case Z -> this.irradiateBlockPos.getZ() - this.getBlockPos().getZ(); }; Direction.AxisDirection axisDir = diff > 0 ? Direction.AxisDirection.POSITIVE @@ -46,7 +48,7 @@ public Direction getFacing() { return Direction.fromAxisAndDirection(axis, axisDir); } return Direction.fromAxisAndDirection( - getBlockState().getValue(LensBlock.AXIS), + this.getBlockState().getValue(LensBlock.AXIS), Direction.AxisDirection.POSITIVE ); } @@ -64,7 +66,7 @@ public BlockMiningEffect getMiningEffect() { /// 按镜片类型给激光束染色(在渲染阶段通过 LaserRenderState.color 读取)。 @Override public int getLaserColor() { - return switch (getBlockState().getValue(LensBlock.TYPE)) { + return switch (this.getBlockState().getValue(LensBlock.TYPE)) { case ROYAL -> 0x0000FFBF; case FROST -> 0x00598CFF; case EMBER -> 0x00FFD900; @@ -94,9 +96,9 @@ public void resetLaserStateAfterMove() { } private boolean determineEmissionDirection(BaseLaserBlockEntity source) { - Direction.Axis axis = getBlockState().getValue(LensBlock.AXIS); + Direction.Axis axis = this.getBlockState().getValue(LensBlock.AXIS); BlockPos sourcePos = source.getBlockPos(); - BlockPos myPos = getBlockPos(); + BlockPos myPos = this.getBlockPos(); boolean aligned = switch (axis) { case X -> sourcePos.getY() == myPos.getY() && sourcePos.getZ() == myPos.getZ(); case Y -> sourcePos.getX() == myPos.getX() && sourcePos.getZ() == myPos.getZ(); @@ -122,14 +124,14 @@ public void tick(Level level) { this.emitLaser(this.emittingDirection); } super.tick(level); - if (laserLevel == 0) this.enabled = false; - resetState(); + if (this.laserLevel == 0) this.enabled = false; + this.resetState(); } @Override public void deliverItem(List drops, Direction direction, BlockPos sourceBlockPos) { - if (!irradiateSelfLaserBlockSet.isEmpty()) { - BaseLaserBlockEntity upstream = irradiateSelfLaserBlockSet.iterator().next(); + if (!this.irradiateSelfLaserBlockSet.isEmpty()) { + BaseLaserBlockEntity upstream = this.irradiateSelfLaserBlockSet.iterator().next(); upstream.deliverItem(drops, direction, sourceBlockPos); return; } @@ -153,15 +155,16 @@ public void emitLaser(Direction direction) { ); BaseLaserBlockEntity newLaserTarget = this.level.getBlockEntity(tempIrradiateBlockPos) instanceof BaseLaserBlockEntity target ? target : null; - boolean targetChanged = !tempIrradiateBlockPos.equals(this.irradiateBlockPos); + BlockPos oldIrradiateBlockPos = this.irradiateBlockPos; + boolean targetChanged = !Objects.equals(tempIrradiateBlockPos, oldIrradiateBlockPos); boolean targetEntityChanged = newLaserTarget != this.irradiatedLaserTarget; boolean targetRevisionChanged = newLaserTarget != null && newLaserTarget.laserLinkRevision != this.irradiatedLaserTargetRevision; if (targetChanged || targetEntityChanged || targetRevisionChanged) { if (this.irradiatedLaserTarget != null) { this.irradiatedLaserTarget.onCancelingIrradiation(this); - } else if (targetChanged && this.irradiateBlockPos != null) { - BlockEntity oldBe = this.level.getBlockEntity(this.irradiateBlockPos); + } else if (targetChanged && oldIrradiateBlockPos != null) { + BlockEntity oldBe = this.level.getBlockEntity(oldIrradiateBlockPos); if (oldBe instanceof BaseLaserBlockEntity lastIrradiatedLaserBlockEntity) { lastIrradiatedLaserBlockEntity.onCancelingIrradiation(this); } @@ -179,7 +182,7 @@ public void emitLaser(Direction direction) { || targetRevisionChanged || laserLevelChanged; if (needsIrradiationUpdate && !newLaserTarget.getIgnoreFace().contains(direction)) { - this.level.updateNeighborsAt(tempIrradiateBlockPos, getBlockState().getBlock()); + this.level.updateNeighborsAt(tempIrradiateBlockPos, this.getBlockState().getBlock()); newLaserTarget.onIrradiated(this); this.irradiatedLaserTarget = newLaserTarget; this.irradiatedLaserTargetRevision = newLaserTarget.laserLinkRevision; @@ -205,17 +208,18 @@ public void emitLaser(Direction direction) { trackBoundingBox, Entity::isAlive ).forEach(livingEntity -> - livingEntity.hurtOrSimulate( + EntityUtil.hurtOrSimulate( + livingEntity, ModDamageTypes.laser(this.level), hurt ) ); } BlockState irradiateBlock = this.level.getBlockState(this.irradiateBlockPos); - int cooldown = COOLDOWNS[Math.clamp(this.laserLevel / 4, 0, 4)]; + int cooldown = BaseLaserBlockEntity.COOLDOWNS[Math.clamp(this.laserLevel / 4, 0, 4)]; if (this.tickCount >= cooldown) { this.tickCount = 0; - LensType lensType = getBlockState().getValue(LensBlock.TYPE); + LensType lensType = this.getBlockState().getValue(LensBlock.TYPE); boolean isOreTarget = irradiateBlock.is(Tags.Blocks.ORES); boolean isLensSpecialTarget = lensType != LensType.NONE && (irradiateBlock.is(ModBlocks.VOID_STONE) || irradiateBlock.is(ModBlocks.EARTH_CORE_SHARD_ORE)); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/LoadMonitorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/LoadMonitorBlockEntity.java index 3caf127f2f..7432827f23 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/LoadMonitorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/LoadMonitorBlockEntity.java @@ -15,6 +15,8 @@ import net.minecraft.world.level.storage.ValueOutput; import org.jspecify.annotations.Nullable; +import java.util.Objects; + public class LoadMonitorBlockEntity extends BlockEntity implements IPowerConsumer { @Getter @Setter @@ -41,39 +43,41 @@ protected void saveAdditional(ValueOutput output) { @Override public Level getCurrentLevel() { - return getLevel(); + return Objects.requireNonNull(this.getLevel()); } @Override public BlockPos getPos() { - return getBlockPos(); + return this.getBlockPos(); } public int getRedstoneSignal() { - if (getGrid() == null) return 0; + if (this.getGrid() == null) return 0; // 空载 - if (getGrid().getConsume() == 0) return 0; + if (this.getGrid().getConsume() == 0) return 0; // 满载 - if (getGrid().getConsume() > getGrid().getGenerate()) return 0; - return (int) Math.ceil(((double) getGrid().getConsume() / getGrid().getGenerate()) * 15); + if (this.getGrid().getConsume() > this.getGrid().getGenerate()) return 0; + return (int) Math.ceil(((double) this.getGrid().getConsume() / this.getGrid().getGenerate()) * 15); } public void tick() { if (this.cooldown > 0) { this.cooldown--; } else { - if (getGrid() == null) return; - flushState(getLevel(), getBlockPos()); + PowerGrid grid = this.getGrid(); + Level level = this.getLevel(); + if (grid == null || level == null) return; + this.flushState(level, this.getBlockPos()); // 满载 - if (getGrid().getConsume() > getGrid().getGenerate()) return; - int load = getGrid().getConsume() != 0 + if (grid.getConsume() > grid.getGenerate()) return; + int load = grid.getConsume() != 0 ? (int) Math.ceil( - (double) getGrid().getConsume() / getGrid().getGenerate() * 10) + (double) grid.getConsume() / grid.getGenerate() * 10) : 0; - BlockState state = getBlockState().setValue(LoadMonitorBlock.LOAD, load); - getLevel().setBlockAndUpdate(getBlockPos(), state); + BlockState state = this.getBlockState().setValue(LoadMonitorBlock.LOAD, load); + level.setBlockAndUpdate(this.getBlockPos(), state); this.cooldown = AnvilCraft.CONFIG.loadMonitor; - getLevel().updateNeighbourForOutputSignal(getBlockPos(), state.getBlock()); + level.updateNeighbourForOutputSignal(this.getBlockPos(), state.getBlock()); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/MagneticChuteBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/MagneticChuteBlockEntity.java index 1d9fe46014..1938c3ef34 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/MagneticChuteBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/MagneticChuteBlockEntity.java @@ -35,7 +35,7 @@ protected boolean validateBlockState(BlockState state) { @Override protected boolean isEnabled() { - return getBlockState().getValue(MagneticChuteBlock.ENABLED); + return this.getBlockState().getValue(MagneticChuteBlock.ENABLED); } @Override @@ -45,7 +45,7 @@ protected EnumProperty getFacingProperty() { @Override protected Direction getOutputDirection() { - return getDirection(); + return this.getDirection(); } @Override @@ -60,7 +60,7 @@ public Component getDisplayName() { @Override protected void applySpeed(ItemEntity itemEntity, Direction direction) { - itemEntity.setDeltaMovement(getOutputSpeed(direction)); + itemEntity.setDeltaMovement(MagneticChuteBlockEntity.getOutputSpeed(direction)); } public static Vec3 getOutputSpeed(Direction direction) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/MineralFountainBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/MineralFountainBlockEntity.java index 59214f5c0b..de41589331 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/MineralFountainBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/MineralFountainBlockEntity.java @@ -57,24 +57,24 @@ public void tick() { if (this.tickCount != 0) return; if (!(this.level instanceof ServerLevel serverLevel)) return; BlockState aroundState = this.getAroundBlock(); - if (this.level.getMinY() > getBlockPos().getY() || getBlockPos().getY() > this.level.getMinY() + 8) { + if (this.level.getMinY() > this.getBlockPos().getY() || this.getBlockPos().getY() > this.level.getMinY() + 8) { return; } - BlockState aboveState = this.level.getBlockState(getBlockPos().above()); + BlockState aboveState = this.level.getBlockState(this.getBlockPos().above()); if (aroundState.is(Blocks.LAVA)) { if (aboveState.is(Blocks.AIR)) { - this.level.setBlockAndUpdate(getBlockPos().above(), Blocks.LAVA.defaultBlockState()); + this.level.setBlockAndUpdate(this.getBlockPos().above(), Blocks.LAVA.defaultBlockState()); return; } - HeaterManager.addProducer(getBlockPos(), serverLevel, ModHeaterInfos.LAVA_MINERAL_FOUNTAIN); + HeaterManager.addProducer(this.getBlockPos(), serverLevel, ModHeaterInfos.LAVA_MINERAL_FOUNTAIN); return; } else if (aboveState.is(Blocks.AIR)) { - this.level.setBlockAndUpdate(getBlockPos().above(), ModBlocks.CINERITE.getDefaultState()); + this.level.setBlockAndUpdate(this.getBlockPos().above(), ModBlocks.CINERITE.getDefaultState()); } else { MineralFountainRecipe.Input input = new MineralFountainRecipe.Input(aroundState.getBlock(), aboveState.getBlock()); RecipeManager recipeManager = serverLevel.getServer().getRecipeManager(); recipeManager - .getRecipeFor(ModRecipeTypes.MINERAL_FOUNTAIN.get(), input, level) + .getRecipeFor(ModRecipeTypes.MINERAL_FOUNTAIN.get(), input, this.level) .ifPresent(recipe -> { var chanceList = recipeManager.recipeMap() .byType(ModRecipeTypes.MINERAL_FOUNTAIN_CHANCE.get()) @@ -88,19 +88,19 @@ public void tick() { for (var changeRecipe : chanceList) { if (this.level.getRandom().nextDouble() <= changeRecipe.value().getChance(serverLevel)) { this.level.setBlockAndUpdate( - getBlockPos().above(), + this.getBlockPos().above(), changeRecipe.value().toBlock().state() ); return; } } - level.setBlockAndUpdate( - getBlockPos().above(), + this.level.setBlockAndUpdate( + this.getBlockPos().above(), recipe.value().toBlock().state() ); }); } - HeaterManager.removeProducer(getBlockPos(), serverLevel, ModHeaterInfos.LAVA_MINERAL_FOUNTAIN); + HeaterManager.removeProducer(this.getBlockPos(), serverLevel, ModHeaterInfos.LAVA_MINERAL_FOUNTAIN); } private static final Direction[] HORIZONTAL_DIRECTION = { @@ -114,8 +114,8 @@ public BlockState getAroundBlock() { if (this.level == null) { return Blocks.AIR.defaultBlockState(); } - List blockStates = Arrays.stream(HORIZONTAL_DIRECTION) - .map(direction -> this.level.getBlockState(getBlockPos().relative(direction))) + List blockStates = Arrays.stream(MineralFountainBlockEntity.HORIZONTAL_DIRECTION) + .map(direction -> this.level.getBlockState(this.getBlockPos().relative(direction))) .toList(); BlockState firstState = blockStates.getFirst(); long count = blockStates.stream() diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/MobAmberBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/MobAmberBlockEntity.java index 5f7934563a..784a554b5b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/MobAmberBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/MobAmberBlockEntity.java @@ -33,7 +33,7 @@ public static MobAmberBlockEntity createBlockEntity( // @OnlyIn(Dist.CLIENT) public void clientTick(Level level, BlockPos blockPos) { BlockState state = level.getBlockState(blockPos); - Entity entity = getOrCreateDisplayEntity(level); + Entity entity = this.getOrCreateDisplayEntity(level); if (!state.is(ModBlocks.MOB_AMBER_BLOCK) || !(entity instanceof LivingEntity displayEntity)) return; displayEntity.setPos(blockPos.getCenter()); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/MultiFluidTankHandler.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/MultiFluidTankHandler.java index d0bbe5d743..3ba0a4ee76 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/MultiFluidTankHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/MultiFluidTankHandler.java @@ -157,8 +157,8 @@ void setEnhanced(boolean enhanced) { @Override public void serialize(ValueOutput output) { - output.store("Fluids", FLUIDS_CODEC, this.copyFluids()); - output.store("Infinite", FLAGS_CODEC, this.fluids.stream().map(StoredFluid::infinite).toList()); + output.store("Fluids", MultiFluidTankHandler.FLUIDS_CODEC, this.copyFluids()); + output.store("Infinite", MultiFluidTankHandler.FLAGS_CODEC, this.fluids.stream().map(StoredFluid::infinite).toList()); output.putBoolean("Enhanced", this.enhanced); } @@ -166,8 +166,8 @@ public void serialize(ValueOutput output) { public void deserialize(ValueInput input) { this.fluids.clear(); this.enhanced = input.getBooleanOr("Enhanced", false); - List loaded = input.read("Fluids", FLUIDS_CODEC).orElse(List.of()); - List infinite = input.read("Infinite", FLAGS_CODEC).orElse(List.of()); + List loaded = input.read("Fluids", MultiFluidTankHandler.FLUIDS_CODEC).orElse(List.of()); + List infinite = input.read("Infinite", MultiFluidTankHandler.FLAGS_CODEC).orElse(List.of()); for (int index = 0; index < loaded.size(); index++) { FluidStack fluid = loaded.get(index); if (fluid.isEmpty()) continue; @@ -200,8 +200,8 @@ private void serializeDetached(ValueOutput output, long maxAmount) { detachedFluids.add(stored.fluid().copyWithAmount(amount)); remaining -= amount; } - output.store("Fluids", FLUIDS_CODEC, detachedFluids); - output.store("Infinite", FLAGS_CODEC, detachedFluids.stream().map(ignored -> false).toList()); + output.store("Fluids", MultiFluidTankHandler.FLUIDS_CODEC, detachedFluids); + output.store("Infinite", MultiFluidTankHandler.FLAGS_CODEC, detachedFluids.stream().map(ignored -> false).toList()); output.putBoolean("Enhanced", false); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/NeutronIrradiatorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/NeutronIrradiatorBlockEntity.java index a30e7c8776..b7e1e5fe8e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/NeutronIrradiatorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/NeutronIrradiatorBlockEntity.java @@ -45,7 +45,7 @@ public static NeutronIrradiatorBlockEntity createBlockEntity(BlockEntityType public void tick(Level level, BlockPos pos, BlockState state) { if (this.level == null) return; boolean baseType = true; - for (var entry : IRRADIATOR_TYPE_MAP.entrySet()) { + for (var entry : NeutronIrradiatorBlockEntity.IRRADIATOR_TYPE_MAP.entrySet()) { Block block = entry.getKey(); IrradiatorType type = entry.getValue(); int count = 0; @@ -56,7 +56,7 @@ public void tick(Level level, BlockPos pos, BlockState state) { } } } - if (count >= TYPE_CHECK_THRESHOLD) { + if (count >= NeutronIrradiatorBlockEntity.TYPE_CHECK_THRESHOLD) { baseType = false; if (state.getValue(NeutronIrradiatorBlock.TYPE) != type) { this.level.setBlockAndUpdate(pos, state.setValue(NeutronIrradiatorBlock.TYPE, type)); @@ -68,4 +68,4 @@ public void tick(Level level, BlockPos pos, BlockState state) { this.level.setBlockAndUpdate(pos, state.setValue(NeutronIrradiatorBlock.TYPE, IrradiatorType.NEUTRON)); } } -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/OverseerBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/OverseerBlockEntity.java index 340558b580..861b167a42 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/OverseerBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/OverseerBlockEntity.java @@ -104,8 +104,8 @@ private BaseScanResult scanPyramidBase(Level level, BlockPos selfPos) { List offsetMappings = new ArrayList<>(); BlockPos.MutableBlockPos tierCenter = selfPos.mutable().move(Direction.DOWN); - for (int tier = 0; tier < TIER_RADIUS.length; tier++) { - int radius = TIER_RADIUS[tier]; + for (int tier = 0; tier < OverseerBlockEntity.TIER_RADIUS.length; tier++) { + int radius = OverseerBlockEntity.TIER_RADIUS[tier]; if (!this.isTierComplete(level, tierCenter, radius)) break; completeTiers++; @@ -147,15 +147,15 @@ private int getBlockSourceFlags(BlockState state) { } private boolean isValidBaseBlock(BlockState state) { - for (TagKey tag : VALID_BASE_TAGS) { + for (TagKey tag : OverseerBlockEntity.VALID_BASE_TAGS) { if (state.is(tag)) return true; } return false; } private int getBlockTier(BlockState state) { - for (int i = 0; i < VALID_BASE_TAGS.length; i++) { - if (state.is(VALID_BASE_TAGS[i])) return i; + for (int i = 0; i < OverseerBlockEntity.VALID_BASE_TAGS.length; i++) { + if (state.is(OverseerBlockEntity.VALID_BASE_TAGS[i])) return i; } return -1; } @@ -200,4 +200,4 @@ public int getLoadLevel() { } private record BaseScanResult(int completeTiers, List offsetMappings) {} -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/PlasmaJetsBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/PlasmaJetsBlockEntity.java index 2a04c0e03f..c622c40675 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/PlasmaJetsBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/PlasmaJetsBlockEntity.java @@ -81,17 +81,17 @@ public static PlasmaJetsBlockEntity createBlockEntity(BlockEntityType type, B private boolean tryRaise() { if (this.tubeWalls.size() >= 4) return false; if (this.level != null) { - HeaterManager.removeProducer(this.getBlockPos(), level, ModHeaterInfos.NO_MAGNET_PLASMA_JETS); - HeaterManager.removeProducer(this.getBlockPos(), level, ModHeaterInfos.MAGNET_PLASMA_JETS); + HeaterManager.removeProducer(this.getBlockPos(), this.level, ModHeaterInfos.NO_MAGNET_PLASMA_JETS); + HeaterManager.removeProducer(this.getBlockPos(), this.level, ModHeaterInfos.MAGNET_PLASMA_JETS); } BlockPos pos = this.getBlockPos(); if ( this.level != null && ( - !this.level.getBlockState(pos.north()).isFaceSturdy(level, pos.north(), Direction.SOUTH) - || !this.level.getBlockState(pos.south()).isFaceSturdy(level, pos.south(), Direction.NORTH) - || !this.level.getBlockState(pos.east()).isFaceSturdy(level, pos.east(), Direction.WEST) - || !this.level.getBlockState(pos.west()).isFaceSturdy(level, pos.west(), Direction.EAST) + !this.level.getBlockState(pos.north()).isFaceSturdy(this.level, pos.north(), Direction.SOUTH) + || !this.level.getBlockState(pos.south()).isFaceSturdy(this.level, pos.south(), Direction.NORTH) + || !this.level.getBlockState(pos.east()).isFaceSturdy(this.level, pos.east(), Direction.WEST) + || !this.level.getBlockState(pos.west()).isFaceSturdy(this.level, pos.west(), Direction.EAST) ) ) { return false; @@ -106,8 +106,8 @@ private boolean tryRaise() { this.continuousFuelTimer, this.tubeWalls )); - HeaterManager.addProducer(this.getBlockPos().above(), level, ModHeaterInfos.NO_MAGNET_PLASMA_JETS); - HeaterManager.addProducer(this.getBlockPos().above(), level, ModHeaterInfos.MAGNET_PLASMA_JETS); + HeaterManager.addProducer(this.getBlockPos().above(), this.level, ModHeaterInfos.NO_MAGNET_PLASMA_JETS); + HeaterManager.addProducer(this.getBlockPos().above(), this.level, ModHeaterInfos.MAGNET_PLASMA_JETS); return true; } @@ -175,8 +175,7 @@ protected void tryIgniteValidCauldron(Level level) { if (!(state.getBlock() instanceof IIgnitableCauldron cauldron)) return; BlockCache cache = new BlockCache(level); - // noinspection deprecation - if (!cauldron.getFluid(cache, this.cauldronPos).is(ModFluidTags.OIL)) return; + if (!cauldron.getFluid(cache, this.cauldronPos).defaultFluidState().is(ModFluidTags.OIL)) return; cauldron.setIgnited(cache, this.cauldronPos, true); cache.accept(); } @@ -215,21 +214,21 @@ protected void refreshDuration(Level level) { if (!PlasmaJetsBlock.tryConsumeContinuousFuel( level, this.cauldronPos, - CONTINUOUS_FUEL_AMOUNT + PlasmaJetsBlockEntity.CONTINUOUS_FUEL_AMOUNT )) { level.removeBlock(this.getBlockPos(), false); return; } - this.continuousFuelTimer = CONTINUOUS_FUEL_INTERVAL; + this.continuousFuelTimer = PlasmaJetsBlockEntity.CONTINUOUS_FUEL_INTERVAL; } return; } this.duration--; if ( - this.duration + MAX_DURATION / 2 < MAX_DURATION + this.duration + PlasmaJetsBlockEntity.MAX_DURATION / 2 < PlasmaJetsBlockEntity.MAX_DURATION && PlasmaJetsBlock.tryConsumeOnce(level, Objects.requireNonNull(this.cauldronPos)) ) { - this.duration += MAX_DURATION / 2; + this.duration += PlasmaJetsBlockEntity.MAX_DURATION / 2; } if (this.duration < 0) { level.removeBlock(this.getBlockPos(), false); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/PowerConverterBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/PowerConverterBlockEntity.java index 38215b281f..4649a9179e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/PowerConverterBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/PowerConverterBlockEntity.java @@ -32,7 +32,6 @@ public class PowerConverterBlockEntity extends BlockEntity implements IPowerCons @Getter @Setter private @Nullable PowerGrid grid = null; - @Getter private int inputPower; private int cooldown = 0; int energy = 0; @@ -63,7 +62,7 @@ public int getInputPower() { @Override public @Nullable EnergyHandler getEnergyHandler(@Nullable Direction side) { if (side == null) return new PowerConverterEnergyStore(); - if (side == getBlockState().getValue(BasePowerConverterBlock.FACING)) return new PowerConverterEnergyStore(); + if (side == this.getBlockState().getValue(BasePowerConverterBlock.FACING)) return new PowerConverterEnergyStore(); return null; } @@ -112,12 +111,12 @@ public int getMaxEnergyStored() { /// tick public void tick() { if (this.level != null) { - flushState(this.level, getBlockPos()); + this.flushState(this.level, this.getBlockPos()); if (this.getBlockState().getValue(BasePowerConverterBlock.POWERED)) return; } if (this.cooldown == 0) { this.cooldown = AnvilCraft.CONFIG.powerConverter.powerConverterCountdown; - if (getBlockState().getValue(BasePowerConverterBlock.OVERLOAD)) return; + if (this.getBlockState().getValue(BasePowerConverterBlock.OVERLOAD)) return; int amountTick = (int) ( this.inputPower * AnvilCraft.CONFIG.powerConverter.powerConverterEfficiency @@ -125,22 +124,22 @@ public void tick() { ); int amount = amountTick * AnvilCraft.CONFIG.powerConverter.powerConverterCountdown; this.energy = Math.min(this.energy + amount, this.getMaxEnergy()); - setChanged(); + this.setChanged(); } else { this.cooldown--; } this.pushEnergy(); - if (this.level != null && level.getGameTime() % 20 == 0) { - level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_ALL); + if (this.level != null && this.level.getGameTime() % 20 == 0) { + this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), Block.UPDATE_ALL); } } private void pushEnergy() { if (this.level == null || this.energy <= 0) return; - Direction face = getBlockState().getValue(BasePowerConverterBlock.FACING); - EnergyHandler target = level.getCapability( + Direction face = this.getBlockState().getValue(BasePowerConverterBlock.FACING); + EnergyHandler target = this.level.getCapability( Capabilities.Energy.BLOCK, - getBlockPos().relative(face), + this.getBlockPos().relative(face), face.getOpposite() ); if (target != null) { @@ -149,20 +148,20 @@ private void pushEnergy() { transaction.commit(); if (accepted > 0) { this.energy -= accepted; - setChanged(); + this.setChanged(); } } } } @Override - public Level getCurrentLevel() { - return getLevel(); + public @Nullable Level getCurrentLevel() { + return this.getLevel(); } @Override public BlockPos getPos() { - return getBlockPos(); + return this.getBlockPos(); } class PowerConverterEnergyStore implements EnergyHandler { @@ -188,7 +187,7 @@ public int extract(int maxExtract, TransactionContext transaction) { int r = Math.min(PowerConverterBlockEntity.this.energy, maxExtract); if (r > 0) { PowerConverterBlockEntity.this.energy -= r; - setChanged(); + PowerConverterBlockEntity.this.setChanged(); } return r; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/PropelPistonBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/PropelPistonBlockEntity.java index ce212dd664..a4dd74fec1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/PropelPistonBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/PropelPistonBlockEntity.java @@ -42,7 +42,7 @@ public PropelPistonBlockEntity(BlockEntityType type, BlockPos pos, BlockState @Override public Direction getFacing() { - return getBlockState().getValue(PropelPistonBlock.FACING); + return this.getBlockState().getValue(PropelPistonBlock.FACING); } public void notifyMoved() { @@ -53,18 +53,18 @@ public void notifyMoved() { public void updateStoredEnergy(Integer energy) { this.storedEnergy = Math.clamp(energy, 0, 160000000); - if (level == null || !(level instanceof ServerLevel serverLevel)) { + if (this.level == null || !(this.level instanceof ServerLevel serverLevel)) { return; } PacketDistributor.sendToPlayersTrackingChunk( serverLevel, - ChunkPos.containing(getBlockPos()), - new UpdatePropelPistonStoredEnergyPacket(getBlockPos(), this.storedEnergy) + ChunkPos.containing(this.getBlockPos()), + new UpdatePropelPistonStoredEnergyPacket(this.getBlockPos(), this.storedEnergy) ); } public void addEnergy(int energy) { - this.updateStoredEnergy(getStoredEnergy() + energy); + this.updateStoredEnergy(this.getStoredEnergy() + energy); } @Override @@ -73,12 +73,12 @@ protected int getBaseLaserLevel() { } public void tick(Level level, BlockPos pos, BlockState state) { - updateLaserLevel(calculateLaserLevel()); - if (changed) { + this.updateLaserLevel(this.calculateLaserLevel()); + if (this.changed) { this.delay = 0; - this.power = laserLevel * 15; + this.power = this.laserLevel * 15; } - if (!changed) { + if (!this.changed) { if (this.storedEnergy < 160000000) { this.delay++; if (this.delay >= 20) { @@ -87,7 +87,7 @@ public void tick(Level level, BlockPos pos, BlockState state) { } } } - if (getStoredEnergy() > 0) { + if (this.getStoredEnergy() > 0) { level.setBlockAndUpdate(pos, state.setValue(PropelPistonBlock.EXHAUSTED, false)); if (!level.getBlockTicks().hasScheduledTick(pos, state.getBlock())) { this.checkCanMove(level, pos, state); @@ -96,13 +96,13 @@ public void tick(Level level, BlockPos pos, BlockState state) { level.setBlockAndUpdate(pos, state.setValue(PropelPistonBlock.EXHAUSTED, true).setValue(PropelPistonBlock.MOVING, false)); } super.tick(level); - resetState(); + this.resetState(); } @Override public Set getIgnoreFace() { Set directions = new HashSet<>(List.of(Direction.values())); - directions.remove(getBlockState().getValue(PropelPistonBlock.FACING).getOpposite()); + directions.remove(this.getBlockState().getValue(PropelPistonBlock.FACING).getOpposite()); return directions; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/PulseGeneratorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/PulseGeneratorBlockEntity.java index 82f2a82896..8eb1d7c70b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/PulseGeneratorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/PulseGeneratorBlockEntity.java @@ -260,7 +260,7 @@ public Component getDisplayName() { @Override public @Nullable AbstractContainerMenu createMenu(int containerId, Inventory inventory, Player player) { if (player.isSpectator()) return null; - if (player.level().getBlockEntity(getBlockPos()) instanceof PulseGeneratorBlockEntity blockEntity) { + if (player.level().getBlockEntity(this.getBlockPos()) instanceof PulseGeneratorBlockEntity blockEntity) { return new PulseGeneratorMenu(ModMenuTypes.PULSE_GENERATOR.get(), containerId, inventory, blockEntity); } return null; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/ResentfulAmberBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/ResentfulAmberBlockEntity.java index 87107213ae..2707127aa1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/ResentfulAmberBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/ResentfulAmberBlockEntity.java @@ -1,6 +1,5 @@ package dev.dubhe.anvilcraft.block.entity; -import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; @@ -33,7 +32,7 @@ public static ResentfulAmberBlockEntity createBlockEntity( // @OnlyIn(Dist.CLIENT) public void clientTick(Level level, BlockPos blockPos) { - Entity displayEntity = getOrCreateDisplayEntity(level); + Entity displayEntity = this.getOrCreateDisplayEntity(level); if (displayEntity == null) return; Vec3 center = blockPos.getCenter(); Player nearest = level.getNearestPlayer( diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyLaserBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyLaserBlockEntity.java index 78a4a1ffee..203f410a22 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyLaserBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyLaserBlockEntity.java @@ -1,5 +1,6 @@ package dev.dubhe.anvilcraft.block.entity; +import dev.dubhe.anvilcraft.api.power.IPowerComponent; import dev.dubhe.anvilcraft.api.power.IPowerConsumer; import dev.dubhe.anvilcraft.api.power.PowerGrid; import dev.dubhe.anvilcraft.block.laser.RubyLaserBlock; @@ -41,16 +42,16 @@ public void tick(Level level) { if (this.getGrid() != null && this.getBlockState().getValue(RubyLaserBlock.OVERLOAD) == this.getGrid().isWorking()) { level.setBlock( this.getPos(), - this.getBlockState().setValue(OVERLOAD, !this.getGrid().isWorking()), + this.getBlockState().setValue(IPowerComponent.OVERLOAD, !this.getGrid().isWorking()), 2 ); } - if (level.hasNeighborSignal(getBlockPos()) == (this.getBlockState().getValue(SWITCH) == Switch.ON)) { + if (level.hasNeighborSignal(this.getBlockPos()) == (this.getBlockState().getValue(IPowerComponent.SWITCH) == Switch.ON)) { level.setBlock( this.getPos(), this.getBlockState().setValue( - SWITCH, - level.hasNeighborSignal(getBlockPos()) + IPowerComponent.SWITCH, + level.hasNeighborSignal(this.getBlockPos()) ? Switch.OFF : Switch.ON ), @@ -59,8 +60,8 @@ public void tick(Level level) { if (this.isSwitchedOn()) { this.emitLaser(this.getFacing()); } else { - if (irradiateBlockPos != null - && level.getBlockEntity(irradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity + if (this.irradiateBlockPos != null + && level.getBlockEntity(this.irradiateBlockPos) instanceof BaseLaserBlockEntity irradiateBlockEntity ) { irradiateBlockEntity.onCancelingIrradiation(this); } @@ -70,8 +71,8 @@ public void tick(Level level) { } public boolean isSwitchedOn() { - return getBlockState().getValue(RubyLaserBlock.SWITCH) == Switch.ON - && !getBlockState().getValue(RubyLaserBlock.OVERLOAD); + return this.getBlockState().getValue(RubyLaserBlock.SWITCH) == Switch.ON + && !this.getBlockState().getValue(RubyLaserBlock.OVERLOAD); } @Override @@ -80,18 +81,18 @@ public void onIrradiated(BaseLaserBlockEntity baseLaserBlockEntity) { @Override public @Nullable Level getCurrentLevel() { - return level; + return this.level; } @Override public BlockPos getPos() { - return getBlockPos(); + return this.getBlockPos(); } @Override public int getInputPower() { - if (level == null) return 16; - return getBlockState().getValue(RubyLaserBlock.SWITCH) == Switch.OFF ? 0 : 16; + if (this.level == null) return 16; + return this.getBlockState().getValue(RubyLaserBlock.SWITCH) == Switch.OFF ? 0 : 16; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyPrismBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyPrismBlockEntity.java index 2169b09bac..63f09be7a5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyPrismBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/RubyPrismBlockEntity.java @@ -6,6 +6,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; +import org.jspecify.annotations.Nullable; public class RubyPrismBlockEntity extends BaseLaserBlockEntity { private boolean enabled = false; @@ -24,13 +25,13 @@ public static RubyPrismBlockEntity createBlockEntity( public void tick(Level level) { if (this.enabled) { - emitLaser(this.getFacing()); + this.emitLaser(this.getFacing()); } - if (laserLevel == 0) { + if (this.laserLevel == 0) { this.enabled = false; } super.tick(level); - resetState(); + this.resetState(); } @Override @@ -40,7 +41,7 @@ protected int getBaseLaserLevel() { @Override public void onCancelingIrradiation(BaseLaserBlockEntity baseLaserBlockEntity) { - if (!irradiateSelfLaserBlockSet.contains(baseLaserBlockEntity)) return; + if (!this.irradiateSelfLaserBlockSet.contains(baseLaserBlockEntity)) return; super.onCancelingIrradiation(baseLaserBlockEntity); this.enabled = !this.irradiateSelfLaserBlockSet.isEmpty(); } @@ -66,13 +67,13 @@ public int getLaserLevel() { } @Override - public void clientUpdate(BlockPos irradiateBlockPos, int laserLevel) { + public void clientUpdate(@Nullable BlockPos irradiateBlockPos, int laserLevel) { this.enabled = laserLevel > 0; super.clientUpdate(irradiateBlockPos, laserLevel); } @Override public Direction getFacing() { - return getBlockState().getValue(RubyPrismBlock.FACING); + return this.getBlockState().getValue(RubyPrismBlock.FACING); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleChuteBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleChuteBlockEntity.java index ae2e902e7d..bca6de17f6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleChuteBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleChuteBlockEntity.java @@ -207,13 +207,19 @@ public void convertTo(ChuteBlockEntity newBe) { return; } - AnvilUtil.dropItems(Collections.singletonList(stack), this.level, newBe.getBlockPos().getCenter()); + Level level = this.level; + if (level != null) { + AnvilUtil.dropItems(Collections.singletonList(stack), level, newBe.getBlockPos().getCenter()); + } } @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); Vec3 center = pos.getCenter(); - Containers.dropItemStack(this.level, center.x, center.y, center.z, this.itemHandler.getStack()); + Level level = this.level; + if (level != null) { + Containers.dropItemStack(level, center.x, center.y, center.z, this.itemHandler.getStack()); + } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleMagneticChuteBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleMagneticChuteBlockEntity.java index fdcae0341c..bbaee0a9ab 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleMagneticChuteBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/SimpleMagneticChuteBlockEntity.java @@ -54,7 +54,7 @@ private static final class TrackedEjectedItem { private TrackedEjectedItem(ItemEntity item) { this.item = item; this.wasOnGround = item.onGround(); - this.ticksLeft = EJECTED_ITEM_TRACK_TICKS; + this.ticksLeft = SimpleMagneticChuteBlockEntity.EJECTED_ITEM_TRACK_TICKS; } } @@ -232,6 +232,9 @@ public boolean isEmpty() { public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); Vec3 center = pos.getCenter(); - Containers.dropItemStack(this.level, center.x, center.y, center.z, this.itemHandler.getStack()); + var level = this.level; + if (level != null) { + Containers.dropItemStack(level, center.x, center.y, center.z, this.itemHandler.getStack()); + } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/SmartBlockPlacerBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/SmartBlockPlacerBlockEntity.java index ad82965023..99fd10a117 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/SmartBlockPlacerBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/SmartBlockPlacerBlockEntity.java @@ -35,6 +35,7 @@ import lombok.Setter; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.FrontAndTop; import net.minecraft.core.HolderLookup; import net.minecraft.core.UUIDUtil; import net.minecraft.nbt.CompoundTag; @@ -45,6 +46,7 @@ import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; import net.minecraft.util.ProblemReporter; import net.minecraft.world.InteractionResult; import net.minecraft.world.MenuProvider; @@ -71,6 +73,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.piston.PistonBaseBlock; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.AttachFace; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.block.state.properties.Half; @@ -112,7 +115,7 @@ public static int getPlacementInterval() { } public static int getPlacementDelay() { - return Math.max(1, (int) (getPlacementInterval() * 0.3f)); + return Math.max(1, (int) (SmartBlockPlacerBlockEntity.getPlacementInterval() * 0.3f)); } // 白名单:蓝图中需要保留的方块状态属性 @@ -170,7 +173,7 @@ public static int getPlacementDelay() { // 基于属性名称的白名单集合(按名称匹配而非对象相等,解决不同方块同名Property非同一实例的问题) private static final Set INHERITED_PROPERTY_NAMES = - INHERITED_PROPERTIES.stream().map(Property::getName).collect(ImmutableSet.toImmutableSet()); + SmartBlockPlacerBlockEntity.INHERITED_PROPERTIES.stream().map(Property::getName).collect(ImmutableSet.toImmutableSet()); // 标记当前是否有方块正在被智能放置器移动 private static final ThreadLocal IS_BEING_MOVED_BY_PLACER = ThreadLocal.withInitial(() -> false); @@ -277,7 +280,7 @@ public int getCurrentPlacementIndex() { @Nullable public BlockPos getSyncedAnimationTargetPos() { - return readBlockPos(this.animationTargetPosProxy.getValue()); + return SmartBlockPlacerBlockEntity.readBlockPos(this.animationTargetPosProxy.getValue()); } public boolean isPowered() { @@ -376,46 +379,46 @@ public static SmartBlockPlacerBlockEntity createBlockEntity( protected void saveAdditional(ValueOutput output) { super.saveAdditional(output); // 物品栏直接保存到ValueOutput(不通过CompoundTag中转,避免兼容性问题) - saveInventoryToOutput(output, "diskInventory", this.diskInventory); - saveInventoryToOutput(output, "bookInventory", this.bookInventory); - saveInventoryToOutput(output, "outputBookInventory", this.outputBookInventory); + SmartBlockPlacerBlockEntity.saveInventoryToOutput(output, "diskInventory", this.diskInventory); + SmartBlockPlacerBlockEntity.saveInventoryToOutput(output, "bookInventory", this.bookInventory); + SmartBlockPlacerBlockEntity.saveInventoryToOutput(output, "outputBookInventory", this.outputBookInventory); // 其他数据仍通过CompoundTag保存 CompoundTag tag = new CompoundTag(); this.saveAdditionalDataToTag(tag); - output.store(DATA_KEY, CompoundTag.CODEC, tag); + output.store(SmartBlockPlacerBlockEntity.DATA_KEY, CompoundTag.CODEC, tag); } protected void saveAdditional(CompoundTag tag, HolderLookup.Provider ignored) { this.saveAdditionalDataToTag(tag); // 旧路径也保存物品栏(向后兼容) - saveItemsToTag(tag, this.diskInventory); - saveItemsToTag(tag, this.bookInventory); - saveItemsToTag(tag, this.outputBookInventory); + SmartBlockPlacerBlockEntity.saveItemsToTag(tag, this.diskInventory); + SmartBlockPlacerBlockEntity.saveItemsToTag(tag, this.bookInventory); + SmartBlockPlacerBlockEntity.saveItemsToTag(tag, this.outputBookInventory); } @Override public void loadAdditional(ValueInput input) { super.loadAdditional(input); // 物品栏直接从ValueInput加载 - loadInventoryFromInput(input, "diskInventory", this.diskInventory); + SmartBlockPlacerBlockEntity.loadInventoryFromInput(input, "diskInventory", this.diskInventory); this.lastDiskItem = this.diskInventory.getItem(0).copy(); - loadInventoryFromInput(input, "bookInventory", this.bookInventory); - loadInventoryFromInput(input, "outputBookInventory", this.outputBookInventory); + SmartBlockPlacerBlockEntity.loadInventoryFromInput(input, "bookInventory", this.bookInventory); + SmartBlockPlacerBlockEntity.loadInventoryFromInput(input, "outputBookInventory", this.outputBookInventory); // 其他数据从CompoundTag加载 - CompoundTag tag = input.read(DATA_KEY, CompoundTag.CODEC).orElse(new CompoundTag()); + CompoundTag tag = input.read(SmartBlockPlacerBlockEntity.DATA_KEY, CompoundTag.CODEC).orElse(new CompoundTag()); this.loadFromTag(tag); } public void loadAdditional(CompoundTag tag, HolderLookup.Provider ignored) { // 先加载物品栏,确保 tryLoadStructure 能正确访问到磁盘物品 // 否则 loadFromTag 中加载的 cachedStructure 会被 tryLoadStructure 误判清空 - loadItemsFromTag(tag, this.diskInventory); + SmartBlockPlacerBlockEntity.loadItemsFromTag(tag, this.diskInventory); this.lastDiskItem = this.diskInventory.getItem(0).copy(); - loadItemsFromTag(tag, this.bookInventory); - loadItemsFromTag(tag, this.outputBookInventory); + SmartBlockPlacerBlockEntity.loadItemsFromTag(tag, this.bookInventory); + SmartBlockPlacerBlockEntity.loadItemsFromTag(tag, this.outputBookInventory); // 结构数据存储在 DATA_KEY 子节点下,需要提取后再传入 loadFromTag - CompoundTag dataTag = tag.contains(DATA_KEY) - ? tag.getCompoundOrEmpty(DATA_KEY) + CompoundTag dataTag = tag.contains(SmartBlockPlacerBlockEntity.DATA_KEY) + ? tag.getCompoundOrEmpty(SmartBlockPlacerBlockEntity.DATA_KEY) : tag; this.loadFromTag(dataTag); } @@ -489,7 +492,7 @@ public void onChanged() { this.placeCooldownProxy.setValue(this.placeCooldown); this.currentHeldBlockProxy.setValue(this.currentHeldBlock); this.currentPlacementIndexProxy.setValue(this.currentPlacementIndex); - this.animationTargetPosProxy.setValue(writeBlockPos(this.serverAnimationTargetPos)); + this.animationTargetPosProxy.setValue(SmartBlockPlacerBlockEntity.writeBlockPos(this.serverAnimationTargetPos)); this.isPoweredProxy.setValue(this.isPowered); this.hasRedstoneSignalProxy.setValue(this.hasRedstoneSignal); if (!level.isClientSide()) { @@ -791,19 +794,20 @@ private int calculateComparatorSignal() { // 蓝图模式:基于结构数据计算进度 if (this.loadedStructure != null && !this.loadedStructure.isEmpty()) { // 获取旋转后的结构数据 - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); // 获取所有位置 Direction facing = this.getFacing(this.getBlockPos(), this.level); boolean upsideDown = this.level.getBlockState(this.getBlockPos()).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); - List allPositions = buildBlueprintPositions(this.getBlockPos(), facing, upsideDown, rotatedData); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions( + this.getBlockPos(), facing, upsideDown, rotatedData); if (allPositions.isEmpty()) { return 0; } // 获取有序索引列表(只包含主体部件,多方块结构的次要部件已被过滤) - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); int totalBlocks = orderedIndices.size(); if (totalBlocks == 0) { @@ -960,12 +964,12 @@ private void updateMissingBlockInfo(Level level, BlockPos pos) { } // 获取旋转后的结构数据 - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); // 获取所有位置 Direction facing = this.getFacing(pos, level); boolean upsideDown = level.getBlockState(pos).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); - List allPositions = buildBlueprintPositions(pos, facing, upsideDown, rotatedData); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions(pos, facing, upsideDown, rotatedData); if (allPositions.isEmpty() || rotatedData.blocks.isEmpty()) { if (!this.missingBlockItem.isEmpty()) { @@ -976,7 +980,7 @@ private void updateMissingBlockInfo(Level level, BlockPos pos) { } // 获取有序索引列表 - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); // 遍历所有位置,找到第一个未放置且缺少材料的位置 for (int index : orderedIndices) { @@ -1051,7 +1055,7 @@ public static StructureLoadUtil.StructureData rotateStructureDataStatic( StructureLoadUtil.StructureData result = new StructureLoadUtil.StructureData(originalData.diskData); for (var bp : originalData.blocks) { - BlockState rotatedState = rotateBlockStateForPreview(bp.state(), scannerFacing); + BlockState rotatedState = SmartBlockPlacerBlockEntity.rotateBlockStateForPreview(bp.state(), scannerFacing); result.blocks.add(new StructureLoadUtil.BlockPosition(bp.x(), bp.y(), bp.z(), rotatedState)); } @@ -1064,20 +1068,20 @@ public static StructureLoadUtil.StructureData rotateStructureDataStatic( private static BlockState rotateBlockStateForPreview(BlockState state, Direction scannerFacing) { if (state.hasProperty(BlockStateProperties.HORIZONTAL_FACING)) { Direction blockFacing = state.getValue(BlockStateProperties.HORIZONTAL_FACING); - Direction rotatedFacing = rotateDirectionForPreview(blockFacing, scannerFacing); + Direction rotatedFacing = SmartBlockPlacerBlockEntity.rotateDirectionForPreview(blockFacing, scannerFacing); return state.setValue(BlockStateProperties.HORIZONTAL_FACING, rotatedFacing); } if (state.hasProperty(HorizontalDirectionalBlock.FACING)) { Direction blockFacing = state.getValue(HorizontalDirectionalBlock.FACING); - Direction rotatedFacing = rotateDirectionForPreview(blockFacing, scannerFacing); + Direction rotatedFacing = SmartBlockPlacerBlockEntity.rotateDirectionForPreview(blockFacing, scannerFacing); return state.setValue(HorizontalDirectionalBlock.FACING, rotatedFacing); } if (state.hasProperty(BlockStateProperties.FACING)) { Direction blockFacing = state.getValue(BlockStateProperties.FACING); if (blockFacing == Direction.UP || blockFacing == Direction.DOWN) return state; - Direction rotatedFacing = rotateDirectionForPreview(blockFacing, scannerFacing); + Direction rotatedFacing = SmartBlockPlacerBlockEntity.rotateDirectionForPreview(blockFacing, scannerFacing); return state.setValue(BlockStateProperties.FACING, rotatedFacing); } @@ -1163,7 +1167,7 @@ public void tickClient() { Integer cooldownValue = this.placeCooldownProxy.getValue(); int cooldown = cooldownValue != null ? cooldownValue : 0; boolean isNewCycle = cooldown > this.lastPlaceCooldown - && cooldown >= getPlacementInterval(); + && cooldown >= SmartBlockPlacerBlockEntity.getPlacementInterval(); boolean wasIdle = this.lastPlaceCooldown == 0; boolean isNowWorking = cooldown > 0; @@ -1251,13 +1255,13 @@ private boolean checkResourceDepleted(Level level, BlockPos pos, WorkMode mode) } // 使用旋转后的结构数据 - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); // 获取倒挂状态 boolean upsideDown = level.getBlockState(pos).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); // 获取有序索引列表 - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); boolean indexExhausted = this.currentPlacementIndex >= orderedIndices.size(); if (indexExhausted) { @@ -1383,8 +1387,8 @@ private void prepareBlueprintModeHeldBlock(Level level, BlockPos pos) { Direction facing = this.getFacing(pos, level); boolean upsideDown = level.getBlockState(pos).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); - List allPositions = buildBlueprintPositions(pos, facing, upsideDown, rotatedData); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions(pos, facing, upsideDown, rotatedData); if (allPositions.isEmpty()) { this.currentHeldBlock = ItemStack.EMPTY; @@ -1392,7 +1396,7 @@ private void prepareBlueprintModeHeldBlock(Level level, BlockPos pos) { } // 获取有序索引列表 - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); if (orderedIndices.isEmpty()) { this.currentHeldBlock = ItemStack.EMPTY; return; @@ -1591,7 +1595,7 @@ private void tickCommonCooldownLogic( boolean shouldDecrementCooldown = currentGameTime != this.lastTickGameTime; if (this.placeCooldown > 0 && shouldDecrementCooldown) { - if (this.placeCooldown == getPlacementDelay() && shouldExecute) { + if (this.placeCooldown == SmartBlockPlacerBlockEntity.getPlacementDelay() && shouldExecute) { if (this.currentHeldBlock.isEmpty()) { this.currentPlacementIndex = 0; } @@ -1608,7 +1612,7 @@ private void tickCommonCooldownLogic( if (this.placeCooldown == 0 && shouldExecute) { onCycleStart.run(); - this.placeCooldown = getPlacementInterval(); + this.placeCooldown = SmartBlockPlacerBlockEntity.getPlacementInterval(); this.lastTickGameTime = currentGameTime; this.onChanged(); } @@ -1692,15 +1696,15 @@ private boolean hasBlueprintPositions(Level level, BlockPos placerPos) { Direction facing = this.getFacing(placerPos, level); boolean upsideDown = level.getBlockState(placerPos).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); - List allPositions = buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); if (allPositions.isEmpty()) { return false; } // 检查是否还有空位(按有序索引遍历,跳过次要部件) - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); for (int index : orderedIndices) { // 跳过多方块方块的次要部件 if (index < rotatedData.blocks.size() @@ -1738,15 +1742,15 @@ private boolean hasBlueprintMoveTargets(Level level, BlockPos placerPos) { return false; } - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); - List allPositions = buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); if (allPositions.isEmpty()) { return false; } // 检查是否还有可放置的蓝图位置(跳过次要部件) - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); for (int index : orderedIndices) { // 跳过多方块方块的次要部件 if (index < rotatedData.blocks.size() @@ -2003,11 +2007,11 @@ private void moveBlocks(Level level, BlockPos placerPos) { BlockState stateToPlace = this.getMovedPlacementState(sourceState, level, targetPos); // 先删除源方块,再放置,放置失败则回滚 - IS_BEING_MOVED_BY_PLACER.set(true); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(true); try { level.removeBlock(sourcePos, false); } finally { - IS_BEING_MOVED_BY_PLACER.set(false); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(false); } boolean placeSuccess = this.tryPlaceBlockWithFakePlayer( @@ -2017,7 +2021,7 @@ private void moveBlocks(Level level, BlockPos placerPos) { if (!placeSuccess) { // 放置失败,回滚源方块 - IS_BEING_MOVED_BY_PLACER.set(true); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(true); try { level.setBlock(sourcePos, sourceState, Block.UPDATE_CLIENTS | Block.UPDATE_NEIGHBORS); if (sourceBlockEntityData != null) { @@ -2029,7 +2033,7 @@ private void moveBlocks(Level level, BlockPos placerPos) { } } } finally { - IS_BEING_MOVED_BY_PLACER.set(false); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(false); } this.currentHeldBlock = ItemStack.EMPTY; this.currentPlacementIndex = (index + 1) % allPositions.size(); @@ -2047,9 +2051,9 @@ private void moveBlocks(Level level, BlockPos placerPos) { } } - updatePlacedBlock(level, targetPos); + SmartBlockPlacerBlockEntity.updatePlacedBlock(level, targetPos); - if (targetPos.equals(this.expectedShuttleTarget)) { + if (Objects.equals(targetPos, this.expectedShuttleTarget)) { TriggerUtil.placerShuttle(level, targetPos); this.expectedShuttleTarget = null; } @@ -2120,7 +2124,7 @@ private boolean isMySourceInNeighborTargets(Level level, for (var entry : neighborPlacer.layerPositions.entrySet()) { int layer = entry.getKey(); for (int position : entry.getValue()) { - BlockPos neighborTarget = calculateTargetPosition( + BlockPos neighborTarget = SmartBlockPlacerBlockEntity.calculateTargetPosition( basePos, neighborFacing, position / 5, position % 5, layer, upsideDown); if (neighborTarget.equals(mySource)) { return true; @@ -2142,15 +2146,15 @@ private void placeBlueprintBlocks(Level level, BlockPos placerPos) { } // 获取旋转后的结构数据 - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); - List allPositions = buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); if (allPositions.isEmpty()) { return; } // 获取有序索引列表(按 y → z → x 排序) - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); if (orderedIndices.isEmpty()) { return; } @@ -2254,7 +2258,7 @@ private void placeBlueprintBlocks(Level level, BlockPos placerPos) { // 多方块方块使用蓝图中的朝向进行放置,确保所有部件位置正确 Direction placementFacing = facing; if (StructureLoadUtil.isMultiblockBlock(requiredBlock)) { - Direction desiredFacing = extractDesiredHorizontalFacing(blueprintState); + Direction desiredFacing = SmartBlockPlacerBlockEntity.extractDesiredHorizontalFacing(blueprintState); if (desiredFacing != null) { placementFacing = desiredFacing; } @@ -2316,15 +2320,15 @@ private void moveBlueprintBlocks(Level level, BlockPos placerPos) { } // 获取旋转后的结构数据 - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); - List allPositions = buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions(placerPos, facing, upsideDown, rotatedData); if (allPositions.isEmpty()) { return; } // 获取有序索引列表(按 y → z → x 排序) - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); if (orderedIndices.isEmpty()) { return; } @@ -2396,18 +2400,18 @@ private void moveBlueprintBlocks(Level level, BlockPos placerPos) { // 多方块方块使用蓝图中的朝向进行放置,确保所有部件位置正确 Direction placementFacing = facing; if (StructureLoadUtil.isMultiblockBlock(requiredBlock)) { - Direction desiredFacing = extractDesiredHorizontalFacing(blueprintState); + Direction desiredFacing = SmartBlockPlacerBlockEntity.extractDesiredHorizontalFacing(blueprintState); if (desiredFacing != null) { placementFacing = desiredFacing; } } // 先删除源方块,再使用 FakePlayer 放置方块 - IS_BEING_MOVED_BY_PLACER.set(true); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(true); try { level.removeBlock(sourcePos, false); } finally { - IS_BEING_MOVED_BY_PLACER.set(false); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(false); } boolean placeSuccess = this.tryPlaceBlockWithFakePlayer( @@ -2417,7 +2421,7 @@ private void moveBlueprintBlocks(Level level, BlockPos placerPos) { if (!placeSuccess) { // 放置失败,回滚源方块 - IS_BEING_MOVED_BY_PLACER.set(true); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(true); try { level.setBlock(sourcePos, sourceState, Block.UPDATE_CLIENTS | Block.UPDATE_NEIGHBORS); if (sourceBlockEntityData != null) { @@ -2429,7 +2433,7 @@ private void moveBlueprintBlocks(Level level, BlockPos placerPos) { } } } finally { - IS_BEING_MOVED_BY_PLACER.set(false); + SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.set(false); } this.currentHeldBlock = ItemStack.EMPTY; this.currentPlacementIndex = (orderIndex + 1) % orderedIndices.size(); @@ -2453,7 +2457,7 @@ private void moveBlueprintBlocks(Level level, BlockPos placerPos) { } // 在目标位置发送方块更新通知 - updatePlacedBlock(level, targetPos); + SmartBlockPlacerBlockEntity.updatePlacedBlock(level, targetPos); // 放置成功,清空 currentHeldBlock;下一轮 prepareHeldBlock 会重新设置 this.currentHeldBlock = ItemStack.EMPTY; @@ -2645,7 +2649,7 @@ private void executeUnifiedBlockOperationWithExtraction( */ private List buildOrderedPositionsFromLayers(BlockPos placerPos, Direction facing, boolean upsideDown) { BlockPos basePos = placerPos.relative(facing.getOpposite(), -4); - return buildOrderedPositions(basePos, facing, this.layerPositions, upsideDown); + return SmartBlockPlacerBlockEntity.buildOrderedPositions(basePos, facing, this.layerPositions, upsideDown); } /** @@ -2674,7 +2678,7 @@ public static List buildBlueprintPositions( // 根据放置器朝向和Scanner朝向计算实际旋转 // Scanner和Placer南北相反,需要修正 - Rotation rotation = getRotationForPlacement(forward, rotatedData.diskData.direction()); + Rotation rotation = SmartBlockPlacerBlockEntity.getRotationForPlacement(forward, rotatedData.diskData.direction()); // 使用原始坐标,但相对于中心点偏移 for (StructureLoadUtil.BlockPosition blueprintBlock : rotatedData.blocks) { @@ -2739,7 +2743,7 @@ private static int calculateRotationSteps(Direction forward, Direction scannerFa * @return Minecraft Rotation对象 */ private static Rotation getRotationForPlacement(Direction forward, Direction scannerFacing) { - int rotationSteps = calculateRotationSteps(forward, scannerFacing); + int rotationSteps = SmartBlockPlacerBlockEntity.calculateRotationSteps(forward, scannerFacing); return switch (rotationSteps) { case 1 -> Rotation.CLOCKWISE_90; case 2 -> Rotation.CLOCKWISE_180; @@ -2793,18 +2797,18 @@ public static BlockState flipHalfPropertyStatic(BlockState state) { // 处理六向方块的 ORIENTATION 属性(Minecraft 原生的 FrontAndTop,用于钟等方块) if (state.hasProperty(BlockStateProperties.ORIENTATION)) { - net.minecraft.core.FrontAndTop currentOrientation = + FrontAndTop currentOrientation = state.getValue(BlockStateProperties.ORIENTATION); // 倒挂时,翻转垂直方向:UP <-> DOWN,水平方向旋转180度 - net.minecraft.core.FrontAndTop flippedOrientation = switch (currentOrientation) { - case DOWN_EAST -> net.minecraft.core.FrontAndTop.UP_EAST; - case DOWN_NORTH -> net.minecraft.core.FrontAndTop.UP_NORTH; - case DOWN_SOUTH -> net.minecraft.core.FrontAndTop.UP_SOUTH; - case DOWN_WEST -> net.minecraft.core.FrontAndTop.UP_WEST; - case UP_EAST -> net.minecraft.core.FrontAndTop.DOWN_EAST; - case UP_NORTH -> net.minecraft.core.FrontAndTop.DOWN_NORTH; - case UP_SOUTH -> net.minecraft.core.FrontAndTop.DOWN_SOUTH; - case UP_WEST -> net.minecraft.core.FrontAndTop.DOWN_WEST; + FrontAndTop flippedOrientation = switch (currentOrientation) { + case DOWN_EAST -> FrontAndTop.UP_EAST; + case DOWN_NORTH -> FrontAndTop.UP_NORTH; + case DOWN_SOUTH -> FrontAndTop.UP_SOUTH; + case DOWN_WEST -> FrontAndTop.UP_WEST; + case UP_EAST -> FrontAndTop.DOWN_EAST; + case UP_NORTH -> FrontAndTop.DOWN_NORTH; + case UP_SOUTH -> FrontAndTop.DOWN_SOUTH; + case UP_WEST -> FrontAndTop.DOWN_WEST; // 侧向附着不需要垂直翻转 case WEST_UP, EAST_UP, NORTH_UP, SOUTH_UP -> currentOrientation; }; @@ -2827,13 +2831,13 @@ public static BlockState flipHalfPropertyStatic(BlockState state) { // 处理 ATTACH_FACE 属性(墙面附着方块,如按钮、压力板等) if (state.hasProperty(BlockStateProperties.ATTACH_FACE)) { - net.minecraft.world.level.block.state.properties.AttachFace currentFace = + AttachFace currentFace = state.getValue(BlockStateProperties.ATTACH_FACE); - net.minecraft.world.level.block.state.properties.AttachFace flippedFace = + AttachFace flippedFace = switch (currentFace) { - case CEILING -> net.minecraft.world.level.block.state.properties.AttachFace.FLOOR; - case FLOOR -> net.minecraft.world.level.block.state.properties.AttachFace.CEILING; - case WALL -> net.minecraft.world.level.block.state.properties.AttachFace.WALL; + case CEILING -> AttachFace.FLOOR; + case FLOOR -> AttachFace.CEILING; + case WALL -> AttachFace.WALL; }; return state.setValue(BlockStateProperties.ATTACH_FACE, flippedFace); } @@ -2857,7 +2861,7 @@ public static BlockState flipHalfPropertyStatic(BlockState state) { * @return 翻转 half 属性后的方块状态 */ private static BlockState flipHalfProperty(BlockState state) { - return flipHalfPropertyStatic(state); + return SmartBlockPlacerBlockEntity.flipHalfPropertyStatic(state); } /** @@ -2911,7 +2915,7 @@ public Block getRequiredBlockForPosition(int index) { } // 获取旋转后的结构数据 - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); if (index < 0 || index >= rotatedData.blocks.size()) { return null; } @@ -2933,15 +2937,16 @@ public BlockPos getCurrentBlueprintTargetPosition() { Direction facing = this.getFacing(this.getBlockPos(), this.level); boolean upsideDown = this.level.getBlockState(this.getBlockPos()).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); - StructureLoadUtil.StructureData rotatedData = rotateStructureDataStatic(this.loadedStructure); - List allPositions = buildBlueprintPositions(this.getBlockPos(), facing, upsideDown, rotatedData); + StructureLoadUtil.StructureData rotatedData = SmartBlockPlacerBlockEntity.rotateStructureDataStatic(this.loadedStructure); + List allPositions = SmartBlockPlacerBlockEntity.buildBlueprintPositions( + this.getBlockPos(), facing, upsideDown, rotatedData); if (allPositions.isEmpty()) { return null; } // 获取有序索引列表 - List orderedIndices = buildOrderedBlueprintIndices(rotatedData, upsideDown); + List orderedIndices = SmartBlockPlacerBlockEntity.buildOrderedBlueprintIndices(rotatedData, upsideDown); if (orderedIndices.isEmpty() || this.currentPlacementIndex >= orderedIndices.size()) { return null; } @@ -3160,7 +3165,7 @@ private BlockState getBlueprintBlockState(int index, Level level) { Direction facing = this.getFacing(this.getBlockPos(), level); // 计算旋转(与buildBlueprintPositions保持一致) - Rotation rotation = getRotationForPlacement(facing, this.loadedStructure.diskData.direction()); + Rotation rotation = SmartBlockPlacerBlockEntity.getRotationForPlacement(facing, this.loadedStructure.diskData.direction()); // 获取原始状态并应用旋转 StructureLoadUtil.StructureData originalData = this.loadedStructure; @@ -3175,7 +3180,7 @@ private BlockState getBlueprintBlockState(int index, Level level) { // 倒挂情况下,翻转 half 属性 boolean upsideDown = level.getBlockState(this.getBlockPos()).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); if (upsideDown) { - rotatedState = flipHalfProperty(rotatedState); + rotatedState = SmartBlockPlacerBlockEntity.flipHalfProperty(rotatedState); } // 应用白名单过滤:只保留白名单中的状态属性 @@ -3195,7 +3200,7 @@ private void applyBlueprintBlockFacing(Level level, BlockPos targetPos, int inde Direction facing = this.getFacing(this.getBlockPos(), level); // 计算旋转(与buildBlueprintPositions保持一致) - Rotation rotation = getRotationForPlacement(facing, this.loadedStructure.diskData.direction()); + Rotation rotation = SmartBlockPlacerBlockEntity.getRotationForPlacement(facing, this.loadedStructure.diskData.direction()); // 使用旋转后的结构数据;index 按旋转后结构数据的索引空间解释 StructureLoadUtil.StructureData originalData = this.loadedStructure; @@ -3208,7 +3213,7 @@ private void applyBlueprintBlockFacing(Level level, BlockPos targetPos, int inde // 倒挂情况下,翻转 half 属性 boolean upsideDown = level.getBlockState(this.getBlockPos()).getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); if (upsideDown) { - rotatedState = flipHalfProperty(rotatedState); + rotatedState = SmartBlockPlacerBlockEntity.flipHalfProperty(rotatedState); } BlockState worldState = level.getBlockState(targetPos); @@ -3225,7 +3230,7 @@ private void applyBlueprintBlockFacing(Level level, BlockPos targetPos, int inde } // 树叶方块特殊处理:蓝图模式下默认设置 persistent=true - if (rotatedState.is(net.minecraft.tags.BlockTags.LEAVES) + if (rotatedState.is(BlockTags.LEAVES) && rotatedState.hasProperty(BlockStateProperties.PERSISTENT)) { rotatedState = rotatedState.setValue(BlockStateProperties.PERSISTENT, true); } @@ -3308,8 +3313,8 @@ private BlockState applyWhitelistFilter(BlockState state) { // 遍历状态的属性,按名称匹配白名单(解决不同方块同名Property对象不同的问题) for (Property property : state.getProperties()) { - if (INHERITED_PROPERTY_NAMES.contains(property.getName())) { - resultState = setAllowedValue( + if (SmartBlockPlacerBlockEntity.INHERITED_PROPERTY_NAMES.contains(property.getName())) { + resultState = SmartBlockPlacerBlockEntity.setAllowedValue( (Property) property, resultState, state); } } @@ -3330,7 +3335,7 @@ public static > BlockState setAllowedValue( */ @SuppressWarnings("unused") public static boolean isBlockBeingMovedByPlacer() { - return IS_BEING_MOVED_BY_PLACER.get(); + return SmartBlockPlacerBlockEntity.IS_BEING_MOVED_BY_PLACER.get(); } /** @@ -3379,7 +3384,8 @@ public static List buildOrderedPositions( }); for (int[] rowCol : rowColList) { - positions.add(calculateTargetPosition(basePos, facing, rowCol[0], rowCol[1], layer, upsideDown)); + positions.add( + SmartBlockPlacerBlockEntity.calculateTargetPosition(basePos, facing, rowCol[0], rowCol[1], layer, upsideDown)); } } return positions; @@ -4118,8 +4124,8 @@ public void applyDataSyncFromPacket(CompoundTag tag) { this.loadedStructure = this.loadStructureData(tag.getCompoundOrEmpty("cachedStructure")); this.loadedStructureName = tag.getStringOr("cachedStructureName", ""); if (tag.contains("cachedStructureUuid")) { - this.loadedStructureUuid = net.minecraft.core.UUIDUtil.CODEC.parse( - net.minecraft.nbt.NbtOps.INSTANCE, tag.getCompoundOrEmpty("cachedStructureUuid") + this.loadedStructureUuid = UUIDUtil.CODEC.parse( + NbtOps.INSTANCE, tag.getCompoundOrEmpty("cachedStructureUuid") ).result().orElse(null); } this.hasStructureDisk = true; @@ -4296,7 +4302,7 @@ public int getInputPower() { // 20gt 时:普通模式 8kW,蓝图模式 64kW // 10gt 时:普通模式 16kW,蓝图模式 128kW int basePower = (this.loadedStructure != null && !this.loadedStructure.isEmpty()) ? 64 : SmartBlockPlacerBlockEntity.POWER; - return Math.max(1, basePower * 20 / getPlacementInterval()); + return Math.max(1, basePower * 20 / SmartBlockPlacerBlockEntity.getPlacementInterval()); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/SpaceOvercompressorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/SpaceOvercompressorBlockEntity.java index cd575b0d2c..94418b5e9f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/SpaceOvercompressorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/SpaceOvercompressorBlockEntity.java @@ -26,7 +26,7 @@ public class SpaceOvercompressorBlockEntity extends BlockEntity { public static long NEUTRONIUM_INGOT_MASS = 10_000_000; - public static long DISPLAYED_MASS = NEUTRONIUM_INGOT_MASS / 100; + public static long DISPLAYED_MASS = SpaceOvercompressorBlockEntity.NEUTRONIUM_INGOT_MASS / 100; public static int MAX_OUTPUT_PER_TIME = 640; private long storedMass = 0; @@ -88,12 +88,15 @@ public void produceNeutronium() { Level level = this.level; if (level == null) return; BlockPos pos = this.getBlockPos(); - int produceCount = (int) Math.min(MAX_OUTPUT_PER_TIME, this.storedMass / NEUTRONIUM_INGOT_MASS); + int produceCount = (int) Math.min( + SpaceOvercompressorBlockEntity.MAX_OUTPUT_PER_TIME, this.storedMass / SpaceOvercompressorBlockEntity.NEUTRONIUM_INGOT_MASS); if (produceCount <= 0) return; - this.storedMass -= produceCount * NEUTRONIUM_INGOT_MASS; - AnvilUtil.dropItems(List.of(ModItems.NEUTRONIUM_INGOT.asStack(produceCount)), + this.storedMass -= produceCount * SpaceOvercompressorBlockEntity.NEUTRONIUM_INGOT_MASS; + AnvilUtil.dropItems( + List.of(ModItems.NEUTRONIUM_INGOT.asStack(produceCount)), level, - pos.below().getCenter()); + pos.below().getCenter() + ); } public Component displayStoredMass() { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/SpacetimeSupercomputerBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/SpacetimeSupercomputerBlockEntity.java index 53da0f7dd6..4287c32f0f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/SpacetimeSupercomputerBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/SpacetimeSupercomputerBlockEntity.java @@ -42,7 +42,7 @@ public class SpacetimeSupercomputerBlockEntity extends BlockEntity implements IPowerConsumer { private static final int TICK_SPRINT_COUNTDOWN_SECONDS = 30; - private static final int TICK_SPRINT_COUNTDOWN_TICKS = TICK_SPRINT_COUNTDOWN_SECONDS * 20; + private static final int TICK_SPRINT_COUNTDOWN_TICKS = SpacetimeSupercomputerBlockEntity.TICK_SPRINT_COUNTDOWN_SECONDS * 20; private static final String TICK_SPRINT_VOTE_SEPARATOR = "------------"; private static final Set PENDING_TICK_SPRINTS = new HashSet<>(); @@ -94,7 +94,7 @@ public void addHistoryCommand(String command) { public void onChange() { this.setChanged(); if (this.level != null) { - this.level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), 3); + this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), 3); } } @@ -153,7 +153,7 @@ public void runCommand(@Nullable Player player) { if (cmd.startsWith("locate") || cmd.startsWith("time add") || cmd.startsWith("tick sprint")) { if (this.chargingProgress >= 20f) { if (cmd.startsWith("time add")) { - int timeAddConsumeProcess = getTimeAddConsumeProcess(cmd); + int timeAddConsumeProcess = SpacetimeSupercomputerBlockEntity.getTimeAddConsumeProcess(cmd); if (this.chargingProgress >= 20f + timeAddConsumeProcess) { Objects.requireNonNull(this.level.getServer()) .getCommands() @@ -167,7 +167,7 @@ public void runCommand(@Nullable Player player) { ); } } else if (cmd.startsWith("tick sprint")) { - int tickSprintConsumeProcess = getTickSprintConsumeProcess(cmd); + int tickSprintConsumeProcess = SpacetimeSupercomputerBlockEntity.getTickSprintConsumeProcess(cmd); if (this.chargingProgress >= 20f + tickSprintConsumeProcess) { if (cmd.equals("tick sprint stop")) { Objects.requireNonNull(this.level.getServer()) @@ -267,14 +267,14 @@ private void startTickSprintCountdown(@Nullable Player player, String command) { this.pendingTickSprintVoteId = UUID.randomUUID(); this.pendingTickSprintVoters.clear(); this.confirmedTickSprintVoters.clear(); - this.tickSprintCountdownTicks = TICK_SPRINT_COUNTDOWN_TICKS; - PENDING_TICK_SPRINTS.add(this); + this.tickSprintCountdownTicks = SpacetimeSupercomputerBlockEntity.TICK_SPRINT_COUNTDOWN_TICKS; + SpacetimeSupercomputerBlockEntity.PENDING_TICK_SPRINTS.add(this); this.initializeTickSprintVoters(server); this.setChanged(); } public static void cancelPendingTickSprints(MinecraftServer server) { - for (SpacetimeSupercomputerBlockEntity supercomputer : List.copyOf(PENDING_TICK_SPRINTS)) { + for (SpacetimeSupercomputerBlockEntity supercomputer : List.copyOf(SpacetimeSupercomputerBlockEntity.PENDING_TICK_SPRINTS)) { if (supercomputer.pendingTickSprintCommand != null && supercomputer.level != null && supercomputer.level.getServer() == server) { @@ -304,7 +304,7 @@ private boolean updateTickSprintVoters(MinecraftServer server) { private void sendTickSprintVoteMessage(ServerPlayer player) { MutableComponent message = Component.empty() - .append(Component.literal(TICK_SPRINT_VOTE_SEPARATOR).withStyle(ChatFormatting.DARK_GRAY)) + .append(Component.literal(SpacetimeSupercomputerBlockEntity.TICK_SPRINT_VOTE_SEPARATOR).withStyle(ChatFormatting.DARK_GRAY)) .append(Component.literal("\n")) .append(Component.translatable("block.anvilcraft.spacetime_supercomputer.tick_sprint_confirmation")) .append(Component.literal("\n")) @@ -312,7 +312,7 @@ private void sendTickSprintVoteMessage(ServerPlayer player) { .append(Component.literal(" ")) .append(this.createTickSprintVoteOption(false)) .append(Component.literal("\n")) - .append(Component.literal(TICK_SPRINT_VOTE_SEPARATOR).withStyle(ChatFormatting.DARK_GRAY)); + .append(Component.literal(SpacetimeSupercomputerBlockEntity.TICK_SPRINT_VOTE_SEPARATOR).withStyle(ChatFormatting.DARK_GRAY)); player.sendSystemMessage(message); } @@ -392,7 +392,7 @@ private void executePendingTickSprint() { ServerPlayer player = this.pendingTickSprintPlayer == null ? null : server.getPlayerList().getPlayer(this.pendingTickSprintPlayer); - int energyCost = 20 + getTickSprintConsumeProcess(normalizedCommand); + int energyCost = 20 + SpacetimeSupercomputerBlockEntity.getTickSprintConsumeProcess(normalizedCommand); if (this.chargingProgress >= energyCost) { server.getCommands().performPrefixedCommand(this.createCommandSource(player), command); this.chargingProgress -= energyCost; @@ -419,7 +419,7 @@ private void cancelTickSprintCountdown() { } private void clearTickSprintCountdown() { - PENDING_TICK_SPRINTS.remove(this); + SpacetimeSupercomputerBlockEntity.PENDING_TICK_SPRINTS.remove(this); this.pendingTickSprintCommand = null; this.pendingTickSprintPlayer = null; this.pendingTickSprintVoteId = null; @@ -431,7 +431,7 @@ private void clearTickSprintCountdown() { @Override public void setRemoved() { - PENDING_TICK_SPRINTS.remove(this); + SpacetimeSupercomputerBlockEntity.PENDING_TICK_SPRINTS.remove(this); super.setRemoved(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/TeslaTowerBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/TeslaTowerBlockEntity.java index ead6d37237..ac07e31b9a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/TeslaTowerBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/TeslaTowerBlockEntity.java @@ -66,7 +66,7 @@ public class TeslaTowerBlockEntity extends BlockEntity implements IPowerConsumer, MenuProvider, IDiskCloneable { private static final int STRIKE_COOLDOWN_TICKS = 4 * 20; private final ArrayList> whiteList = new ArrayList<>(); - private int tickCount = STRIKE_COOLDOWN_TICKS; + private int tickCount = TeslaTowerBlockEntity.STRIKE_COOLDOWN_TICKS; private int flashTimer = 0; @Getter private long lastStrikeTime = 0; @@ -102,7 +102,7 @@ public PowerComponentType getComponentType() { @Override public int getInputPower() { if (this.level == null) return 0; - BlockState state = this.level.getBlockState(getBlockPos()); + BlockState state = this.level.getBlockState(this.getBlockPos()); return state.getValue(TeslaTowerBlock.HALF) == Vertical4PartHalf.BOTTOM && state.getValue(TeslaTowerBlock.SWITCH) == Switch.ON ? 128 : 0; } @@ -195,7 +195,7 @@ public void onDataPacket(Connection connection, ValueInput input) { public void tick() { if (this.level == null) return; - BlockState state = this.level.getBlockState(getBlockPos()); + BlockState state = this.level.getBlockState(this.getBlockPos()); if (!state.is(ModBlocks.TESLA_TOWER.get())) return; if (state.getValue(TeslaTowerBlock.HALF) != Vertical4PartHalf.BOTTOM) return; if (this.getGrid() == null) { @@ -206,10 +206,10 @@ public void tick() { this.targetEntityUUID = null; this.targetLightningRod = null; } - this.flushState(this.level, getBlockPos()); - this.flushState(this.level, getBlockPos().above(1)); - this.flushState(this.level, getBlockPos().above(2)); - this.flushState(this.level, getBlockPos().above(3)); + this.flushState(this.level, this.getBlockPos()); + this.flushState(this.level, this.getBlockPos().above(1)); + this.flushState(this.level, this.getBlockPos().above(2)); + this.flushState(this.level, this.getBlockPos().above(3)); if (this.level.isClientSide()) return; if (this.flashTimer > 0) { this.flashTimer--; @@ -221,7 +221,7 @@ public void tick() { } } if (!this.isGridWorking() || state.getValue(TeslaTowerBlock.SWITCH) == Switch.OFF) { - this.tickCount = STRIKE_COOLDOWN_TICKS; + this.tickCount = TeslaTowerBlockEntity.STRIKE_COOLDOWN_TICKS; final boolean hasChanged = this.targetEntity != null || this.targetEntityUUID != null || this.targetLightningRod != null; this.targetEntity = null; this.targetEntityUUID = null; @@ -237,7 +237,7 @@ public void tick() { this.tickCount--; return; } - this.tickCount = STRIKE_COOLDOWN_TICKS; + this.tickCount = TeslaTowerBlockEntity.STRIKE_COOLDOWN_TICKS; this.tickCount--; AABB aabb = new AABB(this.getBlockPos().above(3)).expandTowards(8, 8, 8).expandTowards(-8, -8, -8); if (this.targetEntity != null) { @@ -254,7 +254,7 @@ public void tick() { .stream() .filter(LivingEntity::isAlive) .filter(it -> this.whiteList.stream().noneMatch(it2 -> it2.left().match(it, it2.right()))) - .min((e1, e2) -> new DistanceComparator(getBlockPos().getCenter()).compare(e1.position(), e2.position())); + .min((e1, e2) -> new DistanceComparator(this.getBlockPos().getCenter()).compare(e1.position(), e2.position())); if (target.isPresent()) { LivingEntity targetEntity = target.get(); if (NeoForge.EVENT_BUS.post(new TeslaStrikeEvent.TargetEntity(this.level, this, targetEntity)).isCanceled()) { @@ -282,7 +282,7 @@ public void tick() { } } this.flashTimer = 5; - this.level.playSound(null, getBlockPos(), ModSoundEvents.TESLA_TOWER_STRIKE.get(), SoundSource.BLOCKS, 1.0f, 1.0f); + this.level.playSound(null, this.getBlockPos(), ModSoundEvents.TESLA_TOWER_STRIKE.get(), SoundSource.BLOCKS, 1.0f, 1.0f); } else { ArrayList lightningRods = new ArrayList<>(); BlockPos.betweenClosedStream(aabb) @@ -293,7 +293,7 @@ public void tick() { } }); Optional targetBlock = lightningRods.stream() - .min((b1, b2) -> new DistanceComparator(getBlockPos().getCenter()).compare(b1.getCenter(), b2.getCenter())); + .min((b1, b2) -> new DistanceComparator(this.getBlockPos().getCenter()).compare(b1.getCenter(), b2.getCenter())); if (targetBlock.isEmpty()) return; BlockPos targetLightningRod = targetBlock.get(); if (NeoForge.EVENT_BUS.post(new TeslaStrikeEvent.TargetBlock(this.level, this, targetLightningRod)).isCanceled()) { @@ -309,7 +309,7 @@ public void tick() { rodBlock.onLightningStrike(targetState, this.level, targetLightningRod); } this.flashTimer = 5; - this.level.playSound(null, getBlockPos(), ModSoundEvents.TESLA_TOWER_STRIKE.get(), SoundSource.BLOCKS, 1.0f, 1.0f); + this.level.playSound(null, this.getBlockPos(), ModSoundEvents.TESLA_TOWER_STRIKE.get(), SoundSource.BLOCKS, 1.0f, 1.0f); } } @@ -332,9 +332,9 @@ public void initWhiteList(Player player) { public void addFilter(String id, String arg) { if (this.level == null) return; - BlockState blockState = this.level.getBlockState(getBlockPos()); + BlockState blockState = this.level.getBlockState(this.getBlockPos()); int offsetY = blockState.getValue(TeslaTowerBlock.HALF).getOffsetY(); - if (this.level.getBlockEntity(getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { + if (this.level.getBlockEntity(this.getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { teslaTowerBlockEntity.whiteList.add(Pair.of(TeslaFilter.getFilter(id), arg)); teslaTowerBlockEntity.setChanged(); } @@ -342,9 +342,9 @@ public void addFilter(String id, String arg) { public void removeFilter(String id, String arg) { if (this.level == null) return; - BlockState blockState = this.level.getBlockState(getBlockPos()); + BlockState blockState = this.level.getBlockState(this.getBlockPos()); int offsetY = blockState.getValue(TeslaTowerBlock.HALF).getOffsetY(); - if (this.level.getBlockEntity(getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { + if (this.level.getBlockEntity(this.getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { teslaTowerBlockEntity.whiteList.removeIf(pair -> pair.first().getId().equals(id) && pair.second().equals(arg)); teslaTowerBlockEntity.setChanged(); } @@ -352,9 +352,9 @@ public void removeFilter(String id, String arg) { public void handleSync(List> filters) { if (this.level == null) return; - BlockState blockState = this.level.getBlockState(getBlockPos()); + BlockState blockState = this.level.getBlockState(this.getBlockPos()); int offsetY = blockState.getValue(TeslaTowerBlock.HALF).getOffsetY(); - if (this.level.getBlockEntity(getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { + if (this.level.getBlockEntity(this.getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { teslaTowerBlockEntity.whiteList.clear(); teslaTowerBlockEntity.whiteList.addAll(filters); teslaTowerBlockEntity.setChanged(); @@ -369,9 +369,9 @@ public Component getDisplayName() { @Override public @Nullable AbstractContainerMenu createMenu(int i, Inventory inventory, Player player) { if (this.level == null || player.isSpectator()) return null; - BlockState blockState = this.level.getBlockState(getBlockPos()); + BlockState blockState = this.level.getBlockState(this.getBlockPos()); int offsetY = blockState.getValue(TeslaTowerBlock.HALF).getOffsetY(); - if (this.level.getBlockEntity(getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { + if (this.level.getBlockEntity(this.getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { return new TeslaTowerMenu(ModMenuTypes.TESLA_TOWER.get(), i, inventory, teslaTowerBlockEntity); } return null; @@ -379,9 +379,9 @@ public Component getDisplayName() { public List> getWhiteList() { if (this.level == null) return List.of(); - BlockState blockState = this.level.getBlockState(getBlockPos()); + BlockState blockState = this.level.getBlockState(this.getBlockPos()); int offsetY = blockState.getValue(TeslaTowerBlock.HALF).getOffsetY(); - if (this.level.getBlockEntity(getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { + if (this.level.getBlockEntity(this.getBlockPos().above(-offsetY)) instanceof TeslaTowerBlockEntity teslaTowerBlockEntity) { return teslaTowerBlockEntity.whiteList; } return List.of(); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/TradingStationBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/TradingStationBlockEntity.java index a349a5615f..06d5625d0e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/TradingStationBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/TradingStationBlockEntity.java @@ -156,25 +156,25 @@ public DirectionVertical2PartHalf getPart() { @Override protected void saveAdditional(ValueOutput output) { super.saveAdditional(output); - if (this.owner != null) output.store(OWNER_NBT_ID, UUIDUtil.CODEC, this.owner); - this.handler.serialize(output.child(STORAGE_NBT_ID)); - this.filters.serialize(output.child(FILTERS_NBT_ID)); - output.putBoolean(ALLOW_PLAYER_NBT_ID, this.playerAllowed); - output.putBoolean(ALLOW_VILLAGER_NBT_ID, this.villagerAllowed); - output.putBoolean(ALLOW_INPUT_NBT_ID, this.inputAllowed); - output.putBoolean(ALLOW_OUTPUT_NBT_ID, this.outputAllowed); + if (this.owner != null) output.store(TradingStationBlockEntity.OWNER_NBT_ID, UUIDUtil.CODEC, this.owner); + this.handler.serialize(output.child(TradingStationBlockEntity.STORAGE_NBT_ID)); + this.filters.serialize(output.child(TradingStationBlockEntity.FILTERS_NBT_ID)); + output.putBoolean(TradingStationBlockEntity.ALLOW_PLAYER_NBT_ID, this.playerAllowed); + output.putBoolean(TradingStationBlockEntity.ALLOW_VILLAGER_NBT_ID, this.villagerAllowed); + output.putBoolean(TradingStationBlockEntity.ALLOW_INPUT_NBT_ID, this.inputAllowed); + output.putBoolean(TradingStationBlockEntity.ALLOW_OUTPUT_NBT_ID, this.outputAllowed); } @Override protected void loadAdditional(ValueInput input) { super.loadAdditional(input); - this.owner = input.read(OWNER_NBT_ID, UUIDUtil.CODEC).orElse(null); - input.child(STORAGE_NBT_ID).ifPresent(this.handler::deserialize); - input.child(FILTERS_NBT_ID).ifPresent(this.filters::deserialize); - this.playerAllowed = input.getBooleanOr(ALLOW_PLAYER_NBT_ID, false); - this.villagerAllowed = input.getBooleanOr(ALLOW_VILLAGER_NBT_ID, false); - this.inputAllowed = input.getBooleanOr(ALLOW_INPUT_NBT_ID, false); - this.outputAllowed = input.getBooleanOr(ALLOW_OUTPUT_NBT_ID, false); + this.owner = input.read(TradingStationBlockEntity.OWNER_NBT_ID, UUIDUtil.CODEC).orElse(null); + input.child(TradingStationBlockEntity.STORAGE_NBT_ID).ifPresent(this.handler::deserialize); + input.child(TradingStationBlockEntity.FILTERS_NBT_ID).ifPresent(this.filters::deserialize); + this.playerAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_PLAYER_NBT_ID, false); + this.villagerAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_VILLAGER_NBT_ID, false); + this.inputAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_INPUT_NBT_ID, false); + this.outputAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_OUTPUT_NBT_ID, false); TradingStationBlockEntity.popoutInvalidItems(this.getLevel(), this.getBlockPos(), this.handler); } @@ -211,18 +211,18 @@ public void writeClientSideData(AbstractContainerMenu menu, RegistryFriendlyByte @Override public void storeDiskData(ValueOutput output) { - if (this.owner != null) output.store(OWNER_NBT_ID, UUIDUtil.CODEC, this.owner); - this.filters.serialize(output.child(FILTERS_NBT_ID)); - this.handler.serializeFiltering(output.child(STORAGE_FILTERING_NBT_ID)); - output.putBoolean(ALLOW_PLAYER_NBT_ID, this.playerAllowed); - output.putBoolean(ALLOW_VILLAGER_NBT_ID, this.villagerAllowed); - output.putBoolean(ALLOW_INPUT_NBT_ID, this.inputAllowed); - output.putBoolean(ALLOW_OUTPUT_NBT_ID, this.outputAllowed); + if (this.owner != null) output.store(TradingStationBlockEntity.OWNER_NBT_ID, UUIDUtil.CODEC, this.owner); + this.filters.serialize(output.child(TradingStationBlockEntity.FILTERS_NBT_ID)); + this.handler.serializeFiltering(output.child(TradingStationBlockEntity.STORAGE_FILTERING_NBT_ID)); + output.putBoolean(TradingStationBlockEntity.ALLOW_PLAYER_NBT_ID, this.playerAllowed); + output.putBoolean(TradingStationBlockEntity.ALLOW_VILLAGER_NBT_ID, this.villagerAllowed); + output.putBoolean(TradingStationBlockEntity.ALLOW_INPUT_NBT_ID, this.inputAllowed); + output.putBoolean(TradingStationBlockEntity.ALLOW_OUTPUT_NBT_ID, this.outputAllowed); } @Override public void applyDiskData(ValueInput input) { - Optional ownerValue = input.read(OWNER_NBT_ID, UUIDUtil.CODEC); + Optional ownerValue = input.read(TradingStationBlockEntity.OWNER_NBT_ID, UUIDUtil.CODEC); if (ownerValue.isEmpty()) return; UUID owner = ownerValue.get(); if (this.owner != null) { @@ -231,12 +231,12 @@ public void applyDiskData(ValueInput input) { this.owner = owner; } - input.child(FILTERS_NBT_ID).ifPresent(this.filters::deserialize); - input.child(STORAGE_FILTERING_NBT_ID).ifPresent(this.handler::deserializeFiltering); - this.playerAllowed = input.getBooleanOr(ALLOW_PLAYER_NBT_ID, false); - this.villagerAllowed = input.getBooleanOr(ALLOW_VILLAGER_NBT_ID, false); - this.inputAllowed = input.getBooleanOr(ALLOW_INPUT_NBT_ID, false); - this.outputAllowed = input.getBooleanOr(ALLOW_OUTPUT_NBT_ID, false); + input.child(TradingStationBlockEntity.FILTERS_NBT_ID).ifPresent(this.filters::deserialize); + input.child(TradingStationBlockEntity.STORAGE_FILTERING_NBT_ID).ifPresent(this.handler::deserializeFiltering); + this.playerAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_PLAYER_NBT_ID, false); + this.villagerAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_VILLAGER_NBT_ID, false); + this.inputAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_INPUT_NBT_ID, false); + this.outputAllowed = input.getBooleanOr(TradingStationBlockEntity.ALLOW_OUTPUT_NBT_ID, false); TradingStationBlockEntity.popoutInvalidItems(this.getLevel(), this.getBlockPos(), this.handler); TradingStationBlockEntity.updateAndSend(this); } @@ -420,15 +420,16 @@ private boolean matchesFilters(MerchantOffer offer) { if (req.isEmpty()) return false; if (!FilterContent.filter(req, result, !req.getComponentsPatch().isEmpty())) return false; if (req.getCount() > result.getCount()) return false; - return assignProvideFilters(this.filters.getItem(0), this.filters.getItem(1), offer.getCostA(), offer.getCostB()); + return TradingStationBlockEntity.assignProvideFilters( + this.filters.getItem(0), this.filters.getItem(1), offer.getCostA(), offer.getCostB()); } private static boolean assignProvideFilters(ItemStack p0, ItemStack p1, ItemStack costA, ItemStack costB) { if (costB.isEmpty()) { - return provideMatches(p0, costA) || provideMatches(p1, costA); + return TradingStationBlockEntity.provideMatches(p0, costA) || TradingStationBlockEntity.provideMatches(p1, costA); } - if (provideMatches(p0, costA) && provideMatches(p1, costB)) return true; - return provideMatches(p0, costB) && provideMatches(p1, costA); + if (TradingStationBlockEntity.provideMatches(p0, costA) && TradingStationBlockEntity.provideMatches(p1, costB)) return true; + return TradingStationBlockEntity.provideMatches(p0, costB) && TradingStationBlockEntity.provideMatches(p1, costA); } private static boolean provideMatches(ItemStack filter, ItemStack cost) { @@ -450,8 +451,8 @@ private boolean simulateVillagerTrade(MerchantOffer offer, boolean commit) { for (int i = 0; i < snapshot.length; i++) { snapshot[i] = this.getStack(i).copy(); } - if (!removeMatching(offer.getCostA(), snapshot)) return false; - if (!offer.getCostB().isEmpty() && !removeMatching(offer.getCostB(), snapshot)) return false; + if (!TradingStationBlockEntity.removeMatching(offer.getCostA(), snapshot)) return false; + if (!offer.getCostB().isEmpty() && !TradingStationBlockEntity.removeMatching(offer.getCostB(), snapshot)) return false; ItemStack result = offer.getResult(); if (!this.insertMatching(result, snapshot)) return false; if (!commit) return true; @@ -463,6 +464,7 @@ private boolean simulateVillagerTrade(MerchantOffer offer, boolean commit) { return true; } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") private static boolean removeMatching(ItemStack cost, ItemStack[] snapshot) { int remaining = cost.getCount(); for (int i = 0; i < snapshot.length && remaining > 0; i++) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/VoidEnergyCollectorBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/VoidEnergyCollectorBlockEntity.java index ad86dce2cd..7c96f2ddf5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/VoidEnergyCollectorBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/VoidEnergyCollectorBlockEntity.java @@ -111,10 +111,10 @@ private static int getPowerFromBlockCount(int count) { public void gridTick() { if (this.level == null || this.level.isClientSide()) return; if (this.cooldownCount-- > 1) return; - this.cooldownCount = COOLDOWN; + this.cooldownCount = VoidEnergyCollectorBlockEntity.COOLDOWN; final int oldPower = this.power; this.blockCount = this.countBlocksInRange(); - this.power = getPowerFromBlockCount(this.blockCount); + this.power = VoidEnergyCollectorBlockEntity.getPowerFromBlockCount(this.blockCount); if (this.power > 0 && this.getBlockState().getBlock() instanceof VoidEnergyCollectorBlock voidEnergyCollector) { voidEnergyCollector.activate(this.level, this.getBlockPos(), this.getBlockState()); if (this.decayCooldownCount-- <= 1) { @@ -157,17 +157,17 @@ public static boolean isAnotherCollectorNearby(Level level, BlockPos pos) { /// /// @return count(normal) - count(negative) IF active ELSE 125 private int countBlocksInRange() { - if (level == null || level.isClientSide()) return 125; + if (this.level == null || this.level.isClientSide()) return 125; int count = 0; - if (isAnotherCollectorNearby(this.level, this.getBlockPos())) return 125; + if (VoidEnergyCollectorBlockEntity.isAnotherCollectorNearby(this.level, this.getBlockPos())) return 125; BlockPos.MutableBlockPos mpos = new BlockPos.MutableBlockPos(); for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { for (int k = -2; k <= 2; k++) { // the 5x5x5 detection that counts how many blocks are there mpos.set(this.getBlockPos()).move(i, j, k); - if (level.isOutsideBuildHeight(mpos)) continue; - BlockState blockState = level.getBlockState(mpos); + if (this.level.isOutsideBuildHeight(mpos)) continue; + BlockState blockState = this.level.getBlockState(mpos); if (blockState.getBlock() instanceof NegativeMatterBlock) count -= 1; else if ( !blockState.isAir() @@ -183,8 +183,8 @@ else if ( } private void makeBlocksDecay() { - if (level == null || level.isClientSide()) return; - RandomSource random = level.getRandom(); + if (this.level == null || this.level.isClientSide()) return; + RandomSource random = this.level.getRandom(); ArrayList list = new ArrayList<>(); for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { @@ -194,8 +194,8 @@ private void makeBlocksDecay() { thisPos.getX() + i, thisPos.getY() + j, thisPos.getZ() + k); - if (isOutOfBuildLimits(level, bp)) continue; - BlockState b = level.getBlockState(bp); + if (VoidEnergyCollectorBlockEntity.isOutOfBuildLimits(this.level, bp)) continue; + BlockState b = this.level.getBlockState(bp); if (b.isAir()) { list.add(bp); } @@ -205,7 +205,7 @@ private void makeBlocksDecay() { if (list.isEmpty()) return; int i = random.nextInt(list.size()); BlockPos bp = list.get(i); - level.setBlockAndUpdate(bp, VoidMatterBlock.voidDecay(level, random)); + this.level.setBlockAndUpdate(bp, VoidMatterBlock.voidDecay(this.level, random)); } @Override @@ -215,10 +215,10 @@ public int getRange() { @Override public AABB shape() { - return AABB.ofSize(getBlockPos().getCenter(), 5, 5, 5); + return AABB.ofSize(this.getBlockPos().getCenter(), 5, 5, 5); } public void clientTick() { - this.rotation += (float) (Math.log(getServerPower() + 1) * 2.5); + this.rotation += (float) (Math.log(this.getServerPower() + 1) * 2.5); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BaseBatchCraftingBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BaseBatchCraftingBlockEntity.java index aa75fedfb3..efa11d394d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BaseBatchCraftingBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BaseBatchCraftingBlockEntity.java @@ -57,7 +57,7 @@ public abstract class BaseBatchCraftingBlockEntity extends BaseMachineBlockEntit protected final PollableFilteredItemStackHandler handler = this.constructHandler(); @Getter - protected @Nullable ItemStack displayingStack; + protected ItemStack displayingStack = ItemStack.EMPTY; protected boolean poweredBefore = false; protected int cooldown = 0; @@ -160,7 +160,10 @@ private void ejectItemEntity(ItemStack stack) { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { - ItemHandlerUtil.dropAllToPos(this.getItemHandler(), this.level, pos.getCenter()); + Level level = this.level; + if (level != null) { + ItemHandlerUtil.dropAllToPos(this.getItemHandler(), level, pos.getCenter()); + } } @Nullable @@ -180,7 +183,7 @@ protected void saveAdditional(ValueOutput output) { this.handler.serialize(output.child("Inventory")); output.putBoolean("PoweredBefore", this.poweredBefore); output.putInt("Cooldown", this.cooldown); - boolean displaying = this.displayingStack != null && !this.displayingStack.isEmpty(); + boolean displaying = !this.displayingStack.isEmpty(); output.putBoolean("HasDisplayItemStack", displaying); if (displaying) output.store("ResultItemStack", ItemStack.OPTIONAL_CODEC, this.displayingStack); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCrafterBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCrafterBlockEntity.java index ed86ab5fe8..121cb42b1c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCrafterBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCrafterBlockEntity.java @@ -53,7 +53,7 @@ public class BatchCrafterBlockEntity extends BaseBatchCraftingBlockEntity { private int selecting; public BatchCrafterBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState, COUNTER.incrementAndGet()); + super(type, pos, blockState, BatchCrafterBlockEntity.COUNTER.incrementAndGet()); } @Override @@ -158,7 +158,9 @@ public boolean craft(ServerLevel level) { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); - Containers.dropContents(this.level, pos, this.getFilteredItemStackHandler().getStacks()); + if (this.level != null) { + Containers.dropContents(this.level, pos, this.getFilteredItemStackHandler().getStacks()); + } } @Nullable @@ -215,8 +217,7 @@ public static class BatchCrafterCache implements Predicate { /// 合成器缓存 /// /// @param container 容器 - /// @param recipe 配方 - /// @param remaining 返还物品 + /// @param recipes 配方 public BatchCrafterCache( Container container, List> recipes diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCutterBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCutterBlockEntity.java index fab9fc37e5..809ba5e34b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCutterBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/batch/BatchCutterBlockEntity.java @@ -48,7 +48,7 @@ public class BatchCutterBlockEntity extends BaseBatchCraftingBlockEntity { private int selecting = 0; public BatchCutterBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { - super(type, pos, blockState, COUNTER.incrementAndGet()); + super(type, pos, blockState, BatchCutterBlockEntity.COUNTER.incrementAndGet()); } @Override @@ -101,7 +101,9 @@ private void onContentsChanged() { @Override public void preRemoveSideEffects(BlockPos pos, BlockState state) { super.preRemoveSideEffects(pos, state); - Containers.dropContents(this.level, pos, this.getFilteredItemStackHandler().getStacks()); + if (this.level != null) { + Containers.dropContents(this.level, pos, this.getFilteredItemStackHandler().getStacks()); + } } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyClass.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyClass.java index 60008a9972..f9221cac95 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyClass.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyClass.java @@ -71,8 +71,8 @@ public enum CelestialBodyClass { private static final Map BY_RGB = new HashMap<>(); static { - for (CelestialBodyClass c : values()) { - BY_RGB.put(c.rgb, c); + for (CelestialBodyClass c : CelestialBodyClass.values()) { + CelestialBodyClass.BY_RGB.put(c.rgb, c); } } @@ -94,12 +94,12 @@ public boolean step2UsesSp() { /** 是否需要第三步年龄-半径图匹配。 */ public boolean needsStep3() { - return this.stellar || this == BROWN_DWARF; + return this.stellar || this == CelestialBodyClass.BROWN_DWARF; } /** 是否为只能写入奇点晶体的极端致密天体(黑洞或中子星)。 */ public boolean isExtreme() { - return this == BLACK_HOLE || this == NEUTRON_STAR; + return this == CelestialBodyClass.BLACK_HOLE || this == CelestialBodyClass.NEUTRON_STAR; } /** 是否为行星类天体,包含褐矮星但不包含大型卫星。 */ @@ -109,17 +109,17 @@ public boolean isPlanetary() { /** 是否为第二步需要特殊处理的岩石行星类别。 */ public boolean isRockyPlanet() { - return this == ROCKY_NO_LIQUID || this == ROCKY_LOW_LIQUID - || this == ROCKY_MED_LIQUID || this == ROCKY_HIGH_LIQUID; + return this == CelestialBodyClass.ROCKY_NO_LIQUID || this == CelestialBodyClass.ROCKY_LOW_LIQUID + || this == CelestialBodyClass.ROCKY_MED_LIQUID || this == CelestialBodyClass.ROCKY_HIGH_LIQUID; } /** 获取该类别第二步接受的颜色;全部岩石行星统一使用 ROCKY_LOW_LIQUID 的 RGB。 */ public int step2MatchRgb() { - return this.isRockyPlanet() ? ROCKY_LOW_LIQUID.rgb : this.rgb; + return this.isRockyPlanet() ? CelestialBodyClass.ROCKY_LOW_LIQUID.rgb : this.rgb; } @Nullable public static CelestialBodyClass fromRgb(int rgb) { - return BY_RGB.get(rgb); + return CelestialBodyClass.BY_RGB.get(rgb); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyData.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyData.java index 0fec4fb740..8278fbe816 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyData.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyData.java @@ -78,22 +78,26 @@ default float bodyScale() { /** 计算指定天体的完整束星环系统缩放,不包含红石插值。 */ static float ringSystemScale(@Nullable CelestialBodyData data, boolean isAmplify) { - if (data == null) return BASE_RING_SCALE; + if (data == null) return CelestialBodyData.BASE_RING_SCALE; float bodyS = data.bodyScale(); - float proportional = bodyS * BODY_SCALE_FACTOR * RING_TO_BODY_RATIO; + float proportional = bodyS * CelestialBodyData.BODY_SCALE_FACTOR * CelestialBodyData.RING_TO_BODY_RATIO; if (data instanceof StarData) { - float inBoneBoost = Math.max(0.0f, INNER_BONE_BOOST_MAX - bodyS * INNER_BONE_BOOST_RATE); + float inBoneBoost = Math.max(0.0f, CelestialBodyData.INNER_BONE_BOOST_MAX - bodyS * CelestialBodyData.INNER_BONE_BOOST_RATE); return proportional + inBoneBoost; } else { - float inBoneBoost = Math.max(0.0f, INNER_BONE_BOOST_MAX * 1.5f - bodyS * INNER_BONE_BOOST_RATE); - return proportional * RING_SMALL_INNER_RADIUS_FACTOR + inBoneBoost; + float inBoneBoost = Math.max( + 0.0f, + CelestialBodyData.INNER_BONE_BOOST_MAX * 1.5f + - bodyS * CelestialBodyData.INNER_BONE_BOOST_RATE + ); + return proportional * CelestialBodyData.RING_SMALL_INNER_RADIUS_FACTOR + inBoneBoost; } } /** 计算指定天体的动态中心高度,不包含红石插值。 */ static float dynamicCenterY(@Nullable CelestialBodyData data, boolean isAmplify) { if (data == null) return isAmplify ? 6.5f : 4.5f; - float ringScale = ringSystemScale(data, isAmplify); + float ringScale = CelestialBodyData.ringSystemScale(data, isAmplify); float baseHeight = isAmplify ? 2.5f : 1.5f; float height = baseHeight + ringScale * 0.74f; if (!(data instanceof StarData)) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyMatcher.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyMatcher.java index 296a3fa533..cf74da2028 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyMatcher.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyMatcher.java @@ -16,7 +16,7 @@ * 每张 64×64 星图把砧子数量映射为天体类别像素颜色,并通过类加载器在服务端和客户端读取。 * *

26.1 的 {@code NativeImage} 仅客户端可用,因此改用服务端同样可用的 - * {@link javax.imageio.ImageIO} 和 {@link BufferedImage}。后者返回 ARGB(0xAARRGGBB), + * {@link ImageIO} 和 {@link BufferedImage}。后者返回 ARGB(0xAARRGGBB), * 与旧版 ABGR 像素顺序不同,读取时需要按新顺序提取 RGB。

*/ public final class CelestialBodyMatcher { @@ -24,10 +24,10 @@ public final class CelestialBodyMatcher { private static final String DIR = "assets/anvilcraft/textures/misc"; // 星图资源路径 - private static final String MASS_RADIUS = DIR + "/mass_radius_diagram_pixel.png"; - private static final String AGE_TEMP = DIR + "/age_temp_diagram_pixel.png"; - private static final String AGE_TEMP_SP = DIR + "/age_temp_diagram_pixel_sp.png"; - private static final String AGE_RADIUS = DIR + "/age_radius_diagram_pixel.png"; + private static final String MASS_RADIUS = CelestialBodyMatcher.DIR + "/mass_radius_diagram_pixel.png"; + private static final String AGE_TEMP = CelestialBodyMatcher.DIR + "/age_temp_diagram_pixel.png"; + private static final String AGE_TEMP_SP = CelestialBodyMatcher.DIR + "/age_temp_diagram_pixel_sp.png"; + private static final String AGE_RADIUS = CelestialBodyMatcher.DIR + "/age_radius_diagram_pixel.png"; private static final String STAR_COLOR_TEMP = "assets/anvilcraft/textures/block/celestial_body/star_color_temperature.png"; private static @Nullable BufferedImage massRadiusImage; @@ -56,33 +56,46 @@ private CelestialBodyMatcher() { public static CelestialBodyData match( int time, int space, int mass, int energy, boolean isAmplified, RandomSource random ) { - ensureLoaded(); + CelestialBodyMatcher.ensureLoaded(); // 第一步:质量-半径图,质量为 X,空间为反向 Y。 - CelestialBodyClass bodyClass = lookupClass(massRadiusImage, toX(mass), toY(space)); + CelestialBodyClass bodyClass = CelestialBodyMatcher.lookupClass( + CelestialBodyMatcher.massRadiusImage, + CelestialBodyMatcher.toX(mass), + CelestialBodyMatcher.toY(space) + ); if (bodyClass == null) return null; // 恒星类天体必须使用增幅器。 if (bodyClass.isStellar() && !isAmplified) return null; // 第二步:温度-年龄图,时间为 X,能量为反向 Y。 - if (!step2(toX(time), toY(energy), bodyClass)) return null; + if (!CelestialBodyMatcher.step2(CelestialBodyMatcher.toX(time), CelestialBodyMatcher.toY(energy), bodyClass)) return null; // 第三步:年龄-半径图,供恒星和褐矮星继续细分。 - if (bodyClass.needsStep3() && !step3(toX(time), toY(space), bodyClass)) return null; + if ( + bodyClass.needsStep3() + && !CelestialBodyMatcher.step3( + CelestialBodyMatcher.toX(time), + CelestialBodyMatcher.toY(space), + bodyClass + ) + ) { + return null; + } // 根据匹配结果生成完整天体数据。 - return generateBodyData(bodyClass, time, space, mass, energy, random); + return CelestialBodyMatcher.generateBodyData(bodyClass, time, space, mass, energy, random); } /** 将 1-64 的砧子数量映射到星图零基 X 坐标。 */ public static int toX(int count) { - return Math.clamp(count - 1, 0, DIAG_SIZE - 1); + return Math.clamp(count - 1, 0, CelestialBodyMatcher.DIAG_SIZE - 1); } /** 将 1-64 的砧子数量映射到反向的星图零基 Y 坐标。 */ public static int toY(int count) { - return Math.clamp(DIAG_SIZE - count, 0, DIAG_SIZE - 1); + return Math.clamp(CelestialBodyMatcher.DIAG_SIZE - count, 0, CelestialBodyMatcher.DIAG_SIZE - 1); } /** 将四种砧子数量编码为位集使用的单个整数索引。 */ @@ -93,39 +106,39 @@ private static int encode(int time, int space, int mass, int energy) { // === 全部合法组合预计算 === private static void ensurePrecomputed() { - if (precomputed) return; - ensureLoaded(); - precomputed = true; + if (CelestialBodyMatcher.precomputed) return; + CelestialBodyMatcher.ensureLoaded(); + CelestialBodyMatcher.precomputed = true; - if (massRadiusImage == null) return; + if (CelestialBodyMatcher.massRadiusImage == null) return; - validAmplified = new BitSet(1 << 24); - validNormal = new BitSet(1 << 24); + CelestialBodyMatcher.validAmplified = new BitSet(1 << 24); + CelestialBodyMatcher.validNormal = new BitSet(1 << 24); for (int mass = 1; mass <= 64; mass++) { - int mx = toX(mass); + int mx = CelestialBodyMatcher.toX(mass); for (int space = 1; space <= 64; space++) { - int sy = toY(space); - CelestialBodyClass bodyClass = lookupClass(massRadiusImage, mx, sy); + int sy = CelestialBodyMatcher.toY(space); + CelestialBodyClass bodyClass = CelestialBodyMatcher.lookupClass(CelestialBodyMatcher.massRadiusImage, mx, sy); if (bodyClass == null) continue; int massSpaceBase = ((space - 1) << 12) | ((mass - 1) << 6); for (int time = 1; time <= 64; time++) { - int tx = toX(time); + int tx = CelestialBodyMatcher.toX(time); - boolean step3Ok = !bodyClass.needsStep3() || step3(tx, sy, bodyClass); + boolean step3Ok = !bodyClass.needsStep3() || CelestialBodyMatcher.step3(tx, sy, bodyClass); if (!step3Ok) continue; int timeBase = ((time - 1) << 18) | massSpaceBase; for (int energy = 1; energy <= 64; energy++) { - int ey = toY(energy); - if (step2(tx, ey, bodyClass)) { + int ey = CelestialBodyMatcher.toY(energy); + if (CelestialBodyMatcher.step2(tx, ey, bodyClass)) { int index = timeBase | (energy - 1); - validAmplified.set(index); + CelestialBodyMatcher.validAmplified.set(index); if (!bodyClass.isStellar()) { - validNormal.set(index); + CelestialBodyMatcher.validNormal.set(index); } } } @@ -136,7 +149,7 @@ private static void ensurePrecomputed() { /** 提前触发预计算,避免界面首次查询有效范围时卡顿。 */ public static void warmup() { - ensurePrecomputed(); + CelestialBodyMatcher.ensurePrecomputed(); } // === 界面提示范围查询 === @@ -145,8 +158,8 @@ public static void warmup() { * 根据部分已知数量查询某种砧子的合法范围 [min, max],数量 0 表示尚未放置。 */ public static int @Nullable [] getValidRange(int time, int space, int mass, int energy, boolean isAmplified, int targetIndex) { - ensurePrecomputed(); - BitSet bitset = isAmplified ? validAmplified : validNormal; + CelestialBodyMatcher.ensurePrecomputed(); + BitSet bitset = isAmplified ? CelestialBodyMatcher.validAmplified : CelestialBodyMatcher.validNormal; if (bitset == null) return null; int[] counts = {time, space, mass, energy}; @@ -160,7 +173,7 @@ public static void warmup() { } if (allUnknown) return new int[] {1, 64}; - java.util.List unknownIndices = new ArrayList<>(); + List unknownIndices = new ArrayList<>(); for (int i = 0; i < 4; i++) { if (i != targetIndex && counts[i] <= 0) { unknownIndices.add(i); @@ -173,7 +186,7 @@ public static void warmup() { for (int candidate = 1; candidate <= 64; candidate++) { test[targetIndex] = candidate; - if (anyValid(bitset, test, unknownIndices)) { + if (CelestialBodyMatcher.anyValid(bitset, test, unknownIndices)) { if (candidate < min) min = candidate; max = candidate; } @@ -185,19 +198,19 @@ public static void warmup() { private static boolean anyValid(BitSet bitset, int[] counts, List unknownIndices) { if (unknownIndices.isEmpty()) { - return bitset.get(encode(counts[0], counts[1], counts[2], counts[3])); + return bitset.get(CelestialBodyMatcher.encode(counts[0], counts[1], counts[2], counts[3])); } - return anyValidRecursive(bitset, counts, unknownIndices, 0); + return CelestialBodyMatcher.anyValidRecursive(bitset, counts, unknownIndices, 0); } private static boolean anyValidRecursive(BitSet bitset, int[] counts, List unknownIndices, int depth) { if (depth == unknownIndices.size()) { - return bitset.get(encode(counts[0], counts[1], counts[2], counts[3])); + return bitset.get(CelestialBodyMatcher.encode(counts[0], counts[1], counts[2], counts[3])); } int idx = unknownIndices.get(depth); for (int val = 1; val <= 64; val++) { counts[idx] = val; - if (anyValidRecursive(bitset, counts, unknownIndices, depth + 1)) { + if (CelestialBodyMatcher.anyValidRecursive(bitset, counts, unknownIndices, depth + 1)) { return true; } } @@ -207,15 +220,15 @@ private static boolean anyValidRecursive(BitSet bitset, int[] counts, List generateLargeMoon(space, energy, random); - case ROCKY_NO_LIQUID, ROCKY_LOW_LIQUID, ROCKY_MED_LIQUID, ROCKY_HIGH_LIQUID -> generateRockyPlanet( + case LARGE_MOON -> CelestialBodyMatcher.generateLargeMoon(space, energy, random); + case ROCKY_NO_LIQUID, ROCKY_LOW_LIQUID, ROCKY_MED_LIQUID, ROCKY_HIGH_LIQUID -> CelestialBodyMatcher.generateRockyPlanet( bodyClass, energy, space, random); - case ICE_GIANT -> generateGiantPlanet(bodyClass, PressureType.ICE, space, random); - case GAS_GIANT -> generateGiantPlanet(bodyClass, PressureType.GAS, space, random); - case BROWN_DWARF -> generateBrownDwarf(space, energy, random); - default -> generateStar(bodyClass, energy, space, random); + case ICE_GIANT -> CelestialBodyMatcher.generateGiantPlanet(bodyClass, PressureType.ICE, space, random); + case GAS_GIANT -> CelestialBodyMatcher.generateGiantPlanet(bodyClass, PressureType.GAS, space, random); + case BROWN_DWARF -> CelestialBodyMatcher.generateBrownDwarf(space, energy, random); + default -> CelestialBodyMatcher.generateStar(bodyClass, energy, space, random); }; } // === 大型卫星 === private static CelestialBodyData generateLargeMoon(int space, int energy, RandomSource random) { - int size = sizeForSpace(space); + int size = CelestialBodyMatcher.sizeForSpace(space); int mag = random.nextFloat() < 0.5f ? 0 : 1; - Temperature temperature = energyToTemperature(energy); + Temperature temperature = CelestialBodyMatcher.energyToTemperature(energy); return new RockyPlanetData( CelestialBodyClass.LARGE_MOON, false, LiquidCoverage.NONE, temperature, RingType.NONE, size, random.nextInt(16), 0, - randomAxialTilt(random), randomRotationSpeed(random), mag + CelestialBodyMatcher.randomAxialTilt(random), CelestialBodyMatcher.randomRotationSpeed(random), mag ); } @@ -318,35 +331,35 @@ private static CelestialBodyData generateRockyPlanet( default -> LiquidCoverage.NONE; }; boolean hasAtmosphere = random.nextFloat() < 0.2f; - Temperature temperature = energyToTemperature(energy); - RingType ring = weightedRing(random, 0.97f, 0.02f, 0.01f); - int size = sizeForSpace(space); + Temperature temperature = CelestialBodyMatcher.energyToTemperature(energy); + RingType ring = CelestialBodyMatcher.weightedRing(random, 0.97f, 0.02f, 0.01f); + int size = CelestialBodyMatcher.sizeForSpace(space); int baseRow = random.nextInt(8); int overlayRow = liquid == LiquidCoverage.NONE ? 0 : 8 + random.nextInt(8); - int mag = weightedMagnetic(random, 0.10f, 0.80f, 0.10f); + int mag = CelestialBodyMatcher.weightedMagnetic(random, 0.10f, 0.80f, 0.10f); return new RockyPlanetData( bodyClass, hasAtmosphere, liquid, temperature, ring, size, baseRow, overlayRow, - randomAxialTilt(random), randomRotationSpeed(random), mag + CelestialBodyMatcher.randomAxialTilt(random), CelestialBodyMatcher.randomRotationSpeed(random), mag ); } // === 褐矮星 === private static CelestialBodyData generateBrownDwarf(int space, int energy, RandomSource random) { - int size = sizeForSpace(space); + int size = CelestialBodyMatcher.sizeForSpace(space); int baseRow = random.nextInt(16); int overlayRow; do { overlayRow = random.nextInt(16); } while (overlayRow == baseRow); - int mag = weightedMagnetic(random, 0.01f, 0.49f, 0.50f); + int mag = CelestialBodyMatcher.weightedMagnetic(random, 0.01f, 0.49f, 0.50f); return new GiantPlanetData( CelestialBodyClass.BROWN_DWARF, PressureType.GAS, WindSpeed.HIGH, RingType.NONE, size, baseRow, overlayRow, - randomAxialTilt(random), randomRotationSpeed(random), mag, true + CelestialBodyMatcher.randomAxialTilt(random), CelestialBodyMatcher.randomRotationSpeed(random), mag, true ); } @@ -354,20 +367,20 @@ private static CelestialBodyData generateBrownDwarf(int space, int energy, Rando private static CelestialBodyData generateGiantPlanet( CelestialBodyClass bodyClass, PressureType pressure, int space, RandomSource random ) { - RingType ring = weightedRing(random, 0.70f, 0.20f, 0.10f); - int size = sizeForSpace(space); + RingType ring = CelestialBodyMatcher.weightedRing(random, 0.70f, 0.20f, 0.10f); + int size = CelestialBodyMatcher.sizeForSpace(space); int baseRow = random.nextInt(16); int overlayRow; do { overlayRow = random.nextInt(16); } while (overlayRow == baseRow); WindSpeed wind = random.nextBoolean() ? WindSpeed.HIGH : WindSpeed.VERY_HIGH; - int mag = weightedMagnetic(random, 0.01f, 0.49f, 0.50f); + int mag = CelestialBodyMatcher.weightedMagnetic(random, 0.01f, 0.49f, 0.50f); return new GiantPlanetData( bodyClass, pressure, wind, ring, size, baseRow, overlayRow, - randomAxialTilt(random), randomRotationSpeed(random), mag, false + CelestialBodyMatcher.randomAxialTilt(random), CelestialBodyMatcher.randomRotationSpeed(random), mag, false ); } @@ -375,10 +388,10 @@ private static CelestialBodyData generateGiantPlanet( private static CelestialBodyData generateStar( CelestialBodyClass bodyClass, int energy, int space, RandomSource random ) { - int size = sizeForSpace(space); - int[] rgb = getStarColorFromTempDiagram(energy); + int size = CelestialBodyMatcher.sizeForSpace(space); + int[] rgb = CelestialBodyMatcher.getStarColorFromTempDiagram(energy); int mag = random.nextFloat() < 0.10f ? 5 : 4; - int rotSpeed = bodyClass == CelestialBodyClass.BLACK_HOLE ? 0 : randomRotationSpeed(random); + int rotSpeed = bodyClass == CelestialBodyClass.BLACK_HOLE ? 0 : CelestialBodyMatcher.randomRotationSpeed(random); float axialTilt = 0f; return new StarData( bodyClass, @@ -432,11 +445,11 @@ private static int randomRotationSpeed(RandomSource random) { } private static int[] getStarColorFromTempDiagram(int energy) { - BufferedImage img = loadStarColorTemp(); + BufferedImage img = CelestialBodyMatcher.loadStarColorTemp(); if (img == null) { return new int[]{255, 255, 255}; } - int row = toY(energy); + int row = CelestialBodyMatcher.toY(energy); int argb = img.getRGB(0, row); // BufferedImage 的像素格式为 AARRGGBB。 int r = (argb >> 16) & 0xFF; @@ -448,33 +461,49 @@ private static int[] getStarColorFromTempDiagram(int energy) { // === 供界面星图指南使用的公开像素查询 === public static int getMassRadiusRgb(int mass, int space) { - ensureLoaded(); - return getRgb(massRadiusImage, toX(mass), toY(space)); + CelestialBodyMatcher.ensureLoaded(); + return CelestialBodyMatcher.getRgb( + CelestialBodyMatcher.massRadiusImage, + CelestialBodyMatcher.toX(mass), + CelestialBodyMatcher.toY(space) + ); } public static int getAgeTempRgb(int time, int energy) { - ensureLoaded(); - return getRgb(ageTempImage, toX(time), toY(energy)); + CelestialBodyMatcher.ensureLoaded(); + return CelestialBodyMatcher.getRgb( + CelestialBodyMatcher.ageTempImage, + CelestialBodyMatcher.toX(time), + CelestialBodyMatcher.toY(energy) + ); } public static int getAgeTempSpRgb(int time, int energy) { - ensureLoaded(); - return getRgb(ageTempSpImage, toX(time), toY(energy)); + CelestialBodyMatcher.ensureLoaded(); + return CelestialBodyMatcher.getRgb( + CelestialBodyMatcher.ageTempSpImage, + CelestialBodyMatcher.toX(time), + CelestialBodyMatcher.toY(energy) + ); } public static int getAgeRadiusRgb(int time, int space) { - ensureLoaded(); - return getRgb(ageRadiusImage, toX(time), toY(space)); + CelestialBodyMatcher.ensureLoaded(); + return CelestialBodyMatcher.getRgb( + CelestialBodyMatcher.ageRadiusImage, + CelestialBodyMatcher.toX(time), + CelestialBodyMatcher.toY(space) + ); } // === 恒星演化加速器使用的像素扫描 === public static int countPixelsRightInAgeTemp(int x, int y) { - ensureLoaded(); - if (ageTempImage == null) return 0; + CelestialBodyMatcher.ensureLoaded(); + if (CelestialBodyMatcher.ageTempImage == null) return 0; int count = 0; - for (int scanX = x + 1; scanX < DIAG_SIZE; scanX++) { - int rgb = getRgb(ageTempImage, scanX, y); + for (int scanX = x + 1; scanX < CelestialBodyMatcher.DIAG_SIZE; scanX++) { + int rgb = CelestialBodyMatcher.getRgb(CelestialBodyMatcher.ageTempImage, scanX, y); if (rgb == 0x000000) break; count++; } @@ -482,11 +511,11 @@ public static int countPixelsRightInAgeTemp(int x, int y) { } public static int countPixelsDownInAgeTempSp(int x, int y) { - ensureLoaded(); - if (ageTempSpImage == null) return 0; + CelestialBodyMatcher.ensureLoaded(); + if (CelestialBodyMatcher.ageTempSpImage == null) return 0; int count = 0; - for (int scanY = y + 1; scanY < DIAG_SIZE; scanY++) { - int rgb = getRgb(ageTempSpImage, x, scanY); + for (int scanY = y + 1; scanY < CelestialBodyMatcher.DIAG_SIZE; scanY++) { + int rgb = CelestialBodyMatcher.getRgb(CelestialBodyMatcher.ageTempSpImage, x, scanY); if (rgb == 0x000000) break; count++; } @@ -494,16 +523,16 @@ public static int countPixelsDownInAgeTempSp(int x, int y) { } public static int countTotalColoredPixelsInAgeTempSpColumn(int x, int startY) { - ensureLoaded(); - if (ageTempSpImage == null) return 0; + CelestialBodyMatcher.ensureLoaded(); + if (CelestialBodyMatcher.ageTempSpImage == null) return 0; int segmentTop = startY; for (int scanY = startY - 1; scanY >= 0; scanY--) { - if (getRgb(ageTempSpImage, x, scanY) == 0x000000) break; + if (CelestialBodyMatcher.getRgb(CelestialBodyMatcher.ageTempSpImage, x, scanY) == 0x000000) break; segmentTop = scanY; } int count = 0; - for (int scanY = segmentTop; scanY < DIAG_SIZE; scanY++) { - int rgb = getRgb(ageTempSpImage, x, scanY); + for (int scanY = segmentTop; scanY < CelestialBodyMatcher.DIAG_SIZE; scanY++) { + int rgb = CelestialBodyMatcher.getRgb(CelestialBodyMatcher.ageTempSpImage, x, scanY); if (rgb == 0x000000) break; count++; } @@ -511,6 +540,6 @@ public static int countTotalColoredPixelsInAgeTempSpColumn(int x, int startY) { } public static int[] getStarColor(int energy) { - return getStarColorFromTempDiagram(energy); + return CelestialBodyMatcher.getStarColorFromTempDiagram(energy); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyType.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyType.java index aa653d5881..abade08437 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyType.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialBodyType.java @@ -20,11 +20,11 @@ public String getSerializedName() { } public static CelestialBodyType fromName(String name) { - for (CelestialBodyType type : values()) { + for (CelestialBodyType type : CelestialBodyType.values()) { if (type.name.equals(name)) { return type; } } - return ROCKY_PLANET; + return CelestialBodyType.ROCKY_PLANET; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialRefactorRegistry.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialRefactorRegistry.java index 3ba47d71ab..53c5f6584a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialRefactorRegistry.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialRefactorRegistry.java @@ -4,6 +4,7 @@ import dev.dubhe.anvilcraft.init.block.ModBlocks; import dev.dubhe.anvilcraft.init.item.ModItems; import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Items; import org.jspecify.annotations.Nullable; import java.util.ArrayList; @@ -50,12 +51,12 @@ public static List getOptions( if (body instanceof SpecialCelestialBodyData s && s.isErrorPlanet()) { return Collections.emptyList(); } - int innermostRing = getInnermostRing(body, amplified); + int innermostRing = CelestialRefactorRegistry.getInnermostRing(body, amplified); int maxRing = amplified ? 5 : 2; - List options = getOptionsForRing(innermostRing, maxRing); + List options = CelestialRefactorRegistry.getOptionsForRing(innermostRing, maxRing); // 行星开采器要求岩石或特殊行星拥有液体。 - if (!hasLiquid(body)) { + if (!CelestialRefactorRegistry.hasLiquid(body)) { options.removeIf(opt -> "planet_exctractor".equals(opt.megastructure())); } @@ -123,7 +124,7 @@ public static List getOptions( // 生态站要求存在生物资源且没有低级文明。 if (resources != null) { options.removeIf(opt -> "eco_station".equals(opt.megastructure()) - && !isEcoStationEligible(resources)); + && !CelestialRefactorRegistry.isEcoStationEligible(resources)); // 神庙要求存在低级文明。 options.removeIf(opt -> "temple".equals(opt.megastructure()) && !resources.hasCivilization()); @@ -155,57 +156,127 @@ public static List getOptionsForRing(int innermostRing, if (innermostRing <= 1 && 1 <= maxRing) { // R1 巨构,主要用于小型岩石行星。 - options.add(CelestialRefactorOption.withMaterial(1, "planet_excavator", - ringModel(1, "excavator"), prefix + "planet_excavator", - ModBlocks.RUBY_PRISM.asItem(), 16)); - options.add(CelestialRefactorOption.withMaterial(1, "planet_exctractor", - ringModel(1, "exctractor"), prefix + "planet_exctractor", - ModBlocks.PUMP.asItem(), 16)); - options.add(CelestialRefactorOption.withMaterial(1, "eco_station", - ringModel(1, "eco_station"), prefix + "eco_station", - ModBlocks.TEMPERING_GLASS.asItem(), 64)); - options.add(CelestialRefactorOption.withMaterial(1, "temple", - ringModel(1, "temple"), prefix + "temple", - net.minecraft.world.item.Items.GOLD_BLOCK, 64)); + options.add(CelestialRefactorOption.withMaterial( + 1, + "planet_excavator", + CelestialRefactorRegistry.ringModel(1, "excavator"), + prefix + "planet_excavator", + ModBlocks.RUBY_PRISM.asItem(), + 16 + )); + options.add(CelestialRefactorOption.withMaterial( + 1, + "planet_exctractor", + CelestialRefactorRegistry.ringModel(1, "exctractor"), + prefix + "planet_exctractor", + ModBlocks.PUMP.asItem(), + 16 + )); + options.add(CelestialRefactorOption.withMaterial( + 1, + "eco_station", + CelestialRefactorRegistry.ringModel(1, "eco_station"), + prefix + "eco_station", + ModBlocks.TEMPERING_GLASS.asItem(), + 64 + )); + options.add(CelestialRefactorOption.withMaterial( + 1, + "temple", + CelestialRefactorRegistry.ringModel(1, "temple"), + prefix + "temple", + Items.GOLD_BLOCK, + 64 + )); } if (innermostRing <= 2 && 2 <= maxRing) { // R2 巨构,主要用于小型巨行星。 - options.add(CelestialRefactorOption.withMaterial(2, "giant_planet_exctractor", - ringModel(2, "exctractor"), prefix + "giant_planet_exctractor", - ModBlocks.PUMP.asItem(), 32)); + options.add(CelestialRefactorOption.withMaterial( + 2, + "giant_planet_exctractor", + CelestialRefactorRegistry.ringModel(2, "exctractor"), + prefix + "giant_planet_exctractor", + ModBlocks.PUMP.asItem(), + 32 + )); } if (innermostRing <= 4 && 4 <= maxRing) { // R4 巨构,主要用于小型恒星和致密天体。 - options.add(CelestialRefactorOption.withMaterial(4, "stellar_ring_collider", - ringModel(4, "collider"), prefix + "stellar_ring_collider", - ModItems.STELLAR_RING_COMPONENT, 8)); - options.add(CelestialRefactorOption.withMaterial(4, "dyson_sphere_small", - ringModel(4, "dyson_sphere"), prefix + "dyson_sphere_small", - ModItems.DYSON_SPHERE_COMPONENT, 16)); - options.add(CelestialRefactorOption.withMaterial(4, "magnetar_coil", - ringModel(4, "coil"), prefix + "magnetar_coil", - ModItems.MAGNETAR_COIL_COMPONENT, 4)); - options.add(CelestialRefactorOption.withMaterial(4, "penrose_sphere", - ringModel(4, "penrose_sphere"), prefix + "penrose_sphere", - ModItems.PENROSE_SPHERE_COMPONENT, 8)); - options.add(CelestialRefactorOption.withMaterial(4, "matter_decompressor", - ringModel(4, "matter_decompressor"), prefix + "matter_decompressor", - ModItems.MATTER_DECOMPRESSOR_COMPONENT, 2)); - options.add(CelestialRefactorOption.withMaterial(4, "wormhole_stabilizer", - ringModel(4, "wormhole_stabilizer"), prefix + "wormhole_stabilizer", - ModItems.WORMHOLE_STABILIZER_COMPONENT, 4)); - options.add(CelestialRefactorOption.withMaterial(5, "stellar_evolution_accelerator", - ringModel(5, "stellar_evolution_accelerator"), prefix + "stellar_evolution_accelerator", - ModItems.STELLAR_EVOLUTION_ACCELERATOR_COMPONENT, 8)); + options.add(CelestialRefactorOption.withMaterial( + 4, + "stellar_ring_collider", + CelestialRefactorRegistry.ringModel(4, "collider"), + prefix + "stellar_ring_collider", + ModItems.STELLAR_RING_COMPONENT, + 8 + )); + options.add(CelestialRefactorOption.withMaterial( + 4, + "dyson_sphere_small", + CelestialRefactorRegistry.ringModel(4, "dyson_sphere"), + prefix + "dyson_sphere_small", + ModItems.DYSON_SPHERE_COMPONENT, + 16 + )); + options.add(CelestialRefactorOption.withMaterial( + 4, + "magnetar_coil", + CelestialRefactorRegistry.ringModel(4, "coil"), + prefix + "magnetar_coil", + ModItems.MAGNETAR_COIL_COMPONENT, + 4 + )); + options.add(CelestialRefactorOption.withMaterial( + 4, + "penrose_sphere", + CelestialRefactorRegistry.ringModel(4, "penrose_sphere"), + prefix + "penrose_sphere", + ModItems.PENROSE_SPHERE_COMPONENT, + 8 + )); + options.add(CelestialRefactorOption.withMaterial( + 4, + "matter_decompressor", + CelestialRefactorRegistry.ringModel(4, "matter_decompressor"), + prefix + "matter_decompressor", + ModItems.MATTER_DECOMPRESSOR_COMPONENT, + 2 + )); + options.add(CelestialRefactorOption.withMaterial( + 4, + "wormhole_stabilizer", + CelestialRefactorRegistry.ringModel(4, "wormhole_stabilizer"), + prefix + "wormhole_stabilizer", + ModItems.WORMHOLE_STABILIZER_COMPONENT, + 4 + )); + options.add(CelestialRefactorOption.withMaterial( + 5, + "stellar_evolution_accelerator", + CelestialRefactorRegistry.ringModel(5, "stellar_evolution_accelerator"), + prefix + "stellar_evolution_accelerator", + ModItems.STELLAR_EVOLUTION_ACCELERATOR_COMPONENT, + 8 + )); } if (innermostRing <= 5 && 5 <= maxRing) { // R5 巨构,主要用于大型恒星。 - options.add(CelestialRefactorOption.withMaterial(5, "dyson_sphere_large", - ringModel(5, "dyson_sphere"), prefix + "dyson_sphere_large", - ModItems.DYSON_SPHERE_COMPONENT, 32)); - options.add(CelestialRefactorOption.withMaterial(6, "stellar_evolution_accelerator", - ringModel(6, "stellar_evolution_accelerator"), prefix + "stellar_evolution_accelerator", - ModItems.STELLAR_EVOLUTION_ACCELERATOR_COMPONENT, 8)); + options.add(CelestialRefactorOption.withMaterial( + 5, + "dyson_sphere_large", + CelestialRefactorRegistry.ringModel(5, "dyson_sphere"), + prefix + "dyson_sphere_large", + ModItems.DYSON_SPHERE_COMPONENT, + 32 + )); + options.add(CelestialRefactorOption.withMaterial( + 6, + "stellar_evolution_accelerator", + CelestialRefactorRegistry.ringModel(6, "stellar_evolution_accelerator"), + prefix + "stellar_evolution_accelerator", + ModItems.STELLAR_EVOLUTION_ACCELERATOR_COMPONENT, + 8 + )); } return options; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSearchHistory.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSearchHistory.java index bd6cd6d6d6..f85d54401c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSearchHistory.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSearchHistory.java @@ -22,7 +22,7 @@ public void add(CelestialBodyData body, @Nullable PlanetaryResourceSet resources return; } this.entries.addFirst(new Entry(body, resources)); - while (this.entries.size() > MAX_ENTRIES) { + while (this.entries.size() > CelestialSearchHistory.MAX_ENTRIES) { this.entries.removeLast(); } this.resetBrowsing(); @@ -86,8 +86,8 @@ public void setBrowseIndex(int browseIndex) { public CompoundTag toTag() { CompoundTag tag = new CompoundTag(); - tag.putInt("size", Math.min(this.entries.size(), MAX_ENTRIES)); - for (int i = 0; i < Math.min(this.entries.size(), MAX_ENTRIES); i++) { + tag.putInt("size", Math.min(this.entries.size(), CelestialSearchHistory.MAX_ENTRIES)); + for (int i = 0; i < Math.min(this.entries.size(), CelestialSearchHistory.MAX_ENTRIES); i++) { tag.put("h" + i, this.entries.get(i).toTag()); } return tag; @@ -96,7 +96,7 @@ public CompoundTag toTag() { /** 同时兼容当前“天体加资源”格式和旧版仅保存天体的格式。 */ public void load(CompoundTag tag) { this.clear(); - int size = Math.min(tag.getIntOr("size", 0), MAX_ENTRIES); + int size = Math.min(tag.getIntOr("size", 0), CelestialSearchHistory.MAX_ENTRIES); for (int i = 0; i < size; i++) { String key = "h" + i; if (!tag.contains(key)) continue; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSnapshotCodec.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSnapshotCodec.java index d2a5f613ff..585bac3b64 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSnapshotCodec.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/CelestialSnapshotCodec.java @@ -24,23 +24,23 @@ private CelestialSnapshotCodec() { if (stack.getItem() instanceof DiskItem && DiskItem.hasDataStored(stack)) { return DiskItem.getData(stack).copy(); } - return load(stack); + return CelestialSnapshotCodec.load(stack); } public static @Nullable CompoundTag load(ItemStack stack) { if (stack.getItem() instanceof DiskItem && DiskItem.hasDataStored(stack)) { CompoundTag data = DiskItem.getData(stack); - if (data.contains(BODY_KEY)) return data.copy(); + if (data.contains(CelestialSnapshotCodec.BODY_KEY)) return data.copy(); } if (!stack.is(ModBlocks.SINGULARITY_CRYSTAL.asItem())) return null; CustomData customData = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY); - CompoundTag snapshot = customData.copyTag().getCompoundOrEmpty(SNAPSHOT_KEY); - return snapshot.contains(BODY_KEY) ? snapshot.copy() : null; + CompoundTag snapshot = customData.copyTag().getCompoundOrEmpty(CelestialSnapshotCodec.SNAPSHOT_KEY); + return snapshot.contains(CelestialSnapshotCodec.BODY_KEY) ? snapshot.copy() : null; } public static void save(ItemStack stack, CompoundTag snapshot) { if (stack.getItem() instanceof DiskItem) { - if (containsExtremeBody(snapshot)) return; + if (CelestialSnapshotCodec.containsExtremeBody(snapshot)) return; CompoundTag diskTag = DiskItem.hasDataStored(stack) ? DiskItem.getData(stack).copy() : new CompoundTag(); @@ -51,14 +51,14 @@ public static void save(ItemStack stack, CompoundTag snapshot) { if (stack.is(ModBlocks.SINGULARITY_CRYSTAL.asItem())) { CustomData oldCustom = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY); CompoundTag updated = oldCustom.copyTag(); - updated.put(SNAPSHOT_KEY, snapshot.copy()); + updated.put(CelestialSnapshotCodec.SNAPSHOT_KEY, snapshot.copy()); stack.set(DataComponents.CUSTOM_DATA, CustomData.of(updated)); } } private static boolean containsExtremeBody(CompoundTag snapshot) { - if (!snapshot.contains(BODY_KEY)) return false; - String bodyClass = snapshot.getCompoundOrEmpty(BODY_KEY).getStringOr("bodyClass", ""); + if (!snapshot.contains(CelestialSnapshotCodec.BODY_KEY)) return false; + String bodyClass = snapshot.getCompoundOrEmpty(CelestialSnapshotCodec.BODY_KEY).getStringOr("bodyClass", ""); return CelestialBodyClass.BLACK_HOLE.name().equals(bodyClass) || CelestialBodyClass.NEUTRON_STAR.name().equals(bodyClass); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/LiquidCoverage.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/LiquidCoverage.java index 2742294211..d91075ec3e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/LiquidCoverage.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/LiquidCoverage.java @@ -20,11 +20,11 @@ public String getSerializedName() { } public static LiquidCoverage fromName(String name) { - for (LiquidCoverage value : values()) { + for (LiquidCoverage value : LiquidCoverage.values()) { if (value.name.equals(name)) { return value; } } - return NONE; + return LiquidCoverage.NONE; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceGenerator.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceGenerator.java index 13195e8b6e..06be78dbb5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceGenerator.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceGenerator.java @@ -29,6 +29,8 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -90,27 +92,27 @@ public static PlanetaryResourceSet generate( } if (body instanceof RockyPlanetData rocky) { - generateMinerals(set, mineralRecipe, level.registryAccess(), random, seedItemId); - generateFluids(set, fluidRecipes, rocky); + PlanetResourceGenerator.generateMinerals(set, mineralRecipe, level.registryAccess(), random, seedItemId); + PlanetResourceGenerator.generateFluids(set, fluidRecipes, rocky); - if (isLifeEligible(rocky)) { - int lifeChance = getLifeChance(rocky, biologicalRecipe); + if (PlanetResourceGenerator.isLifeEligible(rocky)) { + int lifeChance = PlanetResourceGenerator.getLifeChance(rocky, biologicalRecipe); boolean lifeExists = lifeChance > 0 && random.nextInt(100) < lifeChance; if (lifeExists) { - boolean hasCivilization = tryCivilization(set, offeringRecipe, rocky, ageAnvilCount, random); + boolean hasCivilization = PlanetResourceGenerator.tryCivilization(set, offeringRecipe, rocky, ageAnvilCount, random); if (hasCivilization) { set.setHasCivilization(); } else { - tryBiologicalLifeConfirmed(set, biologicalRecipe, rocky, level, random); + PlanetResourceGenerator.tryBiologicalLifeConfirmed(set, biologicalRecipe, rocky, level, random); } } else { - tryWasteland(set, wastelandRecipe, rocky, ageAnvilCount, random); + PlanetResourceGenerator.tryWasteland(set, wastelandRecipe, rocky, ageAnvilCount, random); } } } else if (body instanceof GiantPlanetData) { - generateGiantItems(set, giantItemRecipes, random); - generateGiantFluids(set, giantFluidRecipes, random); + PlanetResourceGenerator.generateGiantItems(set, giantItemRecipes, random); + PlanetResourceGenerator.generateGiantFluids(set, giantFluidRecipes, random); } return set; @@ -144,7 +146,7 @@ private static void generateMinerals( })); if (candidates.isEmpty()) return; - Collections.shuffle(candidates, new java.util.Random(random.nextLong())); + Collections.shuffle(candidates, new Random(random.nextLong())); int step = md.step(); int sum = 0; @@ -157,7 +159,7 @@ private static void generateMinerals( float exponent = 1.0f + 1.0f / (candidateIndex + 1); float skewed = (float) Math.pow(random.nextFloat(), exponent); int steps = 1 + (int) (skewed * maxSteps); - if (candidate.equals(seedItemId)) { + if (Objects.equals(candidate, seedItemId)) { steps++; } int weight = steps * step; @@ -242,15 +244,11 @@ private static boolean tryCivilization( for (PlanetResourceRecipe.WeightedEntry entry : od.entries()) { Identifier id = entry.resourceId(); if ("anvilcraft:gem_amulet_random".equals(id.toString())) { - Identifier randomAmulet = pickRandomGemAmulet(random); - if (randomAmulet != null) { - set.addOffering(new PlanetaryResourceSet.WeightedItemStack(randomAmulet, entry.weight())); - } + Identifier randomAmulet = PlanetResourceGenerator.pickRandomGemAmulet(random); + set.addOffering(new PlanetaryResourceSet.WeightedItemStack(randomAmulet, entry.weight())); } else if ("anvilcraft:gem_block_random".equals(id.toString())) { - Identifier randomBlock = pickRandomGemBlock(random); - if (randomBlock != null) { - set.addOffering(new PlanetaryResourceSet.WeightedItemStack(randomBlock, entry.weight())); - } + Identifier randomBlock = PlanetResourceGenerator.pickRandomGemBlock(random); + set.addOffering(new PlanetaryResourceSet.WeightedItemStack(randomBlock, entry.weight())); } else { set.addOffering(new PlanetaryResourceSet.WeightedItemStack(id, entry.weight())); } @@ -272,7 +270,7 @@ private static void tryBiologicalLifeConfirmed( boolean isHighCoverage = rocky.liquidCoverage() == LiquidCoverage.HIGH; TagKey blacklistTag = TagKey.create(Registries.ITEM, Identifier.parse(bd.dropBlacklistTag())); - Set blacklist = buildItemBlacklist(level.registryAccess(), blacklistTag); + Set blacklist = PlanetResourceGenerator.buildItemBlacklist(level.registryAccess(), blacklistTag); Map dropFrequencies = new HashMap<>(); level.registryAccess().lookupOrThrow(Registries.ENTITY_TYPE).listElements().forEach(holder -> { @@ -284,14 +282,14 @@ private static void tryBiologicalLifeConfirmed( || cat == MobCategory.UNDERGROUND_WATER_CREATURE : cat == MobCategory.CREATURE; if (matches) { - collectEntityDropFrequencies(entityType, level, random, dropFrequencies, blacklist); + PlanetResourceGenerator.collectEntityDropFrequencies(entityType, level, random, dropFrequencies, blacklist); } }); if (!dropFrequencies.isEmpty()) { List> candidates = new ArrayList<>(dropFrequencies.entrySet()); candidates.removeIf(e -> e.getValue() <= 0); - Collections.shuffle(candidates, new java.util.Random(random.nextLong())); + Collections.shuffle(candidates, new Random(random.nextLong())); final int step = 10; int sum = 0; @@ -405,7 +403,6 @@ private static void collectEntityDropFrequencies( } } - @Nullable private static Identifier pickRandomGemAmulet(RandomSource random) { List knownAmulets = List.of( Identifier.parse("anvilcraft:emerald_amulet"), @@ -416,7 +413,6 @@ private static Identifier pickRandomGemAmulet(RandomSource random) { return knownAmulets.get(random.nextInt(knownAmulets.size())); } - @Nullable private static Identifier pickRandomGemBlock(RandomSource random) { List knownBlocks = List.of( Identifier.parse("minecraft:emerald_block"), diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceRecipe.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceRecipe.java index 8ad09e714c..8794a89a7a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceRecipe.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetResourceRecipe.java @@ -52,7 +52,7 @@ public String getSerializedName() { } public static Category fromName(String name) { - for (Category value : values()) { + for (Category value : Category.values()) { if (value.name.equals(name)) return value; } throw new IllegalArgumentException("Unknown planet resource category: " + name); @@ -271,7 +271,7 @@ public void encode(RegistryFriendlyByteBuf buf, PlanetResourceRecipe recipe) { }; public static final RecipeSerializer SERIALIZER = new RecipeSerializer<>( - CODEC, STREAM_CODEC + PlanetResourceRecipe.CODEC, PlanetResourceRecipe.STREAM_CODEC ); @Override @@ -327,7 +327,7 @@ public RecipeBookCategory recipeBookCategory() { @Override public RecipeSerializer getSerializer() { - return SERIALIZER; + return PlanetResourceRecipe.SERIALIZER; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetaryResourceSet.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetaryResourceSet.java index 4f71c72547..fa5541d6d6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetaryResourceSet.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PlanetaryResourceSet.java @@ -157,28 +157,28 @@ void setWasteland() { public CompoundTag toTag() { CompoundTag tag = new CompoundTag(); if (!this.minerals.isEmpty()) { - tag.put("minerals", writeItemList(this.minerals)); + tag.put("minerals", PlanetaryResourceSet.writeItemList(this.minerals)); } if (!this.fluids.isEmpty()) { - tag.put("fluids", writeFluidList(this.fluids)); + tag.put("fluids", PlanetaryResourceSet.writeFluidList(this.fluids)); } if (!this.giantItems.isEmpty()) { - tag.put("giantItems", writeItemList(this.giantItems)); + tag.put("giantItems", PlanetaryResourceSet.writeItemList(this.giantItems)); } if (!this.giantFluids.isEmpty()) { - tag.put("giantFluids", writeFluidList(this.giantFluids)); + tag.put("giantFluids", PlanetaryResourceSet.writeFluidList(this.giantFluids)); } if (!this.biologicalItems.isEmpty()) { - tag.put("biologicalItems", writeItemList(this.biologicalItems)); + tag.put("biologicalItems", PlanetaryResourceSet.writeItemList(this.biologicalItems)); } if (!this.biologicalFluids.isEmpty()) { - tag.put("biologicalFluids", writeFluidList(this.biologicalFluids)); + tag.put("biologicalFluids", PlanetaryResourceSet.writeFluidList(this.biologicalFluids)); } if (!this.offerings.isEmpty()) { - tag.put("offerings", writeItemList(this.offerings)); + tag.put("offerings", PlanetaryResourceSet.writeItemList(this.offerings)); } if (!this.wastelandItems.isEmpty()) { - tag.put("wastelandItems", writeItemList(this.wastelandItems)); + tag.put("wastelandItems", PlanetaryResourceSet.writeItemList(this.wastelandItems)); } tag.putBoolean("hasCivilization", this.hasCivilization); tag.putBoolean("isWasteland", this.isWasteland); @@ -187,14 +187,14 @@ public CompoundTag toTag() { public static PlanetaryResourceSet fromTag(CompoundTag tag) { PlanetaryResourceSet set = new PlanetaryResourceSet(); - tag.getList("minerals").ifPresent(listTag -> readItemList(listTag, set.minerals)); - tag.getList("fluids").ifPresent(listTag -> readFluidList(listTag, set.fluids)); - tag.getList("giantItems").ifPresent(listTag -> readItemList(listTag, set.giantItems)); - tag.getList("giantFluids").ifPresent(listTag -> readFluidList(listTag, set.giantFluids)); - tag.getList("biologicalItems").ifPresent(listTag -> readItemList(listTag, set.biologicalItems)); - tag.getList("biologicalFluids").ifPresent(listTag -> readFluidList(listTag, set.biologicalFluids)); - tag.getList("offerings").ifPresent(listTag -> readItemList(listTag, set.offerings)); - tag.getList("wastelandItems").ifPresent(listTag -> readItemList(listTag, set.wastelandItems)); + tag.getList("minerals").ifPresent(listTag -> PlanetaryResourceSet.readItemList(listTag, set.minerals)); + tag.getList("fluids").ifPresent(listTag -> PlanetaryResourceSet.readFluidList(listTag, set.fluids)); + tag.getList("giantItems").ifPresent(listTag -> PlanetaryResourceSet.readItemList(listTag, set.giantItems)); + tag.getList("giantFluids").ifPresent(listTag -> PlanetaryResourceSet.readFluidList(listTag, set.giantFluids)); + tag.getList("biologicalItems").ifPresent(listTag -> PlanetaryResourceSet.readItemList(listTag, set.biologicalItems)); + tag.getList("biologicalFluids").ifPresent(listTag -> PlanetaryResourceSet.readFluidList(listTag, set.biologicalFluids)); + tag.getList("offerings").ifPresent(listTag -> PlanetaryResourceSet.readItemList(listTag, set.offerings)); + tag.getList("wastelandItems").ifPresent(listTag -> PlanetaryResourceSet.readItemList(listTag, set.wastelandItems)); set.hasCivilization = tag.getBooleanOr("hasCivilization", false); set.isWasteland = tag.getBooleanOr("isWasteland", false); return set; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PressureType.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PressureType.java index d031a569ac..c18690c70d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PressureType.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/PressureType.java @@ -18,11 +18,11 @@ public String getSerializedName() { } public static PressureType fromName(String name) { - for (PressureType value : values()) { + for (PressureType value : PressureType.values()) { if (value.name.equals(name)) { return value; } } - return GAS; + return PressureType.GAS; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/RingType.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/RingType.java index 47af092548..3a9e6c87ff 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/RingType.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/RingType.java @@ -19,11 +19,11 @@ public String getSerializedName() { } public static RingType fromName(String name) { - for (RingType value : values()) { + for (RingType value : RingType.values()) { if (value.name.equals(name)) { return value; } } - return NONE; + return RingType.NONE; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/ShatteredPlanet.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/ShatteredPlanet.java index 28b6d7a3d6..073dd43fd3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/ShatteredPlanet.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/ShatteredPlanet.java @@ -30,10 +30,10 @@ public static SpecialCelestialBodyData createBody() { public static PlanetaryResourceSet createResources() { PlanetaryResourceSet resources = new PlanetaryResourceSet(); - resources.addMineral(item(AnvilCraft.of("raw_tungsten"), 30)); - resources.addMineral(item(Identifier.withDefaultNamespace("raw_gold"), 30)); - resources.addMineral(item(AnvilCraft.of("raw_silver"), 30)); - resources.addMineral(item(AnvilCraft.of("earth_core_shard"), 10)); + resources.addMineral(ShatteredPlanet.item(AnvilCraft.of("raw_tungsten"), 30)); + resources.addMineral(ShatteredPlanet.item(Identifier.withDefaultNamespace("raw_gold"), 30)); + resources.addMineral(ShatteredPlanet.item(AnvilCraft.of("raw_silver"), 30)); + resources.addMineral(ShatteredPlanet.item(AnvilCraft.of("earth_core_shard"), 10)); resources.addFluid(new PlanetaryResourceSet.WeightedFluidStack( Identifier.withDefaultNamespace("lava"), 100 diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/SpecialCelestialBodyRecipe.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/SpecialCelestialBodyRecipe.java index c02cee8467..050502b7d8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/SpecialCelestialBodyRecipe.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/SpecialCelestialBodyRecipe.java @@ -120,7 +120,8 @@ private record ResourceFields( Codec.INT.fieldOf("energy").forGetter(SpecialCelestialBodyRecipe::energy), Codec.STRING.fieldOf("texture").forGetter(SpecialCelestialBodyRecipe::textureName), Codec.BOOL.fieldOf("has_atmosphere").forGetter(SpecialCelestialBodyRecipe::hasAtmosphere), - LIQUID_COVERAGE_CODEC.optionalFieldOf("liquid_coverage").forGetter(SpecialCelestialBodyRecipe::liquidCoverage), + SpecialCelestialBodyRecipe.LIQUID_COVERAGE_CODEC.optionalFieldOf("liquid_coverage") + .forGetter(SpecialCelestialBodyRecipe::liquidCoverage), Codec.INT.fieldOf("magnetic_field").forGetter(SpecialCelestialBodyRecipe::magneticFieldStrength), Codec.INT.fieldOf("rotation_speed").forGetter(SpecialCelestialBodyRecipe::rotationSpeed), Codec.FLOAT.fieldOf("axial_tilt").forGetter(SpecialCelestialBodyRecipe::axialTilt), @@ -161,7 +162,7 @@ public SpecialCelestialBodyRecipe decode(RegistryFriendlyByteBuf buf) { int energy = buf.readInt(); String textureName = buf.readUtf(); boolean hasAtmosphere = buf.readBoolean(); - Optional liquidCoverage = ByteBufCodecs.optional(LIQUID_COVERAGE_STREAM).decode(buf); + Optional liquidCoverage = ByteBufCodecs.optional(SpecialCelestialBodyRecipe.LIQUID_COVERAGE_STREAM).decode(buf); int magneticFieldStrength = buf.readInt(); int rotationSpeed = buf.readInt(); float axialTilt = buf.readFloat(); @@ -193,7 +194,7 @@ public void encode(RegistryFriendlyByteBuf buf, SpecialCelestialBodyRecipe r) { buf.writeInt(r.energy()); buf.writeUtf(r.textureName()); buf.writeBoolean(r.hasAtmosphere()); - ByteBufCodecs.optional(LIQUID_COVERAGE_STREAM).encode(buf, r.liquidCoverage()); + ByteBufCodecs.optional(SpecialCelestialBodyRecipe.LIQUID_COVERAGE_STREAM).encode(buf, r.liquidCoverage()); buf.writeInt(r.magneticFieldStrength()); buf.writeInt(r.rotationSpeed()); buf.writeFloat(r.axialTilt()); @@ -209,11 +210,11 @@ public void encode(RegistryFriendlyByteBuf buf, SpecialCelestialBodyRecipe r) { }; public static final RecipeSerializer SERIALIZER = new RecipeSerializer<>( - CODEC, STREAM_CODEC + SpecialCelestialBodyRecipe.CODEC, SpecialCelestialBodyRecipe.STREAM_CODEC ); public Temperature temperature() { - return energyToTemperature(this.energy); + return SpecialCelestialBodyRecipe.energyToTemperature(this.energy); } private static Temperature energyToTemperature(int energy) { @@ -235,10 +236,10 @@ public boolean hasCivilization() { public Item getEffectiveSeedItem(long worldSeed) { if (this.seedItems.isEmpty()) return Items.AIR; if (this.seedItems.size() == 1) { - return resolveItem(this.seedItems.getFirst()); + return SpecialCelestialBodyRecipe.resolveItem(this.seedItems.getFirst()); } Random random = new Random(worldSeed * 31L + this.name.hashCode() * 7919L); - return resolveItem(this.seedItems.get(random.nextInt(this.seedItems.size()))); + return SpecialCelestialBodyRecipe.resolveItem(this.seedItems.get(random.nextInt(this.seedItems.size()))); } public boolean isEffectiveSeedItem(Item consumedItem, long worldSeed) { @@ -299,7 +300,7 @@ public RecipeBookCategory recipeBookCategory() { @Override public RecipeSerializer getSerializer() { - return SERIALIZER; + return SpecialCelestialBodyRecipe.SERIALIZER; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/Temperature.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/Temperature.java index 11ce8792da..c638eacde6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/Temperature.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/Temperature.java @@ -21,11 +21,11 @@ public String getSerializedName() { } public static Temperature fromName(String name) { - for (Temperature value : values()) { + for (Temperature value : Temperature.values()) { if (value.name.equals(name)) { return value; } } - return MILD; + return Temperature.MILD; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/TempleDemandRecipe.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/TempleDemandRecipe.java index f9fe2e6ddd..b353e884e5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/TempleDemandRecipe.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/TempleDemandRecipe.java @@ -48,7 +48,7 @@ public String getSerializedName() { } public static Category fromName(String name) { - for (Category value : values()) { + for (Category value : Category.values()) { if (value.name.equals(name)) return value; } throw new IllegalArgumentException("Unknown temple demand category: " + name); @@ -89,7 +89,7 @@ public Identifier itemResource() { ); public static final RecipeSerializer SERIALIZER = new RecipeSerializer<>( - CODEC, STREAM_CODEC + TempleDemandRecipe.CODEC, TempleDemandRecipe.STREAM_CODEC ); @Override @@ -120,7 +120,7 @@ public RecipeBookCategory recipeBookCategory() { @Override public RecipeSerializer getSerializer() { - return SERIALIZER; + return TempleDemandRecipe.SERIALIZER; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/WindSpeed.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/WindSpeed.java index 613d916d3a..76587dc4a2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/WindSpeed.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/celestial/WindSpeed.java @@ -18,11 +18,11 @@ public String getSerializedName() { } public static WindSpeed fromName(String name) { - for (WindSpeed value : values()) { + for (WindSpeed value : WindSpeed.values()) { if (value.name.equals(name)) { return value; } } - return HIGH; + return WindSpeed.HIGH; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/AbstractPipeBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/AbstractPipeBlockEntity.java index f5ff91b6bd..14d4f6bb08 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/AbstractPipeBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/AbstractPipeBlockEntity.java @@ -113,27 +113,27 @@ public boolean setPowered(boolean powered) { @Override protected void saveAdditional(ValueOutput output) { super.saveAdditional(output); - output.putBoolean(TAG_POWERED, this.powered); + output.putBoolean(AbstractPipeBlockEntity.TAG_POWERED, this.powered); this.writeValves(output); } @Override public void loadAdditional(ValueInput input) { super.loadAdditional(input); - this.powered = input.getBooleanOr(TAG_POWERED, false); + this.powered = input.getBooleanOr(AbstractPipeBlockEntity.TAG_POWERED, false); this.readValves(input); } @Override public CompoundTag getUpdateTag(HolderLookup.Provider registries) { TagValueOutput output = TagValueOutput.createWithContext(new ProblemReporter.Collector(this.problemPath()), registries); - output.putBoolean(TAG_POWERED, this.powered); + output.putBoolean(AbstractPipeBlockEntity.TAG_POWERED, this.powered); this.writeValves(output); return output.buildResult(); } private void writeValves(ValueOutput output) { - ValueOutput.TypedOutputList list = output.list(TAG_VALVES, ValveData.CODEC); + ValueOutput.TypedOutputList list = output.list(AbstractPipeBlockEntity.TAG_VALVES, ValveData.CODEC); for (Map.Entry entry : this.baseFlow.entrySet()) { list.add(new ValveData(entry.getKey(), entry.getValue())); } @@ -141,7 +141,7 @@ private void writeValves(ValueOutput output) { private void readValves(ValueInput input) { this.baseFlow.clear(); - for (ValveData valve : input.listOrEmpty(TAG_VALVES, ValveData.CODEC)) { + for (ValveData valve : input.listOrEmpty(AbstractPipeBlockEntity.TAG_VALVES, ValveData.CODEC)) { this.baseFlow.put(valve.face(), valve.flow()); } } @@ -169,7 +169,7 @@ public static boolean canFlowThroughCheckValve(Level level, BlockPos pipePos, Di * 从指定位置出发,沿管道递归追踪 PipeEnd。 */ public static @Nullable PipeEnd getPipeEnd(Level level, BlockPos blockPos, Direction direction, int accumulatedHeight) { - return getPipeEnd(level, blockPos, direction, accumulatedHeight, true); + return AbstractPipeBlockEntity.getPipeEnd(level, blockPos, direction, accumulatedHeight, true); } public static @Nullable PipeEnd getPipeEnd( @@ -179,22 +179,22 @@ public static boolean canFlowThroughCheckValve(Level level, BlockPos pipePos, Di BlockState blockState = level.getBlockState(blockPos); if (checkValves && blockState.getBlock() instanceof PipeBlock - && !canFlowThroughCheckValve(level, blockPos, direction, direction.getOpposite())) { + && !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, blockPos, direction, direction.getOpposite())) { return null; } if (blockState.getBlock() instanceof PipeNodeBlock) { return new PipeEnd(blockPos.relative(direction.getOpposite()), direction, accumulatedHeight); } if (blockState.getBlock() instanceof PipeStraightBlock) { - return getPipeStraightEnd(level, blockPos, blockState, direction, accumulatedHeight, checkValves); + return AbstractPipeBlockEntity.getPipeStraightEnd(level, blockPos, blockState, direction, accumulatedHeight, checkValves); } if (blockState.getBlock() instanceof PipeCornerBlock) { - return getPipeCornerEnd(level, blockPos, blockState, direction, accumulatedHeight, checkValves); + return AbstractPipeBlockEntity.getPipeCornerEnd(level, blockPos, blockState, direction, accumulatedHeight, checkValves); } if (blockState.getBlock() instanceof PumpBlock) { Direction pumpOutputDir = blockState.getValue(PumpBlock.ORIENTATION).getDirection(); if (direction == pumpOutputDir && level.getBlockEntity(blockPos) instanceof PumpBlockEntity pumpBe && pumpBe.canPump()) { - return getPumpPipeEnd(level, blockPos, direction, accumulatedHeight, checkValves); + return AbstractPipeBlockEntity.getPumpPipeEnd(level, blockPos, direction, accumulatedHeight, checkValves); } return null; } @@ -202,7 +202,7 @@ public static boolean canFlowThroughCheckValve(Level level, BlockPos pipePos, Di } public static @Nullable PipeEnd getPipeEnd(Level level, BlockPos blockPos, Direction direction) { - return getPipeEnd(level, blockPos, direction, 0); + return AbstractPipeBlockEntity.getPipeEnd(level, blockPos, direction, 0); } public static @Nullable PipeEnd getPipeStraightEnd( @@ -215,15 +215,15 @@ public static boolean canFlowThroughCheckValve(Level level, BlockPos pipePos, Di if (direction.equals(startDir)) hasNext = !blockState.getValue(PipeStraightBlock.HAS_END_END); else hasNext = !blockState.getValue(PipeStraightBlock.HAS_END_START); Direction targetDir = direction.getOpposite(); - if (checkValves && !canFlowThroughCheckValve(level, blockPos, targetDir, targetDir)) return null; + if (checkValves && !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, blockPos, targetDir, targetDir)) return null; if (!hasNext) { BlockPos neighborPos = blockPos.relative(targetDir); if (level.getBlockState(neighborPos).getBlock() instanceof PumpBlock) { - return getPipeEnd(level, neighborPos, direction, accumulatedHeight, checkValves); + return AbstractPipeBlockEntity.getPipeEnd(level, neighborPos, direction, accumulatedHeight, checkValves); } return new PipeEnd(blockPos, targetDir, accumulatedHeight); } - return getPipeEnd(level, blockPos.relative(targetDir), direction, accumulatedHeight, checkValves); + return AbstractPipeBlockEntity.getPipeEnd(level, blockPos.relative(targetDir), direction, accumulatedHeight, checkValves); } public static @Nullable PipeEnd getPipeCornerEnd( @@ -241,15 +241,21 @@ public static boolean canFlowThroughCheckValve(Level level, BlockPos pipePos, Di hasNext = !blockState.getValue(PipeStraightBlock.HAS_END_START); targetDir = startDir; } - if (checkValves && !canFlowThroughCheckValve(level, blockPos, targetDir, targetDir)) return null; + if (checkValves && !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, blockPos, targetDir, targetDir)) return null; if (!hasNext) { BlockPos neighborPos = blockPos.relative(targetDir); if (level.getBlockState(neighborPos).getBlock() instanceof PumpBlock) { - return getPipeEnd(level, neighborPos, targetDir.getOpposite(), accumulatedHeight, checkValves); + return AbstractPipeBlockEntity.getPipeEnd(level, neighborPos, targetDir.getOpposite(), accumulatedHeight, checkValves); } return new PipeEnd(blockPos, targetDir, accumulatedHeight); } - return getPipeEnd(level, blockPos.relative(targetDir), targetDir.getOpposite(), accumulatedHeight, checkValves); + return AbstractPipeBlockEntity.getPipeEnd( + level, + blockPos.relative(targetDir), + targetDir.getOpposite(), + accumulatedHeight, + checkValves + ); } private static @Nullable PipeEnd getPumpPipeEnd( @@ -262,7 +268,13 @@ public static boolean canFlowThroughCheckValve(Level level, BlockPos pipePos, Di || nextState.getBlock() instanceof PipeStraightBlock || nextState.getBlock() instanceof PipeCornerBlock || nextState.getBlock() instanceof PumpBlock) { - return getPipeEnd(level, nextPos, direction, accumulatedHeight + PumpBlockEntity.PUMP_HEADLIFT, checkValves); + return AbstractPipeBlockEntity.getPipeEnd( + level, + nextPos, + direction, + accumulatedHeight + PumpBlockEntity.PUMP_HEADLIFT, + checkValves + ); } if (PipeBlock.isFluidHandler(level, nextPos)) { return new PipeEnd(pumpPos, direction.getOpposite(), accumulatedHeight + PumpBlockEntity.PUMP_HEADLIFT); @@ -281,13 +293,20 @@ public static void moveFluidWithHeightCheck( if (sourceEffectiveY <= targetEffectiveY) return; Direction sourceDirection = sourceCurDirection.getOpposite(); Direction targetDirection = targetCurDirection.getOpposite(); - if (!canFlowThroughCheckValve(level, sourceCurPos, sourceCurDirection, sourceCurDirection.getOpposite()) - || !canFlowThroughCheckValve(level, targetCurPos, targetCurDirection, targetCurDirection) - || !canFlowThroughCheckValve(level, sourcePos, sourceDirection, sourceDirection) - || !canFlowThroughCheckValve(level, targetPos, targetDirection, targetDirection.getOpposite())) { + if (!AbstractPipeBlockEntity.canFlowThroughCheckValve(level, sourceCurPos, sourceCurDirection, sourceCurDirection.getOpposite()) + || !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, targetCurPos, targetCurDirection, targetCurDirection) + || !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, sourcePos, sourceDirection, sourceDirection) + || !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, targetPos, targetDirection, targetDirection.getOpposite())) { return; } - moveFluid(level, sourcePos, sourceDirection, targetPos, targetDirection, sourceEffectiveY - targetEffectiveY); + AbstractPipeBlockEntity.moveFluid( + level, + sourcePos, + sourceDirection, + targetPos, + targetDirection, + sourceEffectiveY - targetEffectiveY + ); } /** @@ -322,20 +341,37 @@ public static void moveFluidByEffectiveHeight( Direction sourceSide = sourceCurDirection == null ? null : sourceCurDirection.getOpposite(); Direction targetSide = targetCurDirection == null ? null : targetCurDirection.getOpposite(); if (sourceCurDirection != null - && !canFlowThroughCheckValve(level, sourceCurPos, sourceCurDirection, sourceCurDirection.getOpposite())) { + && !AbstractPipeBlockEntity.canFlowThroughCheckValve( + level, + sourceCurPos, + sourceCurDirection, + sourceCurDirection.getOpposite() + )) { return; } if (targetCurDirection != null - && !canFlowThroughCheckValve(level, targetCurPos, targetCurDirection, targetCurDirection)) { + && !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, targetCurPos, targetCurDirection, targetCurDirection)) { return; } - if (sourceSide != null && !canFlowThroughCheckValve(level, sourcePos, sourceSide, sourceSide)) { + if (sourceSide != null && !AbstractPipeBlockEntity.canFlowThroughCheckValve(level, sourcePos, sourceSide, sourceSide)) { return; } - if (targetSide != null && !canFlowThroughCheckValve(level, targetPos, targetSide, targetSide.getOpposite())) { + if (targetSide != null && !AbstractPipeBlockEntity.canFlowThroughCheckValve( + level, + targetPos, + targetSide, + targetSide.getOpposite() + )) { return; } - moveFluid(level, sourcePos, sourceSide, targetPos, targetSide, sourceEffectiveHeight - targetEffectiveHeight); + AbstractPipeBlockEntity.moveFluid( + level, + sourcePos, + sourceSide, + targetPos, + targetSide, + sourceEffectiveHeight - targetEffectiveHeight + ); } /** @@ -343,8 +379,12 @@ public static void moveFluidByEffectiveHeight( * 替代旧的 IFluidHandler.drain()/fill() API。 */ public static void moveFluid( - Level level, BlockPos sourcePos, Direction sourceDirection, - BlockPos targetPos, Direction targetDirection, int heightDiff + Level level, + BlockPos sourcePos, + @Nullable Direction sourceDirection, + BlockPos targetPos, + @Nullable Direction targetDirection, + int heightDiff ) { ResourceHandler source = level.getCapability(Capabilities.Fluid.BLOCK, sourcePos, sourceDirection); ResourceHandler target = level.getCapability(Capabilities.Fluid.BLOCK, targetPos, targetDirection); @@ -413,10 +453,15 @@ public static void moveFluid( } } - public static void moveFluid(Level level, BlockPos sourcePos, Direction sourceDirection, - BlockPos targetPos, Direction targetDirection) { + public static void moveFluid( + Level level, + BlockPos sourcePos, + @Nullable Direction sourceDirection, + BlockPos targetPos, + @Nullable Direction targetDirection + ) { int heightDiff = sourcePos.getY() - targetPos.getY(); - moveFluid(level, sourcePos, sourceDirection, targetPos, targetDirection, heightDiff); + AbstractPipeBlockEntity.moveFluid(level, sourcePos, sourceDirection, targetPos, targetDirection, heightDiff); } /** @@ -426,8 +471,8 @@ public record PipeEnd(BlockPos pos, Direction direction, int effectiveHeight) {} private record ValveData(Direction face, Direction flow) { private static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - DIRECTION_CODEC.fieldOf("Face").forGetter(ValveData::face), - DIRECTION_CODEC.fieldOf("Flow").forGetter(ValveData::flow) + AbstractPipeBlockEntity.DIRECTION_CODEC.fieldOf("Face").forGetter(ValveData::face), + AbstractPipeBlockEntity.DIRECTION_CODEC.fieldOf("Flow").forGetter(ValveData::flow) ).apply(instance, ValveData::new)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/ControlValveBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/ControlValveBlockEntity.java index 374b782794..6b9a037acc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/ControlValveBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/ControlValveBlockEntity.java @@ -38,8 +38,8 @@ public class ControlValveBlockEntity extends BlockEntity implements MenuProvider public static final int FILTER_SLOT_COUNT = 1; public static final int MAX_RATE = 2000; - private final NonNullList filters = NonNullList.withSize(FILTER_SLOT_COUNT, FluidStack.EMPTY); - private int maxRate = MAX_RATE; + private final NonNullList filters = NonNullList.withSize(ControlValveBlockEntity.FILTER_SLOT_COUNT, FluidStack.EMPTY); + private int maxRate = ControlValveBlockEntity.MAX_RATE; private Direction facing = Direction.NORTH; public ControlValveBlockEntity(BlockEntityType type, BlockPos pos, BlockState blockState) { @@ -52,7 +52,7 @@ public void setFacing(Direction facing) { } public void setMaxRate(int maxRate) { - int clamped = Mth.clamp(maxRate, 0, MAX_RATE); + int clamped = Mth.clamp(maxRate, 0, ControlValveBlockEntity.MAX_RATE); if (this.maxRate == clamped) return; this.maxRate = clamped; this.setChanged(); @@ -60,7 +60,7 @@ public void setMaxRate(int maxRate) { } public boolean isLocked() { - BlockState state = getBlockState(); + BlockState state = this.getBlockState(); return state.hasProperty(ControlValveBlock.POWERED) && state.getValue(ControlValveBlock.POWERED); } @@ -121,7 +121,7 @@ protected void saveAdditional(ValueOutput output) { @Override public void loadAdditional(ValueInput input) { super.loadAdditional(input); - this.maxRate = Mth.clamp(input.getIntOr("MaxRate", MAX_RATE), 0, MAX_RATE); + this.maxRate = Mth.clamp(input.getIntOr("MaxRate", ControlValveBlockEntity.MAX_RATE), 0, ControlValveBlockEntity.MAX_RATE); this.facing = Direction.from3DDataValue(input.getIntOr("Facing", Direction.NORTH.get3DDataValue())); this.readFilters(input); } @@ -166,7 +166,7 @@ private void markNetworkDirty() { public void sendUpdate() { if (this.level != null) { - this.level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_CLIENTS); + this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), Block.UPDATE_CLIENTS); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/DrainBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/DrainBlockEntity.java index 8767bf6eac..d1d5dd0fc0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/DrainBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/DrainBlockEntity.java @@ -51,7 +51,7 @@ public class DrainBlockEntity extends BlockEntity implements IFluidResourceHandl private static final int FILL_SOURCE = 2; private static final int FILL_SEARCH_REBUILD_INTERVAL = 256; private static final long EXHAUSTED_SEARCH_TTL = 100; - private final FluidStackResourceHandler tank = new FluidStackResourceHandler(CAPACITY) { + private final FluidStackResourceHandler tank = new FluidStackResourceHandler(DrainBlockEntity.CAPACITY) { @Override protected void onContentChanged(FluidStack original) { DrainBlockEntity.this.setChanged(); @@ -98,13 +98,13 @@ public void setRemoved() { public void sendUpdate() { if (this.level != null && !this.level.isClientSide()) { - this.level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), Block.UPDATE_CLIENTS); + this.level.sendBlockUpdated(this.getBlockPos(), this.getBlockState(), this.getBlockState(), Block.UPDATE_CLIENTS); } } public static void tick(Level level, BlockPos pos, BlockState state, DrainBlockEntity be) { if (level.isClientSide()) return; - if (level.getGameTime() % INTERVAL != 0) return; + if (level.getGameTime() % DrainBlockEntity.INTERVAL != 0) return; FillResult fillResult = be.tryFillDown(level, pos); if (fillResult == FillResult.NONE) be.clearColumn(); be.tryDrainUp(level, pos); @@ -120,7 +120,7 @@ private void clearColumn() { private FillResult tryFillDown(Level level, BlockPos pos) { FluidStack stored = this.tank.getStack(); - if (stored.getAmount() <= FILL_THRESHOLD) { + if (stored.getAmount() <= DrainBlockEntity.FILL_THRESHOLD) { this.fillSearch = null; return FillResult.NONE; } @@ -147,7 +147,7 @@ private FillResult tryFillDown(Level level, BlockPos pos) { } level.setBlock(target, source, Block.UPDATE_ALL); try (Transaction tx = Transaction.openRoot()) { - this.tank.extract(0, FluidResource.of(stored), UNIT, tx); + this.tank.extract(0, FluidResource.of(stored), DrainBlockEntity.UNIT, tx); tx.commit(); } if (this.fillSearch != null && this.fillSearch.acceptFilled(target.asLong())) { @@ -162,14 +162,14 @@ private FillResult tryFillDown(Level level, BlockPos pos) { private SearchResult findFillTarget(Level level, BlockPos drainPos, Fluid fluid) { BlockPos start = drainPos.below(); - if (!isPassableForFill(level, start, fluid)) { + if (!DrainBlockEntity.isPassableForFill(level, start, fluid)) { this.fillSearch = null; return SearchResult.EXHAUSTED; } int minY = level.getMinY(); int bottomY = start.getY(); while (bottomY > minY - && isPassableForFill(level, new BlockPos(drainPos.getX(), bottomY - 1, drainPos.getZ()), fluid)) { + && DrainBlockEntity.isPassableForFill(level, new BlockPos(drainPos.getX(), bottomY - 1, drainPos.getZ()), fluid)) { bottomY--; } if (this.fillSearch == null @@ -180,7 +180,7 @@ && isPassableForFill(level, new BlockPos(drainPos.getX(), bottomY - 1, drainPos. } private static boolean isPassableForFill(Level level, BlockPos pos, Fluid fluid) { - return classifyForFill(level, pos, fluid) != FILL_BLOCKED; + return DrainBlockEntity.classifyForFill(level, pos, fluid) != DrainBlockEntity.FILL_BLOCKED; } private static long offset(BlockPos pos, Direction direction) { @@ -195,10 +195,10 @@ private static int classifyForFill(Level level, BlockPos pos, Fluid fluid) { BlockState state = level.getBlockState(pos); FluidState fs = state.getFluidState(); if (!fs.isEmpty()) { - if (!fs.getType().isSame(fluid)) return FILL_BLOCKED; - return fs.isSource() ? FILL_SOURCE : FILL_TARGET; + if (!fs.getType().isSame(fluid)) return DrainBlockEntity.FILL_BLOCKED; + return fs.isSource() ? DrainBlockEntity.FILL_SOURCE : DrainBlockEntity.FILL_TARGET; } - return state.isAir() || state.canBeReplaced() ? FILL_TARGET : FILL_BLOCKED; + return state.isAir() || state.canBeReplaced() ? DrainBlockEntity.FILL_TARGET : DrainBlockEntity.FILL_BLOCKED; } private static boolean isSameFluidSource(Level level, BlockPos pos, Fluid fluid) { @@ -212,7 +212,7 @@ private static int countSourceNeighbors( int count = 0; for (Direction d : Direction.Plane.HORIZONTAL) { neighborCursor.set(pos.getX() + d.getStepX(), pos.getY(), pos.getZ() + d.getStepZ()); - if (isSameFluidSource(level, neighborCursor, fluid)) count++; + if (DrainBlockEntity.isSameFluidSource(level, neighborCursor, fluid)) count++; } return count; } @@ -220,7 +220,7 @@ private static int countSourceNeighbors( private void tryDrainUp(Level level, BlockPos pos) { if (!this.processFlowCleanup(level)) return; FluidStack stored = this.tank.getStack(); - if (!stored.isEmpty() && stored.getAmount() >= DRAIN_THRESHOLD) { + if (!stored.isEmpty() && stored.getAmount() >= DrainBlockEntity.DRAIN_THRESHOLD) { this.drainSearch = null; return; } @@ -240,25 +240,25 @@ private void tryDrainUp(Level level, BlockPos pos) { this.drainSearch = null; return; } - if (!this.canInsert(fluid, UNIT)) return; + if (!this.canInsert(fluid, DrainBlockEntity.UNIT)) return; this.removeSourceAndQueueFlowCleanup(level, target, fluid); this.processFlowCleanup(level); - this.insert(fluid, UNIT); + this.insert(fluid, DrainBlockEntity.UNIT); this.drainSearch = null; } private void tryGenerateFromInfinite(Level level, BlockPos pos) { if (!(level instanceof ServerLevel serverLevel)) return; FluidStack stored = this.tank.getStack(); - if (!stored.isEmpty() && stored.getAmount() >= CAPACITY) return; + if (!stored.isEmpty() && stored.getAmount() >= DrainBlockEntity.CAPACITY) return; for (Direction d : Direction.Plane.HORIZONTAL) { BlockPos n = pos.relative(d); FluidState fs = level.getFluidState(n); if (fs.isEmpty() || !fs.isSource() || !(fs.getType() instanceof FlowingFluid flowing)) continue; - if (!canFormInfiniteSource(serverLevel, n, flowing)) continue; + if (!DrainBlockEntity.canFormInfiniteSource(serverLevel, n, flowing)) continue; Fluid source = flowing.getSource(); - if (!this.canInsert(source, UNIT)) continue; - this.insert(source, UNIT); + if (!this.canInsert(source, DrainBlockEntity.UNIT)) continue; + this.insert(source, DrainBlockEntity.UNIT); return; } } @@ -277,9 +277,10 @@ private void insert(Fluid fluid, int amount) { } private static boolean canFormInfiniteSource(ServerLevel level, BlockPos pos, FlowingFluid fluid) { - return canRegenerateSourceAt(level, pos, fluid); + return DrainBlockEntity.canRegenerateSourceAt(level, pos, fluid); } + @SuppressWarnings("deprecation") private static boolean canRegenerateSourceAt(ServerLevel level, BlockPos pos, FlowingFluid fluid) { int neighbourSources = 0; for (Direction d : Direction.Plane.HORIZONTAL) { @@ -319,14 +320,14 @@ private SearchResult findHighestDrainTarget(Level level, BlockPos drainPos, @Nul fluid, start.getY(), topY, - level.getGameTime() / INTERVAL + level.getGameTime() / DrainBlockEntity.INTERVAL ); } return this.drainSearch.advance(level); } private void removeSourceAndQueueFlowCleanup(Level level, BlockPos target, Fluid fluid) { - removeFluidSilently(level, target); + DrainBlockEntity.removeFluidSilently(level, target); this.prepareFlowCleanup(fluid); for (Direction direction : Direction.values()) { this.enqueueFlowing(level, target.relative(direction), fluid); @@ -367,13 +368,13 @@ private boolean processFlowCleanup(Level level) { Fluid fluid = this.flowCleanupFluid; BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); int processed = 0; - while (!this.flowCleanupQueue.isEmpty() && processed < MAX_NODES) { + while (!this.flowCleanupQueue.isEmpty() && processed < DrainBlockEntity.MAX_NODES) { long current = this.flowCleanupQueue.dequeueLong(); processed++; cursor.set(BlockPos.getX(current), BlockPos.getY(current), BlockPos.getZ(current)); FluidState fluidState = level.getFluidState(cursor); if (fluidState.isEmpty() || fluidState.isSource() || !fluidState.getType().isSame(fluid)) continue; - removeFluidSilently(level, cursor); + DrainBlockEntity.removeFluidSilently(level, cursor); for (Direction direction : Direction.values()) { cursor.move(direction); this.enqueueFlowing(level, cursor, fluid); @@ -400,7 +401,7 @@ private static boolean isPreferredHorizontalTie( long candidateSecondary; long bestPrimary; long bestSecondary; - switch ((int) Math.floorMod(selectionPhase, 4)) { + switch (Math.floorMod(selectionPhase, 4)) { case 0 -> { candidatePrimary = candidateDx; candidateSecondary = candidateDz; @@ -468,7 +469,7 @@ private boolean matches(BlockPos drainPos, Fluid fluid, int bottomY, int topY, l && this.fluid.isSame(fluid) && this.bottomY == bottomY && this.topY == topY - && (this.exhaustedAt == Long.MIN_VALUE || gameTime - this.exhaustedAt < EXHAUSTED_SEARCH_TTL); + && (this.exhaustedAt == Long.MIN_VALUE || gameTime - this.exhaustedAt < DrainBlockEntity.EXHAUSTED_SEARCH_TTL); } private SearchResult advance(Level level) { @@ -481,7 +482,7 @@ private SearchResult advance(Level level) { ); this.layerSearch = new FillLayerSearch(this.drainPos, entry, this.fluid); } - SearchResult result = this.layerSearch.advance(level, level.getGameTime() / INTERVAL); + SearchResult result = this.layerSearch.advance(level, level.getGameTime() / DrainBlockEntity.INTERVAL); if (result.pending() || result.target() != null) { this.exhaustedAt = Long.MIN_VALUE; return result; @@ -503,7 +504,7 @@ private boolean acceptFilled(long target) { if (this.layerSearch == null) return true; this.layerSearch.acceptFilled(target); this.exhaustedAt = Long.MIN_VALUE; - return ++this.filledTargets >= FILL_SEARCH_REBUILD_INTERVAL; + return ++this.filledTargets >= DrainBlockEntity.FILL_SEARCH_REBUILD_INTERVAL; } } @@ -511,10 +512,10 @@ private static final class FillLayerSearch { private final long drainPos; private final long entry; private final Fluid fluid; - private final LongOpenHashSet discovered = new LongOpenHashSet(MAX_NODES); - private final Long2LongOpenHashMap predecessors = new Long2LongOpenHashMap(MAX_NODES); + private final LongOpenHashSet discovered = new LongOpenHashSet(DrainBlockEntity.MAX_NODES); + private final Long2LongOpenHashMap predecessors = new Long2LongOpenHashMap(DrainBlockEntity.MAX_NODES); private final LongOpenHashSet candidates = new LongOpenHashSet(); - private final LongArrayFIFOQueue queue = new LongArrayFIFOQueue(MAX_NODES); + private final LongArrayFIFOQueue queue = new LongArrayFIFOQueue(DrainBlockEntity.MAX_NODES); private FillLayerSearch(long drainPos, long entry, Fluid fluid) { this.drainPos = drainPos; @@ -528,16 +529,16 @@ private SearchResult advance(Level level, long selectionPhase) { BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); int processed = 0; while (true) { - while (!this.queue.isEmpty() && processed < MAX_NODES) { + while (!this.queue.isEmpty() && processed < DrainBlockEntity.MAX_NODES) { long current = this.queue.dequeueLong(); processed++; cursor.set(BlockPos.getX(current), BlockPos.getY(current), BlockPos.getZ(current)); - int fillType = classifyForFill(level, cursor, this.fluid); - if (fillType == FILL_TARGET) { + int fillType = DrainBlockEntity.classifyForFill(level, cursor, this.fluid); + if (fillType == DrainBlockEntity.FILL_TARGET) { this.candidates.add(current); - } else if (fillType == FILL_SOURCE) { + } else if (fillType == DrainBlockEntity.FILL_SOURCE) { for (Direction direction : Direction.Plane.HORIZONTAL) { - this.discover(level, offset(cursor, direction), current, cursor); + this.discover(level, DrainBlockEntity.offset(cursor, direction), current, cursor); cursor.set(BlockPos.getX(current), BlockPos.getY(current), BlockPos.getZ(current)); } this.discover( @@ -561,12 +562,12 @@ private SearchResult advance(Level level, long selectionPhase) { while (iterator.hasNext()) { long candidate = iterator.nextLong(); cursor.set(BlockPos.getX(candidate), BlockPos.getY(candidate), BlockPos.getZ(candidate)); - int fillType = classifyForFill(level, cursor, this.fluid); - if (fillType == FILL_BLOCKED) { + int fillType = DrainBlockEntity.classifyForFill(level, cursor, this.fluid); + if (fillType == DrainBlockEntity.FILL_BLOCKED) { iterator.remove(); continue; } - if (fillType == FILL_SOURCE) { + if (fillType == DrainBlockEntity.FILL_SOURCE) { iterator.remove(); this.queue.enqueue(candidate); discoveredSource = true; @@ -581,7 +582,7 @@ private SearchResult advance(Level level, long selectionPhase) { || y == bestY && (dist < bestDist || dist == bestDist - && isPreferredHorizontalTie(dx, dz, bestDx, bestDz, selectionPhase))) { + && DrainBlockEntity.isPreferredHorizontalTie(dx, dz, bestDx, bestDz, selectionPhase))) { best = candidate; bestY = y; bestDist = dist; @@ -591,7 +592,7 @@ && isPreferredHorizontalTie(dx, dz, bestDx, bestDz, selectionPhase))) { } } if (discoveredSource) { - if (processed >= MAX_NODES) return SearchResult.PENDING; + if (processed >= DrainBlockEntity.MAX_NODES) return SearchResult.PENDING; continue; } return found ? SearchResult.found(best) : SearchResult.EXHAUSTED; @@ -602,10 +603,10 @@ private void discover(Level level, long pos, long predecessor, BlockPos.MutableB if (!this.discovered.add(pos)) return; this.predecessors.put(pos, predecessor); cursor.set(BlockPos.getX(pos), BlockPos.getY(pos), BlockPos.getZ(pos)); - int fillType = classifyForFill(level, cursor, this.fluid); - if (fillType == FILL_SOURCE) { + int fillType = DrainBlockEntity.classifyForFill(level, cursor, this.fluid); + if (fillType == DrainBlockEntity.FILL_SOURCE) { this.queue.enqueue(pos); - } else if (fillType == FILL_TARGET) { + } else if (fillType == DrainBlockEntity.FILL_TARGET) { this.candidates.add(pos); } } @@ -618,7 +619,7 @@ private boolean isTargetStillReachable(Level level, long target) { BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); cursor.set(BlockPos.getX(target), BlockPos.getY(target), BlockPos.getZ(target)); if (!this.discovered.contains(target) - || classifyForFill(level, cursor, this.fluid) != FILL_TARGET) { + || DrainBlockEntity.classifyForFill(level, cursor, this.fluid) != DrainBlockEntity.FILL_TARGET) { return false; } @@ -628,7 +629,7 @@ private boolean isTargetStillReachable(Level level, long target) { if (!this.predecessors.containsKey(current)) return false; current = this.predecessors.get(current); cursor.set(BlockPos.getX(current), BlockPos.getY(current), BlockPos.getZ(current)); - if (classifyForFill(level, cursor, this.fluid) != FILL_SOURCE) return false; + if (DrainBlockEntity.classifyForFill(level, cursor, this.fluid) != DrainBlockEntity.FILL_SOURCE) return false; } return current == this.entry; } @@ -670,7 +671,7 @@ private boolean matches(BlockPos drainPos, Fluid fluid, int bottomY, int topY, l && this.fluid.isSame(fluid) && this.bottomY == bottomY && this.topY == topY - && (this.exhaustedAt == Long.MIN_VALUE || gameTime - this.exhaustedAt < EXHAUSTED_SEARCH_TTL); + && (this.exhaustedAt == Long.MIN_VALUE || gameTime - this.exhaustedAt < DrainBlockEntity.EXHAUSTED_SEARCH_TTL); } private SearchResult advance(Level level) { @@ -707,8 +708,8 @@ private static final class DrainLayerSearch { private final long drainPos; private final Fluid fluid; private final long selectionPhase; - private final LongOpenHashSet discovered = new LongOpenHashSet(MAX_NODES); - private final LongArrayFIFOQueue queue = new LongArrayFIFOQueue(MAX_NODES); + private final LongOpenHashSet discovered = new LongOpenHashSet(DrainBlockEntity.MAX_NODES); + private final LongArrayFIFOQueue queue = new LongArrayFIFOQueue(DrainBlockEntity.MAX_NODES); private long best; private int bestY = Integer.MIN_VALUE; private long bestDist = Long.MIN_VALUE; @@ -735,7 +736,7 @@ private SearchResult advance(Level level) { BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); BlockPos.MutableBlockPos neighborCursor = new BlockPos.MutableBlockPos(); int processed = 0; - while (!this.queue.isEmpty() && processed < MAX_NODES) { + while (!this.queue.isEmpty() && processed < DrainBlockEntity.MAX_NODES) { long current = this.queue.dequeueLong(); processed++; cursor.set(BlockPos.getX(current), BlockPos.getY(current), BlockPos.getZ(current)); @@ -747,7 +748,7 @@ private SearchResult advance(Level level) { this.considerFlowing(current, cursor); } for (Direction direction : Direction.Plane.HORIZONTAL) { - this.discoverFluid(level, offset(cursor, direction), neighborCursor); + this.discoverFluid(level, DrainBlockEntity.offset(cursor, direction), neighborCursor); } this.discoverFluid( level, @@ -775,7 +776,7 @@ private void considerSource( BlockPos sourcePos, BlockPos.MutableBlockPos neighborCursor ) { - int neighbors = countSourceNeighbors(level, sourcePos, this.fluid, neighborCursor); + int neighbors = DrainBlockEntity.countSourceNeighbors(level, sourcePos, this.fluid, neighborCursor); long dx = (long) sourcePos.getX() - BlockPos.getX(this.drainPos); long dz = (long) sourcePos.getZ() - BlockPos.getZ(this.drainPos); long dist = dx * dx + dz * dz; @@ -785,7 +786,7 @@ private void considerSource( || neighbors == this.bestNeighbors && (dist > this.bestDist || dist == this.bestDist - && (isPreferredHorizontalTie( + && (DrainBlockEntity.isPreferredHorizontalTie( dx, dz, this.bestDx, @@ -811,7 +812,7 @@ private void considerFlowing(long flowing, BlockPos flowingPos) { if (!this.foundFlowing || dist > this.bestFlowingDist || dist == this.bestFlowingDist - && (isPreferredHorizontalTie( + && (DrainBlockEntity.isPreferredHorizontalTie( dx, dz, this.bestFlowingDx, diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PipeBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PipeBlockEntity.java index adbb197060..9653a8f112 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PipeBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PipeBlockEntity.java @@ -64,7 +64,7 @@ public Packet getUpdatePacket() { * Per-tick 排液逻辑。 */ public static void tick(Level level, BlockPos pos, BlockState state) { - int endCount = getEndCount(state); + int endCount = PipeBlockEntity.getEndCount(state); if (endCount <= 0) return; boolean isStraight = state.getBlock() instanceof PipeStraightBlock; if (endCount == 2) { @@ -72,14 +72,14 @@ public static void tick(Level level, BlockPos pos, BlockState state) { Direction.Axis axis = state.getValue(PipeStraightBlock.AXIS); Direction posDir = PipeBlock.getDirectionFromAxis(axis, Direction.AxisDirection.POSITIVE); Direction negDir = PipeBlock.getDirectionFromAxis(axis, Direction.AxisDirection.NEGATIVE); - tickEndCount2(level, pos, posDir, negDir); - tickEndCount2(level, pos, negDir, posDir); + PipeBlockEntity.tickEndCount2(level, pos, posDir, negDir); + PipeBlockEntity.tickEndCount2(level, pos, negDir, posDir); } else { PipeBlock.CornerEnded cornerEnded = state.getValue(PipeCornerBlock.CORNER_ENDED); Direction firstDir = cornerEnded.getFirstDirection(); Direction secondDir = cornerEnded.getSecondDirection(); - tickEndCount2(level, pos, firstDir, secondDir); - tickEndCount2(level, pos, secondDir, firstDir); + PipeBlockEntity.tickEndCount2(level, pos, firstDir, secondDir); + PipeBlockEntity.tickEndCount2(level, pos, secondDir, firstDir); } return; } @@ -114,7 +114,7 @@ private static void tickEndCount2(Level level, BlockPos pos, Direction posDir, D if (level.getBlockState(sourceNeighbor).getBlock() instanceof PumpBlock) return; BlockPos targetNeighbor = pos.relative(negDir); if (level.getBlockState(targetNeighbor).getBlock() instanceof PumpBlock) { - PipeEnd pumpEnd = getPipeEnd(level, targetNeighbor, negDir.getOpposite()); + PipeEnd pumpEnd = AbstractPipeBlockEntity.getPipeEnd(level, targetNeighbor, negDir.getOpposite()); if (pumpEnd != null) { targetCurPos = pumpEnd.pos(); targetCurDir = pumpEnd.direction(); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PumpBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PumpBlockEntity.java index ab706d3855..45b79215e0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PumpBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/fluid/PumpBlockEntity.java @@ -42,17 +42,17 @@ public static PumpBlockEntity create(BlockEntityType type, Bloc @Override public int getInputPower() { - return getBlockState().getValue(PumpBlock.POWERED) ? 0 : PUMP_POWER; + return this.getBlockState().getValue(PumpBlock.POWERED) ? 0 : PumpBlockEntity.PUMP_POWER; } @Override public @Nullable Level getCurrentLevel() { - return getLevel(); + return this.getLevel(); } @Override public BlockPos getPos() { - return getBlockPos(); + return this.getBlockPos(); } public boolean canPump() { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/heatable/HeatableBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/heatable/HeatableBlockEntity.java index d353bd5de8..f1dfe3bf9a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/heatable/HeatableBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/heatable/HeatableBlockEntity.java @@ -43,7 +43,7 @@ public void addDuration(int second) { } public void addDurationInTick(int tick) { - this.setDuration(Math.clamp(this.duration + tick, -1, MAX_DURATION)); + this.setDuration(Math.clamp(this.duration + tick, -1, HeatableBlockEntity.MAX_DURATION)); } public void setDuration(int duration) { @@ -62,9 +62,9 @@ public static int getDuration(@CallableParam(clazz = HeatableBlockEntity.class, } public int getSignal() { - if (this.duration == MAX_DURATION) return 15; + if (this.duration == HeatableBlockEntity.MAX_DURATION) return 15; if (this.duration == 0) return 0; - return (int) Math.ceil((double) this.duration / MAX_DURATION * 14); + return (int) Math.ceil((double) this.duration / HeatableBlockEntity.MAX_DURATION * 14); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/entity/megastructure/IMegastructureHandler.java b/src/main/java/dev/dubhe/anvilcraft/block/entity/megastructure/IMegastructureHandler.java index a12624db6a..ca2704e433 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/entity/megastructure/IMegastructureHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/entity/megastructure/IMegastructureHandler.java @@ -50,7 +50,7 @@ default void gridTick(CelestialForgingAnvilBlockEntity be) { } default LaserRequirement getLaserRequirement() { - return NO_LASER_REQUIREMENT; + return IMegastructureHandler.NO_LASER_REQUIREMENT; } /** 所有相连激光接口需要满足的激光等级和类型。 */ diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/ControlValveBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/ControlValveBlock.java index 30bcf38753..0e2fd1dbea 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/ControlValveBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/ControlValveBlock.java @@ -11,6 +11,7 @@ import dev.dubhe.anvilcraft.network.ControlValveInitPacket; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; @@ -24,6 +25,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -31,6 +33,7 @@ import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.redstone.Orientation; import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import net.neoforged.neoforge.network.PacketDistributor; @@ -45,30 +48,31 @@ */ public class ControlValveBlock extends BetterBaseEntityBlock implements IHammerRemovable, IMoveableEntityBlock { - public static final MapCodec CODEC = simpleCodec(ControlValveBlock::new); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(ControlValveBlock::new); public static final EnumProperty AXIS = BlockStateProperties.AXIS; /** * 红石锁定:任意侧收到红石信号则锁定,流速视为 0 且 GUI 中不可调。 */ public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - private static final VoxelShape SHAPE_X = box(0, 3, 3, 16, 13, 13); - private static final VoxelShape SHAPE_Y = box(3, 0, 3, 13, 16, 13); - private static final VoxelShape SHAPE_Z = box(3, 3, 0, 13, 13, 16); + private static final VoxelShape SHAPE_X = Block.box(0, 3, 3, 16, 13, 13); + private static final VoxelShape SHAPE_Y = Block.box(3, 0, 3, 13, 16, 13); + private static final VoxelShape SHAPE_Z = Block.box(3, 3, 0, 13, 13, 16); public ControlValveBlock(Properties properties) { super(properties); - registerDefaultState(stateDefinition.any().setValue(AXIS, Direction.Axis.Y).setValue(POWERED, false)); + this.registerDefaultState( + this.stateDefinition.any().setValue(ControlValveBlock.AXIS, Direction.Axis.Y).setValue(ControlValveBlock.POWERED, false)); } @Override protected MapCodec codec() { - return CODEC; + return ControlValveBlock.CODEC; } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(AXIS, POWERED); + builder.add(ControlValveBlock.AXIS, ControlValveBlock.POWERED); } @Override @@ -78,10 +82,10 @@ public RenderShape getRenderShape(BlockState state) { @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { - return switch (state.getValue(AXIS)) { - case X -> SHAPE_X; - case Y -> SHAPE_Y; - default -> SHAPE_Z; + return switch (state.getValue(ControlValveBlock.AXIS)) { + case X -> ControlValveBlock.SHAPE_X; + case Y -> ControlValveBlock.SHAPE_Y; + default -> ControlValveBlock.SHAPE_Z; }; } @@ -92,9 +96,9 @@ public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, Co @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { boolean powered = context.getLevel().hasNeighborSignal(context.getClickedPos()); - return defaultBlockState() - .setValue(AXIS, context.getClickedFace().getAxis()) - .setValue(POWERED, powered); + return this.defaultBlockState() + .setValue(ControlValveBlock.AXIS, context.getClickedFace().getAxis()) + .setValue(ControlValveBlock.POWERED, powered); } /** @@ -104,7 +108,7 @@ public static boolean isConnectableFace(BlockState state, Direction faceToNeighb if (!(state.getBlock() instanceof ControlValveBlock)) { return false; } - return faceToNeighbor.getAxis() == state.getValue(AXIS); + return faceToNeighbor.getAxis() == state.getValue(ControlValveBlock.AXIS); } /** @@ -112,7 +116,7 @@ public static boolean isConnectableFace(BlockState state, Direction faceToNeighb * (法线与玩家视线最反向者)。 */ private static Direction computeHandwheelFacing(Direction.Axis axis, LivingEntity placer) { - net.minecraft.world.phys.Vec3 look = placer.getLookAngle(); + Vec3 look = placer.getLookAngle(); Direction best = null; double bestDot = Double.NEGATIVE_INFINITY; for (Direction dir : Direction.values()) { @@ -140,10 +144,10 @@ public void setPlacedBy(Level level, BlockPos pos, BlockState state, @Nullable L } // 记录手轮朝向:取玩家视线反方向中、垂直于阀门轴的那一面(即玩家面对的、能看到手轮的一面) if (placer != null && level.getBlockEntity(pos) instanceof ControlValveBlockEntity be) { - be.setFacing(computeHandwheelFacing(state.getValue(AXIS), placer)); + be.setFacing(ControlValveBlock.computeHandwheelFacing(state.getValue(ControlValveBlock.AXIS), placer)); } for (Direction dir : Direction.values()) { - if (!isConnectableFace(state, dir)) { + if (!ControlValveBlock.isConnectableFace(state, dir)) { continue; } BlockPos neighborPos = pos.relative(dir); @@ -207,8 +211,8 @@ protected void neighborChanged( } FluidNetworkManager.INSTANCE.addAdjacentContainers(level, pos); boolean hasSignal = level.hasNeighborSignal(pos); - if (hasSignal != state.getValue(POWERED)) { - level.setBlock(pos, state.setValue(POWERED, hasSignal), Block.UPDATE_CLIENTS); + if (hasSignal != state.getValue(ControlValveBlock.POWERED)) { + level.setBlock(pos, state.setValue(ControlValveBlock.POWERED, hasSignal), Block.UPDATE_CLIENTS); // 锁定状态变化会改变有效流速 → 使网络缓存失效 FluidNetworkManager.INSTANCE.markDirty(level); } @@ -232,7 +236,7 @@ public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldS @Override protected void affectNeighborsAfterRemoval( BlockState state, - net.minecraft.server.level.ServerLevel level, + ServerLevel level, BlockPos pos, boolean movedByPiston ) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/DrainBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/DrainBlock.java index 980828d80d..6ca5a47235 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/DrainBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/DrainBlock.java @@ -12,6 +12,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import org.jspecify.annotations.Nullable; @@ -20,7 +21,7 @@ * 向下把内部流体铺放到世界、或从上方抽取流体入内部。 */ public class DrainBlock extends BetterBaseEntityBlock implements IHammerRemovable { - public static final MapCodec CODEC = simpleCodec(DrainBlock::new); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(DrainBlock::new); public DrainBlock(Properties properties) { super(properties); @@ -28,7 +29,7 @@ public DrainBlock(Properties properties) { @Override protected MapCodec codec() { - return CODEC; + return DrainBlock.CODEC; } @Override @@ -46,6 +47,6 @@ protected RenderShape getRenderShape(BlockState state) { Level level, BlockState state, BlockEntityType type ) { if (level.isClientSide()) return null; - return createTickerHelper(type, ModBlockEntities.DRAIN.get(), DrainBlockEntity::tick); + return BaseEntityBlock.createTickerHelper(type, ModBlockEntities.DRAIN.get(), DrainBlockEntity::tick); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/ExpFluidBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/ExpFluidBlock.java index 63c8e82b75..feecd966c4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/ExpFluidBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/ExpFluidBlock.java @@ -29,7 +29,7 @@ protected void entityInside( if (level.isClientSide()) return; if (!level.getFluidState(pos).isSource()) return; if (entity instanceof Player player) { - player.giveExperiencePoints(XP_POINTS); + player.giveExperiencePoints(ExpFluidBlock.XP_POINTS); level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/MeltGemFluid.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/MeltGemFluid.java index 1ad855e20f..30652ed394 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/MeltGemFluid.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/MeltGemFluid.java @@ -9,6 +9,7 @@ import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; +import net.minecraft.world.level.material.FlowingFluid; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; import net.neoforged.neoforge.event.EventHooks; @@ -43,23 +44,23 @@ protected void spreadTo(LevelAccessor level, BlockPos pos, BlockState blockState @Override protected boolean canBeReplacedWith(FluidState state, BlockGetter level, BlockPos pos, Fluid fluidIn, Direction direction) { - if (fluidIn.is(FluidTags.LAVA)) return true; + if (fluidIn.defaultFluidState().is(FluidTags.LAVA)) return true; return super.canBeReplacedWith(state, level, pos, fluidIn, direction); } public static class Flowing extends MeltGemFluid { public Flowing(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(LEVEL, 7)); + this.registerDefaultState(this.getStateDefinition().any().setValue(FlowingFluid.LEVEL, 7)); } protected void createFluidStateDefinition(StateDefinition.Builder builder) { super.createFluidStateDefinition(builder); - builder.add(LEVEL); + builder.add(FlowingFluid.LEVEL); } public int getAmount(FluidState state) { - return state.getValue(LEVEL); + return state.getValue(FlowingFluid.LEVEL); } public boolean isSource(FluidState state) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeBlock.java index da73e0be63..d8c58fa101 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeBlock.java @@ -124,27 +124,27 @@ public abstract class PipeBlock extends Block /** * 管道中心体碰撞箱(对应 pipe_straight / pipe_side_corner 模型 [4,4,4]→[12,12,12]) */ - static final VoxelShape PIPE_CENTER = box(4, 4, 4, 12, 12, 12); + static final VoxelShape PIPE_CENTER = Block.box(4, 4, 4, 12, 12, 12); /** * 节点中心体碰撞箱(对应 pipe_node 模型 [3,3,3]→[13,13,13]) */ - static final VoxelShape NODE_CENTER = box(3, 3, 3, 13, 13, 13); + static final VoxelShape NODE_CENTER = Block.box(3, 3, 3, 13, 13, 13); /** 六个方向;{@code values()} 每次调用都会克隆数组,热路径统一复用这份共享副本。 */ static final Direction[] DIRECTIONS = Direction.values(); /** 按方向预建的无端头臂,避免每次取形状都重新构造。 */ - private static final VoxelShape[] NO_END_ARMS = new VoxelShape[DIRECTIONS.length]; + private static final VoxelShape[] NO_END_ARMS = new VoxelShape[PipeBlock.DIRECTIONS.length]; /** 按方向预建的有端头臂。 */ - private static final VoxelShape[] END_ARMS = new VoxelShape[DIRECTIONS.length]; + private static final VoxelShape[] END_ARMS = new VoxelShape[PipeBlock.DIRECTIONS.length]; /** 直管 / 弯管形状缓存:两端方向 x 两个端头开关。 */ - private static final AtomicReferenceArray TWO_ARM_SHAPES = - new AtomicReferenceArray<>(DIRECTIONS.length * DIRECTIONS.length * 4); + private static final AtomicReferenceArray<@Nullable VoxelShape> TWO_ARM_SHAPES = + new AtomicReferenceArray<>(PipeBlock.DIRECTIONS.length * PipeBlock.DIRECTIONS.length * 4); static { - for (Direction dir : DIRECTIONS) { - NO_END_ARMS[dir.ordinal()] = buildNoEnd(dir); - END_ARMS[dir.ordinal()] = buildEnd(dir); + for (Direction dir : PipeBlock.DIRECTIONS) { + PipeBlock.NO_END_ARMS[dir.ordinal()] = PipeBlock.buildNoEnd(dir); + PipeBlock.END_ARMS[dir.ordinal()] = PipeBlock.buildEnd(dir); } } @@ -155,7 +155,11 @@ public abstract class PipeBlock extends Block * 每次都会回到 {@code getShape};在那里现算 {@link Shapes#or} 会让管道附近的每个实体 * 每 tick 都产生大量形状合并与分配。相同状态算出的形状等价,先写入者胜出即可。

*/ - static VoxelShape cachedShape(AtomicReferenceArray cache, int key, Supplier builder) { + static VoxelShape cachedShape( + AtomicReferenceArray<@Nullable VoxelShape> cache, + int key, + Supplier builder + ) { VoxelShape cached = cache.get(key); if (cached != null) { return cached; @@ -170,7 +174,7 @@ static VoxelShape cachedShape(AtomicReferenceArray cache, int key, S * 从中心体表面延伸到方块边界,4 px 深,8×8 截面。 */ static VoxelShape makeNoEnd(Direction dir) { - return NO_END_ARMS[dir.ordinal()]; + return PipeBlock.NO_END_ARMS[dir.ordinal()]; } /** @@ -178,49 +182,50 @@ static VoxelShape makeNoEnd(Direction dir) { * ring(2 px 深,8×8 截面)+ cap(2 px 深,10×10 截面,与面齐平)。 */ static VoxelShape makeEnd(Direction dir) { - return END_ARMS[dir.ordinal()]; + return PipeBlock.END_ARMS[dir.ordinal()]; } private static VoxelShape buildNoEnd(Direction dir) { return switch (dir) { - case DOWN -> box(4, 0, 4, 12, 4, 12); - case UP -> box(4, 12, 4, 12, 16, 12); - case NORTH -> box(4, 4, 0, 12, 12, 4); - case SOUTH -> box(4, 4, 12, 12, 12, 16); - case WEST -> box(0, 4, 4, 4, 12, 12); - case EAST -> box(12, 4, 4, 16, 12, 12); + case DOWN -> Block.box(4, 0, 4, 12, 4, 12); + case UP -> Block.box(4, 12, 4, 12, 16, 12); + case NORTH -> Block.box(4, 4, 0, 12, 12, 4); + case SOUTH -> Block.box(4, 4, 12, 12, 12, 16); + case WEST -> Block.box(0, 4, 4, 4, 12, 12); + case EAST -> Block.box(12, 4, 4, 16, 12, 12); }; } private static VoxelShape buildEnd(Direction dir) { // ring:内层,紧贴中心体,8×8 截面 VoxelShape ring = switch (dir) { - case DOWN -> box(4, 2, 4, 12, 4, 12); - case UP -> box(4, 12, 4, 12, 14, 12); - case NORTH -> box(4, 4, 2, 12, 12, 4); - case SOUTH -> box(4, 4, 12, 12, 12, 14); - case WEST -> box(2, 4, 4, 4, 12, 12); - case EAST -> box(12, 4, 4, 14, 12, 12); + case DOWN -> Block.box(4, 2, 4, 12, 4, 12); + case UP -> Block.box(4, 12, 4, 12, 14, 12); + case NORTH -> Block.box(4, 4, 2, 12, 12, 4); + case SOUTH -> Block.box(4, 4, 12, 12, 12, 14); + case WEST -> Block.box(2, 4, 4, 4, 12, 12); + case EAST -> Block.box(12, 4, 4, 14, 12, 12); }; VoxelShape cap = switch (dir) { - case DOWN -> box(3, 0, 3, 13, 2, 13); - case UP -> box(3, 14, 3, 13, 16, 13); - case NORTH -> box(3, 3, 0, 13, 13, 2); - case SOUTH -> box(3, 3, 14, 13, 13, 16); - case WEST -> box(0, 3, 3, 2, 13, 13); - case EAST -> box(14, 3, 3, 16, 13, 13); + case DOWN -> Block.box(3, 0, 3, 13, 2, 13); + case UP -> Block.box(3, 14, 3, 13, 16, 13); + case NORTH -> Block.box(3, 3, 0, 13, 13, 2); + case SOUTH -> Block.box(3, 3, 14, 13, 13, 16); + case WEST -> Block.box(0, 3, 3, 2, 13, 13); + case EAST -> Block.box(14, 3, 3, 16, 13, 13); }; return Shapes.or(ring, cap); } public PipeBlock(Properties properties) { super(properties); - this.registerDefaultState(this.getStateDefinition().any().setValue(WATERLOGGED, false).setValue(HAS_CHECK_VALVE, false)); + this.registerDefaultState( + this.getStateDefinition().any().setValue(PipeBlock.WATERLOGGED, false).setValue(PipeBlock.HAS_CHECK_VALVE, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(WATERLOGGED, HAS_CHECK_VALVE); + builder.add(PipeBlock.WATERLOGGED, PipeBlock.HAS_CHECK_VALVE); } /** @@ -235,12 +240,12 @@ public static Direction getDirectionFromAxis(Direction.Axis axis, Direction.Axis */ public static EnumProperty getPropertyForDirection(Direction direction) { return switch (direction) { - case DOWN -> DOWN; - case UP -> UP; - case NORTH -> NORTH; - case SOUTH -> SOUTH; - case WEST -> WEST; - case EAST -> EAST; + case DOWN -> PipeBlock.DOWN; + case UP -> PipeBlock.UP; + case NORTH -> PipeBlock.NORTH; + case SOUTH -> PipeBlock.SOUTH; + case WEST -> PipeBlock.WEST; + case EAST -> PipeBlock.EAST; }; } @@ -250,9 +255,9 @@ public static EnumProperty getPropertyForDirection(Direction direction public static boolean hasConnectionToward(BlockState state, Direction toward) { Block block = state.getBlock(); return switch (block) { - case PipeStraightBlock ignored -> toward.getAxis() == state.getValue(AXIS); - case PipeCornerBlock ignored -> state.getValue(CORNER_ENDED).containsDirection(toward); - case PipeNodeBlock ignored -> state.getValue(getPropertyForDirection(toward)) == NodePipe.PIPE; + case PipeStraightBlock ignored -> toward.getAxis() == state.getValue(PipeBlock.AXIS); + case PipeCornerBlock ignored -> state.getValue(PipeBlock.CORNER_ENDED).containsDirection(toward); + case PipeNodeBlock ignored -> state.getValue(PipeBlock.getPropertyForDirection(toward)) == NodePipe.PIPE; default -> false; }; } @@ -263,7 +268,7 @@ public static boolean hasConnectionToward(BlockState state, Direction toward) { public static boolean isNeighborPipeToward(Level level, BlockPos pos, Direction dir) { BlockPos neighborPos = pos.relative(dir); BlockState neighborState = level.getBlockState(neighborPos); - return neighborState.getBlock() instanceof PipeBlock && hasConnectionToward(neighborState, dir.getOpposite()); + return neighborState.getBlock() instanceof PipeBlock && PipeBlock.hasConnectionToward(neighborState, dir.getOpposite()); } /** @@ -301,10 +306,10 @@ public static boolean isFluidHandlerOrConnectablePump(Level level, BlockPos pos, * 检查指定方向的邻居是否被"占用"(有管道对准、是流体处理器、或连接面正对本方块的泵)。 */ public static boolean isNeighborOccupied(Level level, BlockPos pos, Direction dir) { - if (isNeighborPipeToward(level, pos, dir)) { + if (PipeBlock.isNeighborPipeToward(level, pos, dir)) { return true; } - return isFluidHandlerOrConnectablePump(level, pos.relative(dir), dir.getOpposite()); + return PipeBlock.isFluidHandlerOrConnectablePump(level, pos.relative(dir), dir.getOpposite()); } @Override @@ -325,9 +330,9 @@ protected void changePipeState( ) { BlockState newState = state; if (neighborDir == startDir) { - newState = newState.setValue(HAS_END_START, !neighborIsPipeToward); + newState = newState.setValue(PipeBlock.HAS_END_START, !neighborIsPipeToward); } else { - newState = newState.setValue(HAS_END_END, !neighborIsPipeToward); + newState = newState.setValue(PipeBlock.HAS_END_END, !neighborIsPipeToward); } if (!newState.equals(state)) { @@ -346,7 +351,7 @@ protected BlockState updateShape( BlockState neighborState, RandomSource random ) { - if (state.getValue(WATERLOGGED)) { + if (state.getValue(PipeBlock.WATERLOGGED)) { ticks.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); } return super.updateShape(state, level, ticks, pos, direction, neighborPos, neighborState, random); @@ -354,14 +359,14 @@ protected BlockState updateShape( @Override public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); + return state.getValue(PipeBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override protected List getDrops(BlockState state, LootParams.Builder params) { List drops = new ArrayList<>(super.getDrops(state, params)); BlockEntity blockEntity = params.getOptionalParameter(LootContextParams.BLOCK_ENTITY); - if (state.getValue(HAS_CHECK_VALVE) + if (state.getValue(PipeBlock.HAS_CHECK_VALVE) && blockEntity instanceof AbstractPipeBlockEntity checkValve && !checkValve.isEmpty() ) { @@ -374,15 +379,16 @@ protected List getDrops(BlockState state, LootParams.Builder params) * 构建直管/弯管的碰撞箱:中心体 + 两端按端头状态拼接 arm。 */ public VoxelShape getShape(BlockState state, Direction startDir, Direction endDir) { - boolean endStart = state.getValue(HAS_END_START); - boolean endEnd = state.getValue(HAS_END_END); + boolean endStart = state.getValue(PipeBlock.HAS_END_START); + boolean endEnd = state.getValue(PipeBlock.HAS_END_END); // 两端方向 x 两个端头开关唯一决定形状,直管与弯管共用同一张缓存表。 - int key = ((startDir.ordinal() * DIRECTIONS.length + endDir.ordinal()) * 2 + (endStart ? 1 : 0)) * 2 + int key = ((startDir.ordinal() * PipeBlock.DIRECTIONS.length + endDir.ordinal()) * 2 + (endStart ? 1 : 0)) * 2 + (endEnd ? 1 : 0); - return cachedShape(TWO_ARM_SHAPES, key, () -> Shapes.or( - PIPE_CENTER, - endStart ? makeEnd(startDir) : makeNoEnd(startDir), - endEnd ? makeEnd(endDir) : makeNoEnd(endDir) + return PipeBlock.cachedShape( + PipeBlock.TWO_ARM_SHAPES, key, () -> Shapes.or( + PipeBlock.PIPE_CENTER, + endStart ? PipeBlock.makeEnd(startDir) : PipeBlock.makeNoEnd(startDir), + endEnd ? PipeBlock.makeEnd(endDir) : PipeBlock.makeNoEnd(endDir) )); } @@ -399,7 +405,6 @@ public static AbstractPipeBlockEntity getCheckValve(Level level, BlockPos pos) { /** * 根据射线命中检测结果确定玩家点击了哪个臂方向。 */ - @Nullable public static Direction getArmDirection(BlockPos pos, BlockHitResult hitResult) { Vec3 loc = hitResult.getLocation(); double bx = loc.x - pos.getX(); @@ -427,7 +432,7 @@ public static Direction getArmDirection(BlockPos pos, BlockHitResult hitResult) * 判断该管道在给定方向是否有臂(连接)。子类需覆盖以实现具体逻辑。 */ protected boolean hasArmToward(BlockState state, Direction dir) { - return hasConnectionToward(state, dir); + return PipeBlock.hasConnectionToward(state, dir); } /** @@ -435,9 +440,9 @@ protected boolean hasArmToward(BlockState state, Direction dir) { */ protected boolean addCheckValve(Level level, BlockPos pos, BlockState state, Direction face, Direction flowOut) { if (level.isClientSide()) return false; - BlockState newState = state.setValue(HAS_CHECK_VALVE, true); - setBlockPreservingValve(level, pos, newState); - AbstractPipeBlockEntity valve = getCheckValve(level, pos); + BlockState newState = state.setValue(PipeBlock.HAS_CHECK_VALVE, true); + PipeBlock.setBlockPreservingValve(level, pos, newState); + AbstractPipeBlockEntity valve = PipeBlock.getCheckValve(level, pos); if (valve != null) { valve.setValve(face, flowOut); valve.sendUpdate(); @@ -451,13 +456,13 @@ protected boolean addCheckValve(Level level, BlockPos pos, BlockState state, Dir */ protected boolean removeCheckValve(Level level, BlockPos pos, BlockState state, Direction face) { if (level.isClientSide()) return false; - AbstractPipeBlockEntity valve = getCheckValve(level, pos); + AbstractPipeBlockEntity valve = PipeBlock.getCheckValve(level, pos); if (valve == null || !valve.hasValveOn(face)) return false; valve.removeValve(face); valve.sendUpdate(); if (valve.isEmpty()) { - BlockState newState = state.setValue(HAS_CHECK_VALVE, false); - setBlockPreservingValve(level, pos, newState); + BlockState newState = state.setValue(PipeBlock.HAS_CHECK_VALVE, false); + PipeBlock.setBlockPreservingValve(level, pos, newState); } FluidNetworkManager.INSTANCE.markDirty(level); return true; @@ -479,16 +484,16 @@ protected InteractionResult handleCheckValveInteraction( } if (level.isClientSide()) return InteractionResult.SUCCESS; - Direction face = getArmDirection(pos, hitResult); - if (face == null || !this.hasArmToward(state, face)) { + Direction face = PipeBlock.getArmDirection(pos, hitResult); + if (!this.hasArmToward(state, face)) { return InteractionResult.PASS; } // 已有止回阀 → 不重复安装 - AbstractPipeBlockEntity existing = getCheckValve(level, pos); + AbstractPipeBlockEntity existing = PipeBlock.getCheckValve(level, pos); if (existing != null && existing.hasValveOn(face)) { if (this.removeCheckValve(level, pos, state, face)) { - giveOrDrop(player, level, pos, new ItemStack(ModItems.CHECK_VALVE.get())); + PipeBlock.giveOrDrop(player, level, pos, new ItemStack(ModItems.CHECK_VALVE.get())); return InteractionResult.CONSUME; } return InteractionResult.PASS; @@ -511,16 +516,14 @@ protected InteractionResult handleCheckValveInteraction( protected InteractionResult detachCheckValve(BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult) { if (level.isClientSide()) return InteractionResult.SUCCESS; - Direction face = getArmDirection(pos, hitResult); - if (face == null) return InteractionResult.PASS; - - AbstractPipeBlockEntity valve = getCheckValve(level, pos); + Direction face = PipeBlock.getArmDirection(pos, hitResult); + AbstractPipeBlockEntity valve = PipeBlock.getCheckValve(level, pos); if (valve == null || !valve.hasValveOn(face)) { return InteractionResult.PASS; } if (this.removeCheckValve(level, pos, state, face)) { - giveOrDrop(player, level, pos, new ItemStack(ModItems.CHECK_VALVE.get())); + PipeBlock.giveOrDrop(player, level, pos, new ItemStack(ModItems.CHECK_VALVE.get())); return InteractionResult.CONSUME; } return InteractionResult.PASS; @@ -567,7 +570,7 @@ protected InteractionResult useItemOn( return this.handleCheckValveInteraction(stack, state, level, pos, player, hitResult); } // 扳手或锤子拆卸止回阀 - if ((stack.is(Tags.Items.TOOLS_WRENCH) || stack.is(ModItemTags.ANVIL_HAMMER)) && state.getValue(HAS_CHECK_VALVE)) { + if ((stack.is(Tags.Items.TOOLS_WRENCH) || stack.is(ModItemTags.ANVIL_HAMMER)) && state.getValue(PipeBlock.HAS_CHECK_VALVE)) { return this.detachCheckValve(state, level, pos, player, hitResult); } return super.useItemOn(stack, state, level, pos, player, hand, hitResult); @@ -577,9 +580,9 @@ protected InteractionResult useItemOn( protected InteractionResult useWithoutItem( BlockState state, Level level, BlockPos pos, Player player, BlockHitResult hitResult ) { - Direction face = getArmDirection(pos, hitResult); - if (face != null && this.hasArmToward(state, face)) { - AbstractPipeBlockEntity valve = getCheckValve(level, pos); + Direction face = PipeBlock.getArmDirection(pos, hitResult); + if (this.hasArmToward(state, face)) { + AbstractPipeBlockEntity valve = PipeBlock.getCheckValve(level, pos); if (valve != null && valve.hasValveOn(face)) { return this.detachCheckValve(state, level, pos, player, hitResult); } @@ -613,7 +616,7 @@ protected void neighborChanged( @Nullable Orientation orientation, boolean movedByPiston ) { - if (!level.isClientSide() && state.getValue(HAS_CHECK_VALVE)) { + if (!level.isClientSide() && state.getValue(PipeBlock.HAS_CHECK_VALVE)) { this.updateCheckValvePower(level, pos, state); } } @@ -622,7 +625,7 @@ protected void neighborChanged( * 根据红石信号更新止回阀的反向状态。 */ protected void updateCheckValvePower(Level level, BlockPos pos, BlockState state) { - AbstractPipeBlockEntity valve = getCheckValve(level, pos); + AbstractPipeBlockEntity valve = PipeBlock.getCheckValve(level, pos); if (valve == null) return; boolean powered = level.hasNeighborSignal(pos); if (valve.setPowered(powered)) { @@ -640,31 +643,31 @@ public static void setBlockPreservingValve(Level level, BlockPos pos, BlockState Map savedFlows = null; boolean savedPowered = false; - if (oldState.hasProperty(HAS_CHECK_VALVE) && oldState.getValue(HAS_CHECK_VALVE)) { - AbstractPipeBlockEntity oldValve = getCheckValve(level, pos); + if (oldState.hasProperty(PipeBlock.HAS_CHECK_VALVE) && oldState.getValue(PipeBlock.HAS_CHECK_VALVE)) { + AbstractPipeBlockEntity oldValve = PipeBlock.getCheckValve(level, pos); if (oldValve != null && !oldValve.isEmpty()) { Map oldFlows = oldValve.baseFlowCopy(); savedFlows = new EnumMap<>(Direction.class); for (Map.Entry entry : oldFlows.entrySet()) { - if (hasConnectionToward(newState, entry.getKey())) { + if (PipeBlock.hasConnectionToward(newState, entry.getKey())) { savedFlows.put(entry.getKey(), entry.getValue()); } else if (!level.isClientSide()) { Block.popResource(level, pos, new ItemStack(ModItems.CHECK_VALVE.get())); } } savedPowered = oldValve.isPowered(); - newState = newState.setValue(HAS_CHECK_VALVE, !savedFlows.isEmpty()); + newState = newState.setValue(PipeBlock.HAS_CHECK_VALVE, !savedFlows.isEmpty()); } else { - newState = newState.setValue(HAS_CHECK_VALVE, true); + newState = newState.setValue(PipeBlock.HAS_CHECK_VALVE, true); } } else { - newState = newState.setValue(HAS_CHECK_VALVE, false); + newState = newState.setValue(PipeBlock.HAS_CHECK_VALVE, false); } level.setBlockAndUpdate(pos, newState); if (savedFlows != null && !savedFlows.isEmpty()) { - AbstractPipeBlockEntity newValve = getCheckValve(level, pos); + AbstractPipeBlockEntity newValve = PipeBlock.getCheckValve(level, pos); if (newValve != null) { newValve.restore(savedFlows, savedPowered); if (!level.isClientSide()) { @@ -712,12 +715,12 @@ public boolean containsDirection(Direction direction) { } public static CornerEnded fromDirections(Direction a, Direction b) { - for (CornerEnded corner : values()) { + for (CornerEnded corner : CornerEnded.values()) { if ((corner.first == a && corner.second == b) || (corner.first == b && corner.second == a)) { return corner; } } - return UP_NORTH; + return CornerEnded.UP_NORTH; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeCornerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeCornerBlock.java index 981e7176ab..f7f6038795 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeCornerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeCornerBlock.java @@ -25,24 +25,24 @@ public PipeCornerBlock(Properties properties) { super(properties); this.registerDefaultState(this.getStateDefinition() .any() - .setValue(WATERLOGGED, false) - .setValue(HAS_CHECK_VALVE, false) - .setValue(CORNER_ENDED, CornerEnded.UP_NORTH) - .setValue(HAS_END_START, true) - .setValue(HAS_END_END, true)); + .setValue(PipeBlock.WATERLOGGED, false) + .setValue(PipeBlock.HAS_CHECK_VALVE, false) + .setValue(PipeBlock.CORNER_ENDED, CornerEnded.UP_NORTH) + .setValue(PipeBlock.HAS_END_START, true) + .setValue(PipeBlock.HAS_END_END, true)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(CORNER_ENDED); - builder.add(HAS_END_START); - builder.add(HAS_END_END); + builder.add(PipeBlock.CORNER_ENDED); + builder.add(PipeBlock.HAS_END_START); + builder.add(PipeBlock.HAS_END_END); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { - CornerEnded corner = state.getValue(CORNER_ENDED); + CornerEnded corner = state.getValue(PipeBlock.CORNER_ENDED); Direction startDir = corner.getFirstDirection(); Direction endDir = corner.getSecondDirection(); return this.getShape(state, startDir, endDir); @@ -70,7 +70,7 @@ protected void neighborChanged( ) { if (level.isClientSide()) return; this.updateCheckValvePower(level, pos, state); - CornerEnded corner = state.getValue(CORNER_ENDED); + CornerEnded corner = state.getValue(PipeBlock.CORNER_ENDED); // 非弯管方向(侧面)出现对准的管道或连接面正对的泵 → 升级为节点 for (Direction dir : Direction.values()) { @@ -80,16 +80,17 @@ protected void neighborChanged( BlockState neighborState = level.getBlockState(pos.relative(dir)); boolean sidePump = neighborState.getBlock() instanceof PumpBlock && PumpBlock.isConnectableFace(neighborState, dir.getOpposite()); - if (isNeighborPipeToward(level, pos, dir) || sidePump) { + if (PipeBlock.isNeighborPipeToward(level, pos, dir) || sidePump) { BlockState nodeState = ModBlocks.PIPE_NODE.get().defaultBlockState() - .setValue(WATERLOGGED, state.getValue(WATERLOGGED)); + .setValue(PipeBlock.WATERLOGGED, state.getValue(PipeBlock.WATERLOGGED)); for (Direction d : Direction.values()) { - nodeState = nodeState.setValue(getPropertyForDirection(d), + nodeState = nodeState.setValue( + PipeBlock.getPropertyForDirection(d), PipeNodeBlock.evaluateNeighbor(level, pos, d)); } BlockState simplified = PipeNodeBlock.trySimplify(nodeState); if (!simplified.equals(state)) { - setBlockPreservingValve(level, pos, simplified); + PipeBlock.setBlockPreservingValve(level, pos, simplified); } return; } @@ -99,10 +100,10 @@ protected void neighborChanged( Direction first = corner.getFirstDirection(); Direction second = corner.getSecondDirection(); BlockState newState = state - .setValue(HAS_END_START, !isNeighborPipeToward(level, pos, first)) - .setValue(HAS_END_END, !isNeighborPipeToward(level, pos, second)); + .setValue(PipeBlock.HAS_END_START, !PipeBlock.isNeighborPipeToward(level, pos, first)) + .setValue(PipeBlock.HAS_END_END, !PipeBlock.isNeighborPipeToward(level, pos, second)); if (!newState.equals(state)) { - setBlockPreservingValve(level, pos, newState); + PipeBlock.setBlockPreservingValve(level, pos, newState); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeStraightBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeStraightBlock.java index 5c76d6cdc5..3ddc03a23e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeStraightBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PipeStraightBlock.java @@ -27,34 +27,34 @@ public PipeStraightBlock(Properties properties) { super(properties); this.registerDefaultState(this.getStateDefinition() .any() - .setValue(WATERLOGGED, false) - .setValue(HAS_CHECK_VALVE, false) - .setValue(AXIS, Direction.Axis.X) - .setValue(HAS_END_START, true) - .setValue(HAS_END_END, true)); + .setValue(PipeBlock.WATERLOGGED, false) + .setValue(PipeBlock.HAS_CHECK_VALVE, false) + .setValue(PipeBlock.AXIS, Direction.Axis.X) + .setValue(PipeBlock.HAS_END_START, true) + .setValue(PipeBlock.HAS_END_END, true)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(AXIS); - builder.add(HAS_END_START); - builder.add(HAS_END_END); + builder.add(PipeBlock.AXIS); + builder.add(PipeBlock.HAS_END_START); + builder.add(PipeBlock.HAS_END_END); } @Override @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(AXIS, context.getClickedFace().getAxis()) - .setValue(WATERLOGGED, context.getLevel().getFluidState(context.getClickedPos()).getType() == Fluids.WATER); + .setValue(PipeBlock.AXIS, context.getClickedFace().getAxis()) + .setValue(PipeBlock.WATERLOGGED, context.getLevel().getFluidState(context.getClickedPos()).getType() == Fluids.WATER); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { - Direction.Axis axis = state.getValue(AXIS); - Direction startDir = getDirectionFromAxis(axis, Direction.AxisDirection.NEGATIVE); - Direction endDir = getDirectionFromAxis(axis, Direction.AxisDirection.POSITIVE); + Direction.Axis axis = state.getValue(PipeBlock.AXIS); + Direction startDir = PipeBlock.getDirectionFromAxis(axis, Direction.AxisDirection.NEGATIVE); + Direction endDir = PipeBlock.getDirectionFromAxis(axis, Direction.AxisDirection.POSITIVE); return this.getShape(state, startDir, endDir); } @@ -77,7 +77,7 @@ protected void neighborChanged( ) { if (level.isClientSide()) return; this.updateCheckValvePower(level, pos, state); - Direction.Axis axis = state.getValue(AXIS); + Direction.Axis axis = state.getValue(PipeBlock.AXIS); // 侧面(非轴向)出现对准的管道或连接面正对的泵 → 升级为节点 for (Direction dir : Direction.values()) { @@ -87,29 +87,30 @@ protected void neighborChanged( BlockState neighborState = level.getBlockState(pos.relative(dir)); boolean sidePump = neighborState.getBlock() instanceof PumpBlock && PumpBlock.isConnectableFace(neighborState, dir.getOpposite()); - if (isNeighborPipeToward(level, pos, dir) || sidePump) { + if (PipeBlock.isNeighborPipeToward(level, pos, dir) || sidePump) { BlockState nodeState = ModBlocks.PIPE_NODE.get().defaultBlockState() - .setValue(WATERLOGGED, state.getValue(WATERLOGGED)); + .setValue(PipeBlock.WATERLOGGED, state.getValue(PipeBlock.WATERLOGGED)); for (Direction d : Direction.values()) { - nodeState = nodeState.setValue(getPropertyForDirection(d), + nodeState = nodeState.setValue( + PipeBlock.getPropertyForDirection(d), PipeNodeBlock.evaluateNeighbor(level, pos, d)); } BlockState simplified = PipeNodeBlock.trySimplify(nodeState); if (!simplified.equals(state)) { - setBlockPreservingValve(level, pos, simplified); + PipeBlock.setBlockPreservingValve(level, pos, simplified); } return; } } // 无侧面连接 → 保持直管,仅按轴端邻居刷新端头(断连只封头,不变节点) - Direction startDir = getDirectionFromAxis(axis, Direction.AxisDirection.NEGATIVE); - Direction endDir = getDirectionFromAxis(axis, Direction.AxisDirection.POSITIVE); + Direction startDir = PipeBlock.getDirectionFromAxis(axis, Direction.AxisDirection.NEGATIVE); + Direction endDir = PipeBlock.getDirectionFromAxis(axis, Direction.AxisDirection.POSITIVE); BlockState newState = state - .setValue(HAS_END_START, !isNeighborPipeToward(level, pos, startDir)) - .setValue(HAS_END_END, !isNeighborPipeToward(level, pos, endDir)); + .setValue(PipeBlock.HAS_END_START, !PipeBlock.isNeighborPipeToward(level, pos, startDir)) + .setValue(PipeBlock.HAS_END_END, !PipeBlock.isNeighborPipeToward(level, pos, endDir)); if (!newState.equals(state)) { - setBlockPreservingValve(level, pos, newState); + PipeBlock.setBlockPreservingValve(level, pos, newState); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PumpBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PumpBlock.java index 2c11140ae3..93b2ff524e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/fluid/PumpBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/fluid/PumpBlock.java @@ -26,6 +26,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -45,21 +46,21 @@ public class PumpBlock extends BetterBaseEntityBlock implements IHammerRemovable public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public static final BooleanProperty OVERLOAD = IPowerComponent.OVERLOAD; - private static final VoxelShape SHAPE_Z = box(3, 3, 0, 13, 13, 16); - private static final VoxelShape SHAPE_X = box(0, 3, 3, 16, 13, 13); - private static final VoxelShape SHAPE_Y = box(3, 0, 3, 13, 16, 13); + private static final VoxelShape SHAPE_Z = Block.box(3, 3, 0, 13, 13, 16); + private static final VoxelShape SHAPE_X = Block.box(0, 3, 3, 16, 13, 13); + private static final VoxelShape SHAPE_Y = Block.box(3, 0, 3, 13, 16, 13); public PumpBlock(Properties properties) { super(properties); - registerDefaultState(stateDefinition.any() - .setValue(ORIENTATION, Orientation.NORTH_UP) - .setValue(POWERED, false) - .setValue(OVERLOAD, false)); + this.registerDefaultState(this.stateDefinition.any() + .setValue(PumpBlock.ORIENTATION, Orientation.NORTH_UP) + .setValue(PumpBlock.POWERED, false) + .setValue(PumpBlock.OVERLOAD, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(ORIENTATION, POWERED, OVERLOAD); + builder.add(PumpBlock.ORIENTATION, PumpBlock.POWERED, PumpBlock.OVERLOAD); } @Override @@ -69,16 +70,16 @@ public RenderShape getRenderShape(BlockState state) { @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { - return switch (state.getValue(ORIENTATION).getDirection().getAxis()) { - case X -> SHAPE_X; - case Y -> SHAPE_Y; - default -> SHAPE_Z; + return switch (state.getValue(PumpBlock.ORIENTATION).getDirection().getAxis()) { + case X -> PumpBlock.SHAPE_X; + case Y -> PumpBlock.SHAPE_Y; + default -> PumpBlock.SHAPE_Z; }; } @Override protected MapCodec codec() { - return simpleCodec(PumpBlock::new); + return BlockBehaviour.simpleCodec(PumpBlock::new); } @Override @@ -113,9 +114,9 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { default -> Orientation.NORTH_UP; }; }; - return defaultBlockState() - .setValue(ORIENTATION, orientation) - .setValue(POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); + return this.defaultBlockState() + .setValue(PumpBlock.ORIENTATION, orientation) + .setValue(PumpBlock.POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); } /** @@ -132,7 +133,7 @@ public static boolean isConnectableFace(BlockState pumpState, Direction faceToNe if (!(pumpState.getBlock() instanceof PumpBlock)) { return false; } - return faceToNeighbor.getAxis() == pumpState.getValue(ORIENTATION).getDirection().getAxis(); + return faceToNeighbor.getAxis() == pumpState.getValue(PumpBlock.ORIENTATION).getDirection().getAxis(); } @Override @@ -141,7 +142,7 @@ public void setPlacedBy(Level level, BlockPos pos, BlockState state, @Nullable L if (level.isClientSide()) return; for (Direction dir : Direction.values()) { // 仅泵的连接面(输入/输出端)才可能形成连接 - if (!isConnectableFace(state, dir)) { + if (!PumpBlock.isConnectableFace(state, dir)) { continue; } BlockPos neighborPos = pos.relative(dir); @@ -181,8 +182,8 @@ protected void neighborChanged( if (level.isClientSide()) return; FluidNetworkManager.INSTANCE.addAdjacentContainers(level, pos); boolean hasSignal = level.hasNeighborSignal(pos); - if (hasSignal != state.getValue(POWERED)) { - level.setBlock(pos, state.setValue(POWERED, hasSignal), 2); + if (hasSignal != state.getValue(PumpBlock.POWERED)) { + level.setBlock(pos, state.setValue(PumpBlock.POWERED, hasSignal), 2); } } @@ -204,7 +205,7 @@ protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState state = level.getBlockState(blockPos); - level.setBlockAndUpdate(blockPos, state.setValue(ORIENTATION, state.getValue(ORIENTATION).opposite())); + level.setBlockAndUpdate(blockPos, state.setValue(PumpBlock.ORIENTATION, state.getValue(PumpBlock.ORIENTATION).opposite())); if (!level.isClientSide()) { FluidNetworkManager.INSTANCE.markDirty(level); } @@ -213,12 +214,12 @@ public boolean change(Player player, BlockPos blockPos, Level level, ItemStack a @Override public @Nullable Property getChangeableProperty(BlockState state) { - return ORIENTATION; + return PumpBlock.ORIENTATION; } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(ORIENTATION, state.getValue(ORIENTATION).rotate(rotation)); + return state.setValue(PumpBlock.ORIENTATION, state.getValue(PumpBlock.ORIENTATION).rotate(rotation)); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/heatable/RedhotBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/heatable/RedhotBlock.java index f54290e717..0fa028605f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/heatable/RedhotBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/heatable/RedhotBlock.java @@ -14,6 +14,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.BucketPickup; import net.minecraft.world.level.block.LiquidBlock; @@ -113,7 +114,7 @@ private boolean removeWaterBreadthFirstSearch(Level level, BlockPos pos) { } BlockEntity blockentity = state.hasBlockEntity() ? level.getBlockEntity(posx) : null; - dropResources(state, level, posx, blockentity); + Block.dropResources(state, level, posx, blockentity); level.setBlock(posx, Blocks.AIR.defaultBlockState(), 3); return BlockPos.TraversalNodeStatus.ACCEPT; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/laser/LargeLaserBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/laser/LargeLaserBlock.java index 02576956ba..e29f9e8754 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/laser/LargeLaserBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/laser/LargeLaserBlock.java @@ -55,35 +55,42 @@ public class LargeLaserBlock extends FlexibleMultiPartBlock> COLLISION_SHAPES = makeCollisionShapes(); + private static final Map> COLLISION_SHAPES = LargeLaserBlock.makeCollisionShapes(); public LargeLaserBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition - .any() - .setValue(HALF, DirectionCube3x3PartHalf.BOTTOM_CENTER) - .setValue(FACING, Direction.DOWN) - .setValue(OVERLOAD, true) - .setValue(SWITCH, IPowerComponent.Switch.ON) + .any() + .setValue(LargeLaserBlock.HALF, DirectionCube3x3PartHalf.BOTTOM_CENTER) + .setValue(LargeLaserBlock.FACING, Direction.DOWN) + .setValue(LargeLaserBlock.OVERLOAD, true) + .setValue(LargeLaserBlock.SWITCH, IPowerComponent.Switch.ON) ); } private static Map> makeCollisionShapes() { Map> shapes = new EnumMap<>(Direction.class); - shapes.put(Direction.DOWN, makePartShapes(DOWN_COLLISION_SHAPE)); - shapes.put(Direction.UP, makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 180, DOWN_COLLISION_SHAPE))); - shapes.put(Direction.SOUTH, makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 90, DOWN_COLLISION_SHAPE))); - shapes.put(Direction.NORTH, makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 270, DOWN_COLLISION_SHAPE))); - shapes.put(Direction.WEST, makePartShapes(ShapeUtil.rotate( - Direction.Axis.Y, - 270, - ShapeUtil.rotate(Direction.Axis.X, 90, DOWN_COLLISION_SHAPE) - ))); - shapes.put(Direction.EAST, makePartShapes(ShapeUtil.rotate( - Direction.Axis.Y, - 270, - ShapeUtil.rotate(Direction.Axis.X, 270, DOWN_COLLISION_SHAPE) - ))); + shapes.put(Direction.DOWN, LargeLaserBlock.makePartShapes(LargeLaserBlock.DOWN_COLLISION_SHAPE)); + shapes.put( + Direction.UP, LargeLaserBlock.makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 180, LargeLaserBlock.DOWN_COLLISION_SHAPE))); + shapes.put( + Direction.SOUTH, LargeLaserBlock.makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 90, LargeLaserBlock.DOWN_COLLISION_SHAPE))); + shapes.put( + Direction.NORTH, LargeLaserBlock.makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 270, LargeLaserBlock.DOWN_COLLISION_SHAPE))); + shapes.put( + Direction.WEST, LargeLaserBlock.makePartShapes(ShapeUtil.rotate( + Direction.Axis.Y, + 270, + ShapeUtil.rotate(Direction.Axis.X, 90, LargeLaserBlock.DOWN_COLLISION_SHAPE) + )) + ); + shapes.put( + Direction.EAST, LargeLaserBlock.makePartShapes(ShapeUtil.rotate( + Direction.Axis.Y, + 270, + ShapeUtil.rotate(Direction.Axis.X, 270, LargeLaserBlock.DOWN_COLLISION_SHAPE) + )) + ); return shapes; } @@ -92,7 +99,7 @@ private static Map makePartShapes(VoxelSha for (DirectionCube3x3PartHalf part : DirectionCube3x3PartHalf.values()) { ArrayList partBoxes = new ArrayList<>(); for (AABB box : shape.toAabbs()) { - AABB clipped = clipToPart(scale16(box), part); + AABB clipped = LargeLaserBlock.clipToPart(LargeLaserBlock.scale16(box), part); if (clipped != null) partBoxes.add(clipped); } shapes.put( @@ -133,7 +140,7 @@ private static AABB clipToPart(AABB box, DirectionCube3x3PartHalf part) { @Override public Property getPart() { - return HALF; + return LargeLaserBlock.HALF; } @Override @@ -143,7 +150,7 @@ public DirectionCube3x3PartHalf[] getParts() { @Override public EnumProperty getAdditionalProperty() { - return FACING; + return LargeLaserBlock.FACING; } @Override @@ -161,7 +168,7 @@ public EnumProperty getAdditionalProperty() { public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() .setValue( - FACING, + LargeLaserBlock.FACING, context.getPlayer() != null && context.getPlayer().isShiftKeyDown() ? context.getNearestLookingDirection().getOpposite() : context.getNearestLookingDirection() @@ -180,11 +187,11 @@ protected void neighborChanged( boolean isSignal = Arrays.stream(this.getParts()).anyMatch((half) -> level.hasNeighborSignal( pos.subtract(state.getValue(this.getPart()).getOffset()).offset(half.getOffset()) )); - if (isSignal && state.getValue(SWITCH) == IPowerComponent.Switch.ON) { - this.updateState(level, pos, SWITCH, IPowerComponent.Switch.OFF, 3); - } else if (!isSignal && state.getValue(SWITCH) == IPowerComponent.Switch.OFF) { - this.updateState(level, pos, SWITCH, IPowerComponent.Switch.ON, 3); - if (level.getBlockEntity(getMainPartPos(pos, state)) instanceof IPowerConsumer powerConsumer) { + if (isSignal && state.getValue(LargeLaserBlock.SWITCH) == IPowerComponent.Switch.ON) { + this.updateState(level, pos, LargeLaserBlock.SWITCH, IPowerComponent.Switch.OFF, 3); + } else if (!isSignal && state.getValue(LargeLaserBlock.SWITCH) == IPowerComponent.Switch.OFF) { + this.updateState(level, pos, LargeLaserBlock.SWITCH, IPowerComponent.Switch.ON, 3); + if (level.getBlockEntity(this.getMainPartPos(pos, state)) instanceof IPowerConsumer powerConsumer) { if (powerConsumer.getGrid() == null) { return; } @@ -195,19 +202,19 @@ protected void neighborChanged( @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF, FACING, OVERLOAD, SWITCH); + builder.add(LargeLaserBlock.HALF, LargeLaserBlock.FACING, LargeLaserBlock.OVERLOAD, LargeLaserBlock.SWITCH); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)) - .setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(LargeLaserBlock.HALF, state.getValue(LargeLaserBlock.HALF).rotate(rotation)) + .setValue(LargeLaserBlock.FACING, rotation.rotate(state.getValue(LargeLaserBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)) - .setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(LargeLaserBlock.HALF, state.getValue(LargeLaserBlock.HALF).mirror(mirror)) + .setValue(LargeLaserBlock.FACING, mirror.mirror(state.getValue(LargeLaserBlock.FACING))); } @Override @@ -222,7 +229,7 @@ protected boolean propagatesSkylightDown(BlockState state) { @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return COLLISION_SHAPES.get(state.getValue(FACING)).get(state.getValue(HALF)); + return LargeLaserBlock.COLLISION_SHAPES.get(state.getValue(LargeLaserBlock.FACING)).get(state.getValue(LargeLaserBlock.HALF)); } @Override @@ -232,13 +239,13 @@ protected VoxelShape getCollisionShape(BlockState state, BlockGetter level, Bloc @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { - this.change(blockPos, level, (state) -> state.cycle(FACING)); + this.change(blockPos, level, (state) -> state.cycle(LargeLaserBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return LargeLaserBlock.FACING; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/laser/LaserReceiverBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/laser/LaserReceiverBlock.java index 3504bf4d83..d60a1af2c0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/laser/LaserReceiverBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/laser/LaserReceiverBlock.java @@ -12,13 +12,14 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -82,32 +83,32 @@ public class LaserReceiverBlock extends BaseLaserBlock implements IHammerRemovab @Override protected MapCodec codec() { - return simpleCodec(LaserReceiverBlock::new); + return BlockBehaviour.simpleCodec(LaserReceiverBlock::new); } public LaserReceiverBlock(Properties properties) { super(properties); this.registerDefaultState(this.getStateDefinition().any() - .setValue(FACING, Direction.UP) - .setValue(ACTIVE, false)); + .setValue(LaserReceiverBlock.FACING, Direction.UP) + .setValue(LaserReceiverBlock.ACTIVE, false)); } @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case UP -> UP_SHAPE; - case DOWN -> DOWN_SHAPE; - case NORTH -> NORTH_SHAPE; - case SOUTH -> SOUTH_SHAPE; - case EAST -> EAST_SHAPE; - case WEST -> WEST_SHAPE; + return switch (state.getValue(LaserReceiverBlock.FACING)) { + case UP -> LaserReceiverBlock.UP_SHAPE; + case DOWN -> LaserReceiverBlock.DOWN_SHAPE; + case NORTH -> LaserReceiverBlock.NORTH_SHAPE; + case SOUTH -> LaserReceiverBlock.SOUTH_SHAPE; + case EAST -> LaserReceiverBlock.EAST_SHAPE; + case WEST -> LaserReceiverBlock.WEST_SHAPE; }; } @Override public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { Direction clickedFace = context.getClickedFace(); - return this.defaultBlockState().setValue(FACING, clickedFace); + return this.defaultBlockState().setValue(LaserReceiverBlock.FACING, clickedFace); } @Override @@ -117,7 +118,7 @@ protected boolean isSignalSource(BlockState state) { @Override protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { - if (state.getValue(FACING).getOpposite() != direction) { + if (state.getValue(LaserReceiverBlock.FACING).getOpposite() != direction) { if (level.getBlockEntity(pos) instanceof LaserReceiverBlockEntity laserReceiverBlockEntity) { int laserLevel = laserReceiverBlockEntity.getLaserLevel(); return Math.min(laserLevel, 15); @@ -128,12 +129,7 @@ protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direc @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ACTIVE); - } - - @Override - protected RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; + builder.add(LaserReceiverBlock.FACING, LaserReceiverBlock.ACTIVE); } @Override @@ -144,28 +140,29 @@ protected RenderShape getRenderShape(BlockState state) { @Override public @Nullable BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) return null; - return createTickerHelper(type, ModBlockEntities.LASER_RECEIVER.get(), (level1, pos, state1, entity) -> entity.tick(level)); + return BaseEntityBlock.createTickerHelper( + type, ModBlockEntities.LASER_RECEIVER.get(), (level1, pos, state1, entity) -> entity.tick(level)); } @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState state = level.getBlockState(blockPos); - level.setBlockAndUpdate(blockPos, state.cycle(FACING)); + level.setBlockAndUpdate(blockPos, state.cycle(LaserReceiverBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return LaserReceiverBlock.FACING; } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(LaserReceiverBlock.FACING, rotation.rotate(state.getValue(LaserReceiverBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(LaserReceiverBlock.FACING, mirror.mirror(state.getValue(LaserReceiverBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/laser/LensBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/laser/LensBlock.java index 43c133ec2c..7e1285eb8d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/laser/LensBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/laser/LensBlock.java @@ -25,6 +25,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -50,13 +51,13 @@ public LensBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(AXIS, Direction.Axis.Y) - .setValue(TYPE, LensType.NONE)); + .setValue(LensBlock.AXIS, Direction.Axis.Y) + .setValue(LensBlock.TYPE, LensType.NONE)); } @Override protected MapCodec codec() { - return simpleCodec(LensBlock::new); + return BlockBehaviour.simpleCodec(LensBlock::new); } @Nullable @@ -76,7 +77,7 @@ public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type ) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.LENS.get(), (lvl, pos, st, be) -> be.tick(lvl) @@ -85,23 +86,23 @@ public BlockEntityTicker getTicker( @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(AXIS).add(TYPE); + builder.add(LensBlock.AXIS).add(LensBlock.TYPE); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(AXIS, context.getNearestLookingDirection().getAxis()) - .setValue(TYPE, LensType.NONE); + .setValue(LensBlock.AXIS, context.getNearestLookingDirection().getAxis()) + .setValue(LensBlock.TYPE, LensType.NONE); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { return switch (rotation) { - case COUNTERCLOCKWISE_90, CLOCKWISE_90 -> switch (state.getValue(AXIS)) { - case X -> state.setValue(AXIS, Direction.Axis.Z); - case Z -> state.setValue(AXIS, Direction.Axis.X); + case COUNTERCLOCKWISE_90, CLOCKWISE_90 -> switch (state.getValue(LensBlock.AXIS)) { + case X -> state.setValue(LensBlock.AXIS, Direction.Axis.Z); + case Z -> state.setValue(LensBlock.AXIS, Direction.Axis.X); default -> state; }; default -> state; @@ -115,10 +116,10 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return switch (state.getValue(AXIS)) { - case X -> SHAPE_X; - case Z -> SHAPE_Z; - default -> SHAPE_Y; + return switch (state.getValue(LensBlock.AXIS)) { + case X -> LensBlock.SHAPE_X; + case Z -> LensBlock.SHAPE_Z; + default -> LensBlock.SHAPE_Y; }; } @@ -143,19 +144,19 @@ protected InteractionResult useItemOn( // Anvil hammer cycles the lens axis: X → Y → Z → X if (stack.is(ModItemTags.ANVIL_HAMMER)) { - Direction.Axis currentAxis = state.getValue(AXIS); + Direction.Axis currentAxis = state.getValue(LensBlock.AXIS); Direction.Axis newAxis = switch (currentAxis) { case X -> Direction.Axis.Y; case Y -> Direction.Axis.Z; case Z -> Direction.Axis.X; }; - level.setBlockAndUpdate(pos, state.setValue(AXIS, newAxis)); - resetLensLaserState(level, pos); + level.setBlockAndUpdate(pos, state.setValue(LensBlock.AXIS, newAxis)); + LensBlock.resetLensLaserState(level, pos); return InteractionResult.SUCCESS; } - LensType currentType = state.getValue(TYPE); - LensType newType = getGlassType(stack); + LensType currentType = state.getValue(LensBlock.TYPE); + LensType newType = LensBlock.getGlassType(stack); if (newType == null || newType == currentType) { return InteractionResult.TRY_WITH_EMPTY_HAND; @@ -166,17 +167,17 @@ protected InteractionResult useItemOn( // Return old glass if applicable if (currentType != LensType.NONE) { - ItemStack returnedGlass = getGlassItem(currentType); + ItemStack returnedGlass = LensBlock.getGlassItem(currentType); if (!player.getInventory().add(returnedGlass)) { player.drop(returnedGlass, false); } } // Update block state - level.setBlockAndUpdate(pos, state.setValue(TYPE, newType)); + level.setBlockAndUpdate(pos, state.setValue(LensBlock.TYPE, newType)); // Reset laser state so upstream/downstream re-scan with new glass type - resetLensLaserState(level, pos); + LensBlock.resetLensLaserState(level, pos); return InteractionResult.SUCCESS; } @@ -193,21 +194,21 @@ protected InteractionResult useWithoutItem( return InteractionResult.SUCCESS; } - LensType currentType = state.getValue(TYPE); + LensType currentType = state.getValue(LensBlock.TYPE); if (currentType == LensType.NONE) { return InteractionResult.PASS; } // Remove glass and return it to the player - ItemStack returnedGlass = getGlassItem(currentType); + ItemStack returnedGlass = LensBlock.getGlassItem(currentType); if (!player.getInventory().add(returnedGlass)) { player.drop(returnedGlass, false); } - level.setBlockAndUpdate(pos, state.setValue(TYPE, LensType.NONE)); + level.setBlockAndUpdate(pos, state.setValue(LensBlock.TYPE, LensType.NONE)); // Reset laser state since the lens is now pass-through - resetLensLaserState(level, pos); + LensBlock.resetLensLaserState(level, pos); return InteractionResult.SUCCESS; } @@ -221,9 +222,9 @@ protected void spawnAfterBreak( boolean dropExperience ) { super.spawnAfterBreak(state, level, pos, tool, dropExperience); - LensType type = state.getValue(TYPE); + LensType type = state.getValue(LensBlock.TYPE); if (type != LensType.NONE) { - popResource(level, pos, getGlassItem(type)); + Block.popResource(level, pos, LensBlock.getGlassItem(type)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/laser/PropelPistonBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/laser/PropelPistonBlock.java index ef1b8e1980..f3d9c307dc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/laser/PropelPistonBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/laser/PropelPistonBlock.java @@ -35,6 +35,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.piston.MovingPistonBlock; import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BooleanProperty; @@ -55,20 +56,20 @@ public class PropelPistonBlock extends DirectionalBlock implements IMoveableEnti @Override protected MapCodec codec() { - return simpleCodec(PropelPistonBlock::new); + return BlockBehaviour.simpleCodec(PropelPistonBlock::new); } public PropelPistonBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any() - .setValue(EXHAUSTED, true) - .setValue(FACING, Direction.NORTH) - .setValue(MOVING, false)); + .setValue(PropelPistonBlock.EXHAUSTED, true) + .setValue(DirectionalBlock.FACING, Direction.NORTH) + .setValue(PropelPistonBlock.MOVING, false)); } @Override public @Nullable PushReaction getPistonPushReaction(BlockState state) { - if (state.getValue(MOVING)) { + if (state.getValue(PropelPistonBlock.MOVING)) { return PushReaction.BLOCK; } return PushReaction.NORMAL; @@ -79,9 +80,9 @@ public PropelPistonBlock(Properties properties) { Direction clickedFace = context.getNearestLookingDirection().getOpposite(); Player player = context.getPlayer(); if (player != null && player.isShiftKeyDown()) { - return this.defaultBlockState().setValue(FACING, clickedFace.getOpposite()); + return this.defaultBlockState().setValue(DirectionalBlock.FACING, clickedFace.getOpposite()); } - return this.defaultBlockState().setValue(FACING, clickedFace); + return this.defaultBlockState().setValue(DirectionalBlock.FACING, clickedFace); } @Override @@ -92,7 +93,7 @@ protected InteractionResult useWithoutItem( Player player, BlockHitResult hitResult ) { - level.setBlockAndUpdate(pos, state.cycle(MOVING)); + level.setBlockAndUpdate(pos, state.cycle(PropelPistonBlock.MOVING)); return InteractionResult.SUCCESS; } @@ -124,7 +125,7 @@ protected InteractionResult useItemOn( } } } - level.setBlockAndUpdate(pos, state.cycle(MOVING)); + level.setBlockAndUpdate(pos, state.cycle(PropelPistonBlock.MOVING)); return super.useItemOn(stack, state, level, pos, player, hand, hitResult); } @@ -138,26 +139,26 @@ protected void neighborChanged( boolean movedByPiston ) { if (level.hasNeighborSignal(pos)) { - if (!state.getValue(MOVING)) { - level.setBlockAndUpdate(pos, state.setValue(MOVING, true)); + if (!state.getValue(PropelPistonBlock.MOVING)) { + level.setBlockAndUpdate(pos, state.setValue(PropelPistonBlock.MOVING, true)); } } } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(EXHAUSTED, FACING, MOVING); + builder.add(PropelPistonBlock.EXHAUSTED, DirectionalBlock.FACING, PropelPistonBlock.MOVING); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(DirectionalBlock.FACING, rotation.rotate(state.getValue(DirectionalBlock.FACING))); } @SuppressWarnings("deprecation") @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.rotate(mirror.getRotation(state.getValue(FACING))); + return state.rotate(mirror.getRotation(state.getValue(DirectionalBlock.FACING))); } @Override @@ -174,7 +175,7 @@ protected BlockState mirror(BlockState state, Mirror mirror) { if (level.isClientSide()) { return null; } - return createTickerHelper( + return PropelPistonBlock.createTickerHelper( type, ModBlockEntities.PROPEL_PISTON.get(), (level1, blockPos, blockState, blockEntity) -> @@ -209,11 +210,11 @@ protected boolean triggerEvent(BlockState state, Level level, BlockPos pos, int Direction direction = state.getValue(PropelPistonBlock.FACING); if (id == 0) { if (EventHooks.onPistonMovePre(level, pos, direction, true)) { - level.setBlockAndUpdate(pos, state.setValue(MOVING, false)); + level.setBlockAndUpdate(pos, state.setValue(PropelPistonBlock.MOVING, false)); return false; } if (!this.moveBlocks(level, pos, direction)) { - level.setBlockAndUpdate(pos, state.setValue(MOVING, false)); + level.setBlockAndUpdate(pos, state.setValue(PropelPistonBlock.MOVING, false)); return false; } level.playSound( @@ -233,13 +234,13 @@ protected boolean triggerEvent(BlockState state, Level level, BlockPos pos, int @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState state = level.getBlockState(blockPos); - level.setBlockAndUpdate(blockPos, state.cycle(FACING)); + level.setBlockAndUpdate(blockPos, state.cycle(DirectionalBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return DirectionalBlock.FACING; } private boolean moveBlocks(Level level, BlockPos pos, Direction facing) { @@ -270,7 +271,7 @@ private boolean moveBlocks(Level level, BlockPos pos, Direction facing) { BlockPos blockPos2 = list2.get(j); BlockState blockState1 = level.getBlockState(blockPos2); BlockEntity blockentity = blockState1.hasBlockEntity() ? level.getBlockEntity(blockPos2) : null; - dropResources(blockState1, level, blockPos2, blockentity); + Block.dropResources(blockState1, level, blockPos2, blockentity); blockState1.onDestroyedByPushReaction(level, blockPos2, facing, level.getFluidState(blockPos2)); if (!blockState1.is(BlockTags.FIRE)) { level.addDestroyBlockEffect(blockPos2, blockState1); @@ -284,7 +285,7 @@ private boolean moveBlocks(Level level, BlockPos pos, Direction facing) { final BlockState blockState5 = level.getBlockState(blockPos3); blockPos3 = blockPos3.relative(facing); map.remove(blockPos3); - BlockState blockState8 = Blocks.MOVING_PISTON.defaultBlockState().setValue(FACING, facing); + BlockState blockState8 = Blocks.MOVING_PISTON.defaultBlockState().setValue(DirectionalBlock.FACING, facing); BlockEntity blockEntity = null; if (!level.isClientSide()) { BlockPos relative = blockPos3.relative(facing.getOpposite()); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyLaserBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyLaserBlock.java index 4811b57e98..bdba83e6fd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyLaserBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyLaserBlock.java @@ -21,6 +21,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BooleanProperty; @@ -53,19 +54,19 @@ public RubyLaserBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(FACING, Direction.DOWN) - .setValue(OVERLOAD, true) - .setValue(SWITCH, Switch.ON)); + .setValue(RubyLaserBlock.FACING, Direction.DOWN) + .setValue(RubyLaserBlock.OVERLOAD, true) + .setValue(RubyLaserBlock.SWITCH, Switch.ON)); } @Override protected MapCodec codec() { - return simpleCodec(RubyLaserBlock::new); + return BlockBehaviour.simpleCodec(RubyLaserBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING).add(OVERLOAD).add(SWITCH); + builder.add(RubyLaserBlock.FACING).add(RubyLaserBlock.OVERLOAD).add(RubyLaserBlock.SWITCH); } @Nullable @@ -80,13 +81,13 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case UP -> UP_MODEL; - case DOWN -> DOWN_MODEL; - case NORTH -> NORTH_MODEL; - case SOUTH -> SOUTH_MODEL; - case WEST -> WEST_MODEL; - case EAST -> EAST_MODEL; + return switch (state.getValue(RubyLaserBlock.FACING)) { + case UP -> RubyLaserBlock.UP_MODEL; + case DOWN -> RubyLaserBlock.DOWN_MODEL; + case NORTH -> RubyLaserBlock.NORTH_MODEL; + case SOUTH -> RubyLaserBlock.SOUTH_MODEL; + case WEST -> RubyLaserBlock.WEST_MODEL; + case EAST -> RubyLaserBlock.EAST_MODEL; }; } @@ -102,7 +103,7 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return this.defaultBlockState().setValue(FACING, context.getNearestLookingDirection()); + return this.defaultBlockState().setValue(RubyLaserBlock.FACING, context.getNearestLookingDirection()); } @Nullable @@ -110,17 +111,17 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.RUBY_LASER.get(), (level1, pos, state1, entity) -> entity.tick(level1)); } @Override protected BlockState rotate(BlockState state, Rotation rot) { - return state.setValue(FACING, rot.rotate(state.getValue(FACING))); + return state.setValue(RubyLaserBlock.FACING, rot.rotate(state.getValue(RubyLaserBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(RubyLaserBlock.FACING, mirror.mirror(state.getValue(RubyLaserBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyPrismBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyPrismBlock.java index 51ec1bb48f..f38f425279 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyPrismBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/laser/RubyPrismBlock.java @@ -21,6 +21,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.EnumProperty; @@ -48,17 +49,17 @@ public class RubyPrismBlock extends BaseLaserBlock implements IHammerRemovable, /// 方块状态注册 public RubyPrismBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(FACING, Direction.DOWN)); + this.registerDefaultState(this.stateDefinition.any().setValue(RubyPrismBlock.FACING, Direction.DOWN)); } @Override protected MapCodec codec() { - return simpleCodec(RubyPrismBlock::new); + return BlockBehaviour.simpleCodec(RubyPrismBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING); + builder.add(RubyPrismBlock.FACING); } @Nullable @@ -73,13 +74,13 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case UP -> UP_MODEL; - case DOWN -> DOWN_MODEL; - case NORTH -> NORTH_MODEL; - case SOUTH -> SOUTH_MODEL; - case WEST -> WEST_MODEL; - case EAST -> EAST_MODEL; + return switch (state.getValue(RubyPrismBlock.FACING)) { + case UP -> RubyPrismBlock.UP_MODEL; + case DOWN -> RubyPrismBlock.DOWN_MODEL; + case NORTH -> RubyPrismBlock.NORTH_MODEL; + case SOUTH -> RubyPrismBlock.SOUTH_MODEL; + case WEST -> RubyPrismBlock.WEST_MODEL; + case EAST -> RubyPrismBlock.EAST_MODEL; }; } @@ -95,7 +96,7 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return this.defaultBlockState().setValue(FACING, context.getNearestLookingDirection()); + return this.defaultBlockState().setValue(RubyPrismBlock.FACING, context.getNearestLookingDirection()); } @Nullable @@ -103,18 +104,18 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.RUBY_PRISM.get(), (level1, pos, state1, entity) -> entity.tick(level1)); } @Override protected BlockState rotate(BlockState state, Rotation rot) { - return state.setValue(FACING, rot.rotate(state.getValue(FACING))); + return state.setValue(RubyPrismBlock.FACING, rot.rotate(state.getValue(RubyPrismBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(RubyPrismBlock.FACING, mirror.mirror(state.getValue(RubyPrismBlock.FACING))); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/ChuteBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/ChuteBlock.java index 1302d59e73..a70b2f9b97 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/ChuteBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/ChuteBlock.java @@ -39,6 +39,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -98,8 +99,8 @@ public ChuteBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition.any() - .setValue(FACING, Direction.DOWN) - .setValue(ENABLED, Boolean.TRUE) + .setValue(ChuteBlock.FACING, Direction.DOWN) + .setValue(ChuteBlock.ENABLED, Boolean.TRUE) ); } @@ -121,8 +122,8 @@ public static boolean isChuteBlock(T obj) { @Nullable public static Direction getFacing(BlockState state) { - if (state.hasProperty(FACING)) { - return state.getValue(FACING); + if (state.hasProperty(ChuteBlock.FACING)) { + return state.getValue(ChuteBlock.FACING); } if (state.hasProperty(MagneticChuteBlock.FACING)) { return state.getValue(MagneticChuteBlock.FACING); @@ -132,7 +133,7 @@ public static Direction getFacing(BlockState state) { @Override protected MapCodec codec() { - return simpleCodec(ChuteBlock::new); + return BlockBehaviour.simpleCodec(ChuteBlock::new); } @Override @@ -157,14 +158,14 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { @Override public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilHammer) { BlockState oldState = level.getBlockState(pos); - Direction oldFacing = oldState.getValue(FACING); + Direction oldFacing = oldState.getValue(ChuteBlock.FACING); Direction newFacing = switch (oldFacing) { case WEST -> Direction.DOWN; case DOWN -> Direction.NORTH; default -> oldFacing.getClockWise(); }; BlockState facingState = level.getBlockState(pos.relative(newFacing)); - if (isChuteBlock(facingState) && getFacing(facingState) == newFacing.getOpposite()) { + if (ChuteBlock.isChuteBlock(facingState) && ChuteBlock.getFacing(facingState) == newFacing.getOpposite()) { level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); level.levelEvent(2001, pos, Block.getId(oldState)); Block.dropResources(oldState, level, pos); @@ -176,22 +177,22 @@ public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilH @Override public Property getChangeableProperty(BlockState blockState) { - return FACING; + return ChuteBlock.FACING; } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(ChuteBlock.FACING, rotation.rotate(state.getValue(ChuteBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(ChuteBlock.FACING))); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ENABLED); + builder.add(ChuteBlock.FACING, ChuteBlock.ENABLED); } @Override @@ -207,8 +208,8 @@ protected BlockState updateShape( ) { if (level.isClientSide()) return state; Block neighborBlock = neighbourState.getBlock(); - if (isChuteBlock(neighborBlock)) { - BlockState newState = this.getState(level, pos, state.getValue(FACING)); + if (ChuteBlock.isChuteBlock(neighborBlock)) { + BlockState newState = this.getState(level, pos, state.getValue(ChuteBlock.FACING)); if (newState != null && newState != state) state = newState; } state = this.checkPoweredState(level, pos, state); @@ -217,8 +218,8 @@ protected BlockState updateShape( private BlockState checkPoweredState(LevelReader level, BlockPos pos, BlockState state) { boolean flag = !level.hasNeighborSignal(pos); - if (flag == state.getValue(ENABLED)) return state; - return state.setValue(ENABLED, flag); + if (flag == state.getValue(ChuteBlock.ENABLED)) return state; + return state.setValue(ChuteBlock.ENABLED, flag); } @Override @@ -227,8 +228,8 @@ public void tick( ServerLevel level, BlockPos pos, RandomSource random) { - if (!state.getValue(ENABLED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(ENABLED), 2); + if (!state.getValue(ChuteBlock.ENABLED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(ChuteBlock.ENABLED), 2); } } @@ -244,7 +245,7 @@ public BlockEntityTicker getTicker( if (level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.CHUTE.get(), (_, _, _, be) -> be.tick() @@ -253,12 +254,12 @@ public BlockEntityTicker getTicker( @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext collisionContext) { - return switch (state.getValue(FACING)) { - case NORTH -> AABB_N; - case SOUTH -> AABB_S; - case WEST -> AABB_W; - case EAST -> AABB_E; - default -> AABB; + return switch (state.getValue(ChuteBlock.FACING)) { + case NORTH -> ChuteBlock.AABB_N; + case SOUTH -> ChuteBlock.AABB_S; + case WEST -> ChuteBlock.AABB_W; + case EAST -> ChuteBlock.AABB_E; + default -> ChuteBlock.AABB; }; } @@ -338,14 +339,14 @@ BlockState getState(LevelReader level, BlockPos pos, Direction facing) { boolean success = false; boolean tall = false; BlockState result = this.defaultBlockState() - .setValue(FACING, facing) - .setValue(ENABLED, !level.hasNeighborSignal(pos)); + .setValue(ChuteBlock.FACING, facing) + .setValue(ChuteBlock.ENABLED, !level.hasNeighborSignal(pos)); // 遍历六个方向 获取指向自己的溜槽 for (Direction dir : Direction.values()) { BlockPos neighborPos = pos.relative(dir); BlockState neighborState = level.getBlockState(neighborPos); - if (isChuteBlock(neighborState)) { - if (getFacing(neighborState) == dir.getOpposite()) { + if (ChuteBlock.isChuteBlock(neighborState)) { + if (ChuteBlock.getFacing(neighborState) == dir.getOpposite()) { success = true; if (dir == Direction.UP) { tall = !neighborState.is(ModBlocks.MAGNETIC_CHUTE.get()); @@ -354,11 +355,11 @@ BlockState getState(LevelReader level, BlockPos pos, Direction facing) { return null; } } else { - if (facing.getOpposite() == getFacing(neighborState)) { + if (facing.getOpposite() == ChuteBlock.getFacing(neighborState)) { facing = facing.getOpposite(); } BlockState backState = level.getBlockState(pos.relative(facing)); - if (isChuteBlock(backState) && getFacing(backState) == facing.getOpposite()) { + if (ChuteBlock.isChuteBlock(backState) && ChuteBlock.getFacing(backState) == facing.getOpposite()) { return null; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/MagneticChuteBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/MagneticChuteBlock.java index 580b19f691..8f2bfd87a9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/MagneticChuteBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/MagneticChuteBlock.java @@ -5,7 +5,6 @@ import dev.dubhe.anvilcraft.api.hammer.IHammerRemovable; import dev.dubhe.anvilcraft.block.better.BetterBaseEntityBlock; import dev.dubhe.anvilcraft.block.entity.MagneticChuteBlockEntity; -import dev.dubhe.anvilcraft.block.entity.SimpleMagneticChuteBlockEntity; import dev.dubhe.anvilcraft.init.ModMenuTypes; import dev.dubhe.anvilcraft.init.block.ModBlockEntities; import dev.dubhe.anvilcraft.init.block.ModBlocks; @@ -37,6 +36,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -89,23 +89,24 @@ public class MagneticChuteBlock extends BetterBaseEntityBlock implements HammerR public MagneticChuteBlock(Properties properties) { super(properties); this.registerDefaultState( - this.stateDefinition.any().setValue(FACING, Direction.DOWN).setValue(ENABLED, true).setValue(HEAD, false)); + this.stateDefinition.any().setValue(MagneticChuteBlock.FACING, Direction.DOWN).setValue(MagneticChuteBlock.ENABLED, true) + .setValue(MagneticChuteBlock.HEAD, false)); } @Override protected MapCodec codec() { - return simpleCodec(MagneticChuteBlock::new); + return BlockBehaviour.simpleCodec(MagneticChuteBlock::new); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext collisionContext) { - return switch (state.getValue(FACING)) { - case NORTH -> SHAPE_N; - case SOUTH -> SHAPE_S; - case WEST -> SHAPE_W; - case EAST -> SHAPE_E; - case DOWN -> SHAPE_DOWN; - case UP -> SHAPE_UP; + return switch (state.getValue(MagneticChuteBlock.FACING)) { + case NORTH -> MagneticChuteBlock.SHAPE_N; + case SOUTH -> MagneticChuteBlock.SHAPE_S; + case WEST -> MagneticChuteBlock.SHAPE_W; + case EAST -> MagneticChuteBlock.SHAPE_E; + case DOWN -> MagneticChuteBlock.SHAPE_DOWN; + case UP -> MagneticChuteBlock.SHAPE_UP; }; } @@ -173,14 +174,14 @@ protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, .setValue(SimpleMagneticChuteBlock.WATERLOGGED, level.getFluidState(pos).getType() == Fluids.WATER); } return this.defaultBlockState() - .setValue(FACING, facing) - .setValue(ENABLED, !context.getLevel().hasNeighborSignal(context.getClickedPos())); + .setValue(MagneticChuteBlock.FACING, facing) + .setValue(MagneticChuteBlock.ENABLED, !context.getLevel().hasNeighborSignal(context.getClickedPos())); } @Override public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilHammer) { BlockState oldState = level.getBlockState(pos); - Direction oldFacing = oldState.getValue(FACING); + Direction oldFacing = oldState.getValue(MagneticChuteBlock.FACING); Direction newFacing = switch (oldFacing) { case WEST -> Direction.UP; case UP -> Direction.DOWN; @@ -200,22 +201,22 @@ public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilH @Override public Property getChangeableProperty(BlockState blockState) { - return FACING; + return MagneticChuteBlock.FACING; } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(MagneticChuteBlock.FACING, rotation.rotate(state.getValue(MagneticChuteBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(MagneticChuteBlock.FACING))); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ENABLED, HEAD); + builder.add(MagneticChuteBlock.FACING, MagneticChuteBlock.ENABLED, MagneticChuteBlock.HEAD); } @Override @@ -231,7 +232,7 @@ protected void neighborChanged( // 被任意溜槽指向时,降级为简易磁性溜槽 if (SimpleMagneticChuteBlock.isPointedByChute(level, pos)) { level.setBlockAndUpdate(pos, ModBlocks.SIMPLE_MAGNETIC_CHUTE.getDefaultState() - .setValue(SimpleMagneticChuteBlock.FACING, state.getValue(FACING)) + .setValue(SimpleMagneticChuteBlock.FACING, state.getValue(MagneticChuteBlock.FACING)) .setValue(SimpleMagneticChuteBlock.ENABLED, !level.hasNeighborSignal(pos)) .setValue(SimpleMagneticChuteBlock.WATERLOGGED, level.getFluidState(pos).getType() == Fluids.WATER) .setValue(SimpleMagneticChuteBlock.HEAD, false)); @@ -241,8 +242,8 @@ protected void neighborChanged( BlockState aboveState = level.getBlockState(pos.above()); boolean hasHead = (aboveState.is(ModBlocks.CHUTE.get()) || aboveState.is(ModBlocks.SIMPLE_CHUTE.get())) && aboveState.getValue(ChuteBlock.FACING) == Direction.DOWN; - if (state.getValue(HEAD) != hasHead) { - level.setBlockAndUpdate(pos, state.setValue(HEAD, hasHead)); + if (state.getValue(MagneticChuteBlock.HEAD) != hasHead) { + level.setBlockAndUpdate(pos, state.setValue(MagneticChuteBlock.HEAD, hasHead)); return; } } @@ -251,8 +252,8 @@ protected void neighborChanged( private void checkPoweredState(Level level, BlockPos pos, BlockState state) { boolean flag = !level.hasNeighborSignal(pos); - if (flag != state.getValue(ENABLED)) { - level.setBlock(pos, state.setValue(ENABLED, flag), 2); + if (flag != state.getValue(MagneticChuteBlock.ENABLED)) { + level.setBlock(pos, state.setValue(MagneticChuteBlock.ENABLED, flag), 2); } } @@ -262,7 +263,7 @@ private void checkPoweredState(Level level, BlockPos pos, BlockState state) { if (level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( blockEntityType, ModBlockEntities.MAGNETIC_CHUTE.get(), ((_, _, _, be) -> be.tick())); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleChuteBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleChuteBlock.java index 675046a083..6bf2c6716e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleChuteBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleChuteBlock.java @@ -28,6 +28,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -71,15 +72,15 @@ public SimpleChuteBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(FACING, Direction.DOWN) - .setValue(WATERLOGGED, false) - .setValue(ENABLED, true) - .setValue(TALL, false)); + .setValue(SimpleChuteBlock.FACING, Direction.DOWN) + .setValue(SimpleChuteBlock.WATERLOGGED, false) + .setValue(SimpleChuteBlock.ENABLED, true) + .setValue(SimpleChuteBlock.TALL, false)); } @Override protected MapCodec codec() { - return simpleCodec(SimpleChuteBlock::new); + return BlockBehaviour.simpleCodec(SimpleChuteBlock::new); } @Override @@ -89,7 +90,7 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, WATERLOGGED, ENABLED, TALL); + builder.add(SimpleChuteBlock.FACING, SimpleChuteBlock.WATERLOGGED, SimpleChuteBlock.ENABLED, SimpleChuteBlock.TALL); } @Override @@ -103,9 +104,9 @@ protected BlockState updateShape( BlockState neighbourState, RandomSource random ) { - if (state.getValue(WATERLOGGED)) ticks.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); + if (state.getValue(SimpleChuteBlock.WATERLOGGED)) ticks.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); if (level.isClientSide()) return state; - BlockState newState = this.getState(level, pos, state.getValue(FACING)); + BlockState newState = this.getState(level, pos, state.getValue(SimpleChuteBlock.FACING)); if (newState != null && newState != state) state = newState; state = this.checkPoweredState(level, pos, state); @@ -114,8 +115,8 @@ protected BlockState updateShape( private BlockState checkPoweredState(LevelReader level, BlockPos pos, BlockState state) { boolean flag = !level.hasNeighborSignal(pos); - if (flag == state.getValue(ENABLED)) return state; - return state.setValue(ENABLED, flag); + if (flag == state.getValue(SimpleChuteBlock.ENABLED)) return state; + return state.setValue(SimpleChuteBlock.ENABLED, flag); } @Override @@ -136,8 +137,8 @@ public void tick( BlockPos pos, RandomSource random ) { - if (!state.getValue(ENABLED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(ENABLED), 2); + if (!state.getValue(SimpleChuteBlock.ENABLED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(SimpleChuteBlock.ENABLED), 2); } } @@ -160,7 +161,7 @@ protected void affectNeighborsAfterRemoval( public @Nullable BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType blockEntityType) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( blockEntityType, ModBlockEntities.SIMPLE_CHUTE.get(), ((_, _, _, be) -> be.tick()) @@ -169,22 +170,22 @@ protected void affectNeighborsAfterRemoval( @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - Direction facing = state.getValue(FACING); - if (!state.getValue(TALL)) { + Direction facing = state.getValue(SimpleChuteBlock.FACING); + if (!state.getValue(SimpleChuteBlock.TALL)) { return switch (facing) { - case NORTH -> AABB_N; - case EAST -> AABB_E; - case SOUTH -> AABB_S; - case WEST -> AABB_W; - default -> AABB; + case NORTH -> SimpleChuteBlock.AABB_N; + case EAST -> SimpleChuteBlock.AABB_E; + case SOUTH -> SimpleChuteBlock.AABB_S; + case WEST -> SimpleChuteBlock.AABB_W; + default -> SimpleChuteBlock.AABB; }; } else { return switch (facing) { - case NORTH -> AABB_TALL_N; - case EAST -> AABB_TALL_E; - case SOUTH -> AABB_TALL_S; - case WEST -> AABB_TALL_W; - default -> AABB_TALL; + case NORTH -> SimpleChuteBlock.AABB_TALL_N; + case EAST -> SimpleChuteBlock.AABB_TALL_E; + case SOUTH -> SimpleChuteBlock.AABB_TALL_S; + case WEST -> SimpleChuteBlock.AABB_TALL_W; + default -> SimpleChuteBlock.AABB_TALL; }; } } @@ -210,13 +211,13 @@ protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, @Override public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); + return state.getValue(SimpleChuteBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilHammer) { BlockState oldState = level.getBlockState(pos); - Direction oldFacing = oldState.getValue(FACING); + Direction oldFacing = oldState.getValue(SimpleChuteBlock.FACING); Direction newFacing = switch (oldFacing) { case WEST -> Direction.DOWN; case DOWN -> Direction.NORTH; @@ -224,7 +225,7 @@ public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilH }; BlockState facingState = level.getBlockState(pos.relative(newFacing)); if (facingState.is(ModBlocks.CHUTE.get()) || facingState.is(ModBlocks.SIMPLE_CHUTE.get())) { - if (facingState.getValue(FACING).getOpposite() == newFacing) { + if (facingState.getValue(SimpleChuteBlock.FACING).getOpposite() == newFacing) { level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); level.levelEvent(2001, pos, Block.getId(oldState)); Block.dropResources(oldState, level, pos); @@ -237,18 +238,18 @@ public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilH @Override public Property getChangeableProperty(BlockState blockState) { - return FACING; + return SimpleChuteBlock.FACING; } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(SimpleChuteBlock.FACING, rotation.rotate(state.getValue(SimpleChuteBlock.FACING))); } @SuppressWarnings("deprecation") @Override public BlockState mirror(BlockState state, Mirror mirror) { - return state.rotate(mirror.getRotation(state.getValue(FACING))); + return state.rotate(mirror.getRotation(state.getValue(SimpleChuteBlock.FACING))); } @Nullable @@ -272,10 +273,10 @@ BlockState getState(LevelReader level, BlockPos pos, Direction facing) { } if (!success) { result = ModBlocks.CHUTE.getDefaultState() - .setValue(FACING, facing) - .setValue(ENABLED, !level.hasNeighborSignal(pos)); + .setValue(SimpleChuteBlock.FACING, facing) + .setValue(SimpleChuteBlock.ENABLED, !level.hasNeighborSignal(pos)); } else { - result = result.setValue(TALL, tall); + result = result.setValue(SimpleChuteBlock.TALL, tall); } return result; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleMagneticChuteBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleMagneticChuteBlock.java index d441c1b695..50df13a1b0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleMagneticChuteBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/chute/SimpleMagneticChuteBlock.java @@ -28,6 +28,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -85,15 +86,15 @@ public SimpleMagneticChuteBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(FACING, Direction.UP) - .setValue(ENABLED, true) - .setValue(WATERLOGGED, false) - .setValue(HEAD, false)); + .setValue(SimpleMagneticChuteBlock.FACING, Direction.UP) + .setValue(SimpleMagneticChuteBlock.ENABLED, true) + .setValue(SimpleMagneticChuteBlock.WATERLOGGED, false) + .setValue(SimpleMagneticChuteBlock.HEAD, false)); } @Override protected MapCodec codec() { - return simpleCodec(SimpleMagneticChuteBlock::new); + return BlockBehaviour.simpleCodec(SimpleMagneticChuteBlock::new); } @Override @@ -103,7 +104,10 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, ENABLED, WATERLOGGED, HEAD); + builder.add( + SimpleMagneticChuteBlock.FACING, SimpleMagneticChuteBlock.ENABLED, SimpleMagneticChuteBlock.WATERLOGGED, + SimpleMagneticChuteBlock.HEAD + ); } /** @@ -132,10 +136,10 @@ protected void neighborChanged( ) { if (!level.isClientSide()) { // 不再被任意磁性溜槽指向时,升级回正常磁性溜槽 - if (!isPointedByChute(level, pos)) { + if (!SimpleMagneticChuteBlock.isPointedByChute(level, pos)) { level.setBlockAndUpdate( pos, ModBlocks.MAGNETIC_CHUTE.get().defaultBlockState() - .setValue(MagneticChuteBlock.FACING, state.getValue(FACING)) + .setValue(MagneticChuteBlock.FACING, state.getValue(SimpleMagneticChuteBlock.FACING)) ); return; } @@ -143,8 +147,8 @@ protected void neighborChanged( BlockState aboveState = level.getBlockState(pos.above()); boolean hasHead = (aboveState.is(ModBlocks.CHUTE.get()) || aboveState.is(ModBlocks.SIMPLE_CHUTE.get())) && aboveState.getValue(ChuteBlock.FACING) == Direction.DOWN; - if (state.getValue(HEAD) != hasHead) { - level.setBlockAndUpdate(pos, state.setValue(HEAD, hasHead)); + if (state.getValue(SimpleMagneticChuteBlock.HEAD) != hasHead) { + level.setBlockAndUpdate(pos, state.setValue(SimpleMagneticChuteBlock.HEAD, hasHead)); } } } @@ -160,7 +164,7 @@ protected BlockState updateShape( BlockState neighbourState, RandomSource random ) { - if (state.getValue(WATERLOGGED)) ticks.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); + if (state.getValue(SimpleMagneticChuteBlock.WATERLOGGED)) ticks.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); return super.updateShape(state, level, ticks, pos, directionToNeighbour, neighbourPos, neighbourState, random); } @@ -182,8 +186,8 @@ public void tick( BlockPos pos, RandomSource random ) { - if (!state.getValue(ENABLED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(ENABLED), 2); + if (!state.getValue(SimpleMagneticChuteBlock.ENABLED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(SimpleMagneticChuteBlock.ENABLED), 2); } } @@ -206,7 +210,7 @@ protected void affectNeighborsAfterRemoval( public @Nullable BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType blockEntityType) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( blockEntityType, ModBlockEntities.SIMPLE_MAGNETIC_CHUTE.get(), ((_, _, _, be) -> be.tick()) @@ -215,13 +219,17 @@ protected void affectNeighborsAfterRemoval( @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case DOWN -> SHAPE_DOWN; - case NORTH -> state.getValue(HEAD) ? SHAPE_N_HEAD : SHAPE_N; - case SOUTH -> state.getValue(HEAD) ? SHAPE_S_HEAD : SHAPE_S; - case WEST -> state.getValue(HEAD) ? SHAPE_W_HEAD : SHAPE_W; - case EAST -> state.getValue(HEAD) ? SHAPE_E_HEAD : SHAPE_E; - default -> SHAPE_UP; + return switch (state.getValue(SimpleMagneticChuteBlock.FACING)) { + case DOWN -> SimpleMagneticChuteBlock.SHAPE_DOWN; + case NORTH -> state.getValue(SimpleMagneticChuteBlock.HEAD) ? SimpleMagneticChuteBlock.SHAPE_N_HEAD + : SimpleMagneticChuteBlock.SHAPE_N; + case SOUTH -> state.getValue(SimpleMagneticChuteBlock.HEAD) ? SimpleMagneticChuteBlock.SHAPE_S_HEAD + : SimpleMagneticChuteBlock.SHAPE_S; + case WEST -> state.getValue(SimpleMagneticChuteBlock.HEAD) ? SimpleMagneticChuteBlock.SHAPE_W_HEAD + : SimpleMagneticChuteBlock.SHAPE_W; + case EAST -> state.getValue(SimpleMagneticChuteBlock.HEAD) ? SimpleMagneticChuteBlock.SHAPE_E_HEAD + : SimpleMagneticChuteBlock.SHAPE_E; + default -> SimpleMagneticChuteBlock.SHAPE_UP; }; } @@ -246,13 +254,13 @@ protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, @Override public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); + return state.getValue(SimpleMagneticChuteBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilHammer) { BlockState oldState = level.getBlockState(pos); - Direction oldFacing = oldState.getValue(FACING); + Direction oldFacing = oldState.getValue(SimpleMagneticChuteBlock.FACING); Direction newFacing = switch (oldFacing) { case WEST -> Direction.UP; case UP -> Direction.DOWN; @@ -273,17 +281,17 @@ public boolean change(Player player, BlockPos pos, Level level, ItemStack anvilH @Override public Property getChangeableProperty(BlockState blockState) { - return FACING; + return SimpleMagneticChuteBlock.FACING; } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(SimpleMagneticChuteBlock.FACING, rotation.rotate(state.getValue(SimpleMagneticChuteBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(SimpleMagneticChuteBlock.FACING))); } // 防止流体流动时破坏溜槽 diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ActivatorSlidingRailBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ActivatorSlidingRailBlock.java index ee167cb97c..862e208093 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ActivatorSlidingRailBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ActivatorSlidingRailBlock.java @@ -61,7 +61,8 @@ public class ActivatorSlidingRailBlock extends BaseSlidingRailBlock implements I public ActivatorSlidingRailBlock(Properties properties) { super(properties); - this.registerDefaultState(this.getStateDefinition().any().setValue(FACING, Direction.NORTH).setValue(POWERED, false)); + this.registerDefaultState(this.getStateDefinition().any().setValue(ActivatorSlidingRailBlock.FACING, Direction.NORTH).setValue( + ActivatorSlidingRailBlock.POWERED, false)); } @Nullable @@ -72,13 +73,13 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { facing = facing.getOpposite(); } return this.defaultBlockState() - .setValue(FACING, facing) - .setValue(POWERED, this.isPowered(context.getLevel(), context.getClickedPos(), facing)); + .setValue(ActivatorSlidingRailBlock.FACING, facing) + .setValue(ActivatorSlidingRailBlock.POWERED, this.isPowered(context.getLevel(), context.getClickedPos(), facing)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED); + builder.add(ActivatorSlidingRailBlock.FACING, ActivatorSlidingRailBlock.POWERED); } protected boolean findActivatorSlidingRailSignal(Level level, BlockPos pos, Direction facing, boolean searchForward) { @@ -101,8 +102,8 @@ protected boolean findActivatorSlidingRailSignal( int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); - if (!state.hasProperty(FACING)) return false; - Direction facing = state.getValue(FACING); + if (!state.hasProperty(ActivatorSlidingRailBlock.FACING)) return false; + Direction facing = state.getValue(ActivatorSlidingRailBlock.FACING); switch (facing.getAxis()) { case X -> x += searchForward ? 1 : -1; case Z -> z += searchForward ? 1 : -1; @@ -115,10 +116,10 @@ protected boolean findActivatorSlidingRailSignal( protected boolean isSameRailWithPower(Level level, BlockPos pos, boolean searchForward, int recursionCount, Direction facing) { BlockState state = level.getBlockState(pos); if (!(state.getBlock() instanceof ActivatorSlidingRailBlock other)) return false; - Direction otherFacing = state.getValue(FACING); + Direction otherFacing = state.getValue(ActivatorSlidingRailBlock.FACING); if (facing.getAxis() != otherFacing.getAxis()) return false; boolean hasSideSignal = false; - for (Direction d : SIGNAL_SOURCE_SIDES) { + for (Direction d : ActivatorSlidingRailBlock.SIGNAL_SOURCE_SIDES) { if (level.hasSignal(pos.relative(d), d)) { hasSideSignal = true; break; @@ -135,9 +136,9 @@ protected boolean useShapeForLightOcclusion(BlockState state) { @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { - return switch (state.getValue(FACING).getAxis()) { - case X -> AABB_X; - case Z -> AABB_Z; + return switch (state.getValue(ActivatorSlidingRailBlock.FACING).getAxis()) { + case X -> ActivatorSlidingRailBlock.AABB_X; + case Z -> ActivatorSlidingRailBlock.AABB_Z; default -> super.getShape(state, level, pos, ctx); }; } @@ -145,20 +146,22 @@ public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, Co private static final int[] UPDATE_POS = new int[] {-1, 1}; protected void updatePower(Level level, BlockPos pos, BlockState state, BlockPos fromPos) { - boolean powered = state.getValue(POWERED); + boolean powered = state.getValue(ActivatorSlidingRailBlock.POWERED); boolean shouldPower = this.isPowered(level, pos); if (powered != shouldPower) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, shouldPower)); + level.setBlockAndUpdate(pos, state.setValue(ActivatorSlidingRailBlock.POWERED, shouldPower)); this.updateAbove(level, pos); } if (powered) { - Direction.Axis axis = state.getValue(FACING).getAxis(); - for (int updatePos : UPDATE_POS) { + Direction.Axis axis = state.getValue(ActivatorSlidingRailBlock.FACING).getAxis(); + for (int updatePos : ActivatorSlidingRailBlock.UPDATE_POS) { BlockPos pos1 = pos.relative(axis, updatePos); if (pos1.equals(fromPos)) continue; BlockState state1 = level.getBlockState(pos1); if (!(state1.getBlock() instanceof ActivatorSlidingRailBlock other)) continue; - if (state1.getOptionalValue(FACING).map(Direction::getAxis).filter(axis::equals).isEmpty()) continue; + if (state1.getOptionalValue(ActivatorSlidingRailBlock.FACING).map(Direction::getAxis).filter(axis::equals).isEmpty()) { + continue; + } level.neighborChanged(pos1, other, Orientation.random(level.getRandom())); } } @@ -172,23 +175,23 @@ public void onNeighborChange(BlockState state, LevelReader level, BlockPos pos, || !neighbor.equals(pos.above()) || level.getBlockEntity(pos.above(), BlockEntityType.PISTON).map(PistonMovingBlockEntity::isSourcePiston).orElse(true) ) { - MOVING_PISTON_MAP.remove(pos); + ISlidingRail.MOVING_PISTON_MAP.remove(pos); return; } PistonPushInfo ppi = new PistonPushInfo(neighbor, dir); - if (MOVING_PISTON_MAP.containsKey(pos)) { - MOVING_PISTON_MAP.get(pos).fromPos = neighbor; - } else MOVING_PISTON_MAP.put(pos, ppi); + if (ISlidingRail.MOVING_PISTON_MAP.containsKey(pos)) { + ISlidingRail.MOVING_PISTON_MAP.get(pos).fromPos = neighbor; + } else ISlidingRail.MOVING_PISTON_MAP.put(pos, ppi); if (level instanceof Level world) { this.updatePower(world, pos, state, neighbor); Optional beOp = world.getBlockEntity(pos, ModBlockEntities.ACTIVATOR_SLIDING_RAIL.get()); if (!neighbor.equals(pos.above())) return; if ( - state.getValue(POWERED) + state.getValue(ActivatorSlidingRailBlock.POWERED) && !beOp.map(ActivatorSlidingRailBlockEntity::shouldPower).orElse(false) && !world.getBlockTicks().hasScheduledTick(pos, this) - && !MOVING_PISTON_MAP.containsKey(neighbor) + && !ISlidingRail.MOVING_PISTON_MAP.containsKey(neighbor) && level.getBlockState(pos).getBlock().equals(Blocks.MOVING_PISTON) && !level.getBlockEntity(pos.above(), BlockEntityType.PISTON).map(PistonMovingBlockEntity::isSourcePiston).orElse(true) ) { @@ -214,12 +217,12 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou } case FALSE -> { beOp.ifPresent(ActivatorSlidingRailBlockEntity::backToDefault); - if (!state.getValue(POWERED)) return; + if (!state.getValue(ActivatorSlidingRailBlock.POWERED)) return; BlockPos fromPos = pos.above(); if (level.isEmptyBlock(fromPos)) return; - PistonPushInfo ppi = new PistonPushInfo(fromPos, state.getValue(FACING)); + PistonPushInfo ppi = new PistonPushInfo(fromPos, state.getValue(ActivatorSlidingRailBlock.FACING)); ppi.extending = true; - MOVING_PISTON_MAP.put(pos, ppi); + ISlidingRail.MOVING_PISTON_MAP.put(pos, ppi); } case DEFAULT -> { } @@ -229,7 +232,7 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou } private boolean isPowered(Level level, BlockPos pos, Direction facing) { - for (Direction side : SIGNAL_SOURCE_SIDES) { + for (Direction side : ActivatorSlidingRailBlock.SIGNAL_SOURCE_SIDES) { if (level.getSignal(pos.relative(side), side) > 0) return true; } return this.findActivatorSlidingRailSignal(level, pos, facing, true) @@ -237,7 +240,7 @@ private boolean isPowered(Level level, BlockPos pos, Direction facing) { } private boolean isPowered(Level level, BlockPos pos) { - for (Direction side : SIGNAL_SOURCE_SIDES) { + for (Direction side : ActivatorSlidingRailBlock.SIGNAL_SOURCE_SIDES) { if (level.getSignal(pos.relative(side), side) > 0) return true; } BlockState state = level.getBlockState(pos); @@ -252,7 +255,7 @@ protected boolean isSignalSource(BlockState state) { @Override protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { - if (!state.getValue(POWERED)) return 0; + if (!state.getValue(ActivatorSlidingRailBlock.POWERED)) return 0; if ( !level.getBlockEntity(pos, ModBlockEntities.ACTIVATOR_SLIDING_RAIL.get()) .map(ActivatorSlidingRailBlockEntity::shouldPower) @@ -271,20 +274,20 @@ protected int getDirectSignal(BlockState state, BlockGetter level, BlockPos pos, @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState bs = level.getBlockState(blockPos); - level.setBlockAndUpdate(blockPos, bs.cycle(FACING)); + level.setBlockAndUpdate(blockPos, bs.cycle(ActivatorSlidingRailBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return ActivatorSlidingRailBlock.FACING; } @Override public void onSlidingAbove(Level level, BlockPos pos, BlockState state, SlidingBlockEntity entity) { if (entity.getStartPos().equals(pos.above())) return; - level.setBlockAndUpdate(pos, state.setValue(FACING, entity.getMoveDirection())); - if (!state.getValue(POWERED)) return; + level.setBlockAndUpdate(pos, state.setValue(ActivatorSlidingRailBlock.FACING, entity.getMoveDirection())); + if (!state.getValue(ActivatorSlidingRailBlock.POWERED)) return; level.getBlockEntity(pos, ModBlockEntities.ACTIVATOR_SLIDING_RAIL.get()).ifPresent(ActivatorSlidingRailBlockEntity::startPulse); ISlidingRail.stopSlidingBlock(entity); if (level.getBlockTicks().hasScheduledTick(pos, this)) return; @@ -297,7 +300,7 @@ private void updateAbove(Level level, BlockPos pos) { aboveState.onNeighborChange(level, abovePos, pos); level.neighborChanged(aboveState, abovePos, this, Orientation.random(level.getRandom()), false); if (!aboveState.isRedstoneConductor(level, abovePos)) return; - for (Direction dir : UPDATE_SIDES) { + for (Direction dir : ActivatorSlidingRailBlock.UPDATE_SIDES) { BlockPos neighborPos = abovePos.relative(dir); BlockState neighborState = level.getBlockState(neighborPos); level.neighborChanged(neighborState, neighborPos, aboveState.getBlock(), Orientation.random(level.getRandom()), false); @@ -311,11 +314,11 @@ private void updateAbove(Level level, BlockPos pos) { @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(ActivatorSlidingRailBlock.FACING, rotation.rotate(state.getValue(ActivatorSlidingRailBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(ActivatorSlidingRailBlock.FACING, mirror.mirror(state.getValue(ActivatorSlidingRailBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/DetectorSlidingRailBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/DetectorSlidingRailBlock.java index 7b0b7b61c2..aece42d6cb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/DetectorSlidingRailBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/DetectorSlidingRailBlock.java @@ -55,7 +55,8 @@ public class DetectorSlidingRailBlock extends BaseSlidingRailBlock implements IH public DetectorSlidingRailBlock(Properties properties) { super(properties); - this.registerDefaultState(this.getStateDefinition().any().setValue(FACING, Direction.NORTH).setValue(POWERED, false)); + this.registerDefaultState(this.getStateDefinition().any().setValue(DetectorSlidingRailBlock.FACING, Direction.NORTH).setValue( + DetectorSlidingRailBlock.POWERED, false)); } @Nullable @@ -68,12 +69,12 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { ) { facing = facing.getOpposite(); } - return this.defaultBlockState().setValue(FACING, facing).setValue(POWERED, false); + return this.defaultBlockState().setValue(DetectorSlidingRailBlock.FACING, facing).setValue(DetectorSlidingRailBlock.POWERED, false); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED); + builder.add(DetectorSlidingRailBlock.FACING, DetectorSlidingRailBlock.POWERED); } @Override @@ -83,9 +84,9 @@ protected boolean useShapeForLightOcclusion(BlockState state) { @Override public VoxelShape getShape(BlockState blockState, BlockGetter blockGetter, BlockPos blockPos, CollisionContext collisionContext) { - return switch (blockState.getValue(FACING).getAxis()) { - case X -> AABB_X; - case Z -> AABB_Z; + return switch (blockState.getValue(DetectorSlidingRailBlock.FACING).getAxis()) { + case X -> DetectorSlidingRailBlock.AABB_X; + case Z -> DetectorSlidingRailBlock.AABB_Z; default -> super.getShape(blockState, blockGetter, blockPos, collisionContext); }; } @@ -93,11 +94,11 @@ public VoxelShape getShape(BlockState blockState, BlockGetter blockGetter, Block @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if ( - state.getValue(POWERED) + state.getValue(DetectorSlidingRailBlock.POWERED) && level.getEntitiesOfClass(SlidingBlockEntity.class, new AABB(pos.above())).isEmpty() && level.getEntitiesOfClass(ItemEntity.class, new AABB(pos)).isEmpty() ) { - level.setBlock(pos, state.setValue(POWERED, false), Block.UPDATE_ALL); + level.setBlock(pos, state.setValue(DetectorSlidingRailBlock.POWERED, false), Block.UPDATE_ALL); level.getBlockEntity(pos, ModBlockEntities.DETECTOR_SLIDING_RAIL.get()).ifPresent(DetectorSlidingRailBlockEntity::cleanPower); } super.tick(state, level, pos, random); @@ -110,7 +111,7 @@ protected boolean isSignalSource(BlockState state) { @Override protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction side) { - if (!state.getValue(POWERED)) return 0; + if (!state.getValue(DetectorSlidingRailBlock.POWERED)) return 0; return side == Direction.DOWN ? 0 : 15; } @@ -129,27 +130,27 @@ protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState bs = level.getBlockState(blockPos); - level.setBlockAndUpdate(blockPos, bs.cycle(FACING)); + level.setBlockAndUpdate(blockPos, bs.cycle(DetectorSlidingRailBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return DetectorSlidingRailBlock.FACING; } @Override public void onSlidingAbove(Level level, BlockPos pos, BlockState state, SlidingBlockEntity entity) { Optional blockEntity = level.getBlockEntity(pos, ModBlockEntities.DETECTOR_SLIDING_RAIL.get()); blockEntity.ifPresent(detector -> detector.updatePower(entity.getBlockCount())); - level.setBlock(pos, state.setValue(POWERED, true), Block.UPDATE_ALL); + level.setBlock(pos, state.setValue(DetectorSlidingRailBlock.POWERED, true), Block.UPDATE_ALL); level.scheduleTick(pos, this, 20); } public void onItemEntitySlidingAbove(Level level, BlockPos pos, BlockState state) { Optional blockEntity = level.getBlockEntity(pos, ModBlockEntities.DETECTOR_SLIDING_RAIL.get()); blockEntity.ifPresent(detector -> detector.updatePower(1)); - level.setBlock(pos, state.setValue(POWERED, true), Block.UPDATE_ALL); + level.setBlock(pos, state.setValue(DetectorSlidingRailBlock.POWERED, true), Block.UPDATE_ALL); level.scheduleTick(pos, this, 20); } @@ -161,17 +162,17 @@ public void onItemEntitySlidingAbove(Level level, BlockPos pos, BlockState state @Override public void notifyMoved(Level level, BlockPos pos, BlockState state, BlockEntity be) { if (state.getBlock() != this) return; - level.setBlock(pos, state.setValue(POWERED, false), Block.UPDATE_ALL); + level.setBlock(pos, state.setValue(DetectorSlidingRailBlock.POWERED, false), Block.UPDATE_ALL); level.getBlockEntity(pos, ModBlockEntities.DETECTOR_SLIDING_RAIL.get()).ifPresent(DetectorSlidingRailBlockEntity::cleanPower); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(DetectorSlidingRailBlock.FACING, rotation.rotate(state.getValue(DetectorSlidingRailBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(DetectorSlidingRailBlock.FACING, mirror.mirror(state.getValue(DetectorSlidingRailBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ISlidingRail.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ISlidingRail.java index 4b17916216..a437c8ba18 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ISlidingRail.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/ISlidingRail.java @@ -72,40 +72,40 @@ static void whenOnNeighborChange(LevelReader level, BlockPos pos, BlockPos neigh if (!level.getBlockState(neighbor).is(Blocks.MOVING_PISTON)) return; Direction dir = level.getBlockState(neighbor).getValue(BlockStateProperties.FACING); if (dir.getAxis() == Direction.Axis.Y || !neighbor.equals(pos.above())) { - MOVING_PISTON_MAP.remove(pos); + ISlidingRail.MOVING_PISTON_MAP.remove(pos); return; } PistonPushInfo ppi = new PistonPushInfo(neighbor, dir); - if (MOVING_PISTON_MAP.containsKey(pos)) { - MOVING_PISTON_MAP.get(pos).fromPos = neighbor; - } else MOVING_PISTON_MAP.put(pos, ppi); + if (ISlidingRail.MOVING_PISTON_MAP.containsKey(pos)) { + ISlidingRail.MOVING_PISTON_MAP.get(pos).fromPos = neighbor; + } else ISlidingRail.MOVING_PISTON_MAP.put(pos, ppi); } static void whenNeighborChanged(Level level, Block block, BlockPos pos, BlockPos fromPos) { if (level.isClientSide()) return; BlockState blockState = level.getBlockState(fromPos); - if (!MOVING_PISTON_MAP.containsKey(pos)) return; + if (!ISlidingRail.MOVING_PISTON_MAP.containsKey(pos)) return; if (blockState.is(Blocks.MOVING_PISTON)) return; level.scheduleTick(pos, block, 2); } static void whenTick(ServerLevel level, Block block, BlockPos pos) { - if (!MOVING_PISTON_MAP.containsKey(pos)) return; - PistonPushInfo info = MOVING_PISTON_MAP.get(pos); + if (!ISlidingRail.MOVING_PISTON_MAP.containsKey(pos)) return; + PistonPushInfo info = ISlidingRail.MOVING_PISTON_MAP.get(pos); boolean isPoweredRail = block instanceof PoweredSlidingRailBlock; if (!isPoweredRail && !info.extending && info.isSourcePiston) { - MOVING_PISTON_MAP.remove(pos); + ISlidingRail.MOVING_PISTON_MAP.remove(pos); return; } else if (!isPoweredRail && !info.extending) { info.direction = info.direction.getOpposite(); } level.blockEvent(pos, block, 0, info.direction.get3DDataValue()); - MOVING_PISTON_MAP.remove(pos); + ISlidingRail.MOVING_PISTON_MAP.remove(pos); } static boolean whenTriggerEvent(Level level, BlockPos pos, int param) { Direction direction = Direction.from3DDataValue(param); - return moveBlocks(level, pos.above(), direction); + return ISlidingRail.moveBlocks(level, pos.above(), direction); } static boolean moveBlocks(Level level, BlockPos pos, Direction facing) { @@ -180,7 +180,7 @@ static boolean moveBlocks(Level level, BlockPos pos, Direction facing) { static void stopSlidingBlock(SlidingBlockEntity entity) { entity.stop(); - MOVING_PISTON_MAP.remove(entity.blockPosition()); + ISlidingRail.MOVING_PISTON_MAP.remove(entity.blockPosition()); } static void absorbEntity(BlockPos pos, Entity entity) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/PoweredSlidingRailBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/PoweredSlidingRailBlock.java index 855e9ee8d7..3ca0826caf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/PoweredSlidingRailBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/PoweredSlidingRailBlock.java @@ -58,7 +58,8 @@ public class PoweredSlidingRailBlock extends BaseSlidingRailBlock implements IHa public PoweredSlidingRailBlock(Properties properties) { super(properties); - this.registerDefaultState(this.getStateDefinition().any().setValue(FACING, Direction.NORTH).setValue(POWERED, false)); + this.registerDefaultState(this.getStateDefinition().any().setValue(PoweredSlidingRailBlock.FACING, Direction.NORTH).setValue( + PoweredSlidingRailBlock.POWERED, false)); } @Nullable @@ -69,13 +70,13 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { facing = facing.getOpposite(); } return this.defaultBlockState() - .setValue(FACING, facing) - .setValue(POWERED, this.isPowered(context.getLevel(), context.getClickedPos(), facing)); + .setValue(PoweredSlidingRailBlock.FACING, facing) + .setValue(PoweredSlidingRailBlock.POWERED, this.isPowered(context.getLevel(), context.getClickedPos(), facing)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED); + builder.add(PoweredSlidingRailBlock.FACING, PoweredSlidingRailBlock.POWERED); } protected boolean findPoweredSlidingRailSignal(Level level, BlockPos pos, Direction facing, boolean searchForward) { @@ -99,8 +100,8 @@ protected boolean findPoweredSlidingRailSignal(Level level, BlockPos pos, BlockS int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); - if (!state.hasProperty(FACING)) return false; - Direction facing = state.getValue(FACING); + if (!state.hasProperty(PoweredSlidingRailBlock.FACING)) return false; + Direction facing = state.getValue(PoweredSlidingRailBlock.FACING); switch (facing) { case NORTH -> z -= searchForward ? 1 : -1; case SOUTH -> z += searchForward ? 1 : -1; @@ -116,10 +117,10 @@ protected boolean findPoweredSlidingRailSignal(Level level, BlockPos pos, BlockS protected boolean isSameRailWithPower(Level level, BlockPos pos, boolean searchForward, int recursionCount, Direction facing) { BlockState state = level.getBlockState(pos); if (!(state.getBlock() instanceof PoweredSlidingRailBlock other)) return false; - Direction otherFacing = state.getValue(FACING); + Direction otherFacing = state.getValue(PoweredSlidingRailBlock.FACING); if (facing != otherFacing) return false; boolean hasSideSignal = false; - for (Direction d : SIGNAL_SOURCE_SIDES) { + for (Direction d : PoweredSlidingRailBlock.SIGNAL_SOURCE_SIDES) { if (level.hasSignal(pos.relative(d), d)) { hasSideSignal = true; break; @@ -136,25 +137,25 @@ protected boolean useShapeForLightOcclusion(BlockState state) { @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext ctx) { - return switch (state.getValue(FACING).getAxis()) { - case X -> AABB_X; - case Z -> AABB_Z; + return switch (state.getValue(PoweredSlidingRailBlock.FACING).getAxis()) { + case X -> PoweredSlidingRailBlock.AABB_X; + case Z -> PoweredSlidingRailBlock.AABB_Z; default -> super.getShape(state, level, pos, ctx); }; } @Override public void onNeighborChange(BlockState state, LevelReader level, BlockPos pos, BlockPos neighbor) { - if (!state.getValue(POWERED)) return; + if (!state.getValue(PoweredSlidingRailBlock.POWERED)) return; super.onNeighborChange(state, level, pos, neighbor); } protected boolean updatePower(Level level, BlockPos pos, BlockState state) { - boolean powered = state.getValue(POWERED); + boolean powered = state.getValue(PoweredSlidingRailBlock.POWERED); boolean shouldPower = this.isPowered(level, pos); if (powered != shouldPower) { powered = shouldPower; - level.setBlockAndUpdate(pos, state.setValue(POWERED, shouldPower)); + level.setBlockAndUpdate(pos, state.setValue(PoweredSlidingRailBlock.POWERED, shouldPower)); } return powered; } @@ -174,11 +175,11 @@ protected void neighborChanged( boolean movedByPiston ) { super.neighborChanged(state, level, pos, block, orientation, movedByPiston); - boolean wasPowered = state.getValue(POWERED); + boolean wasPowered = state.getValue(PoweredSlidingRailBlock.POWERED); boolean powered = this.updatePower(level, pos, state); if (!wasPowered && powered) { - Direction facing = state.getValue(FACING); + Direction facing = state.getValue(PoweredSlidingRailBlock.FACING); BlockPos behindPos = pos.relative(facing.getOpposite()); BlockState behindState = level.getBlockState(behindPos); if (behindState.is(ModBlockTags.SLIDING_RAIL_STOP_LIKE)) { @@ -194,27 +195,27 @@ protected void neighborChanged( BlockPos above = pos.above(); if (powered && !level.isEmptyBlock(above)) { - PistonPushInfo ppi = new PistonPushInfo(above, state.getValue(FACING)); + PistonPushInfo ppi = new PistonPushInfo(above, state.getValue(PoweredSlidingRailBlock.FACING)); ppi.extending = true; - if (MOVING_PISTON_MAP.containsKey(pos)) { - PistonPushInfo info = MOVING_PISTON_MAP.get(pos); + if (ISlidingRail.MOVING_PISTON_MAP.containsKey(pos)) { + PistonPushInfo info = ISlidingRail.MOVING_PISTON_MAP.get(pos); info.fromPos = above; - info.direction = state.getValue(FACING); + info.direction = state.getValue(PoweredSlidingRailBlock.FACING); info.extending = true; info.isSourcePiston = false; - } else MOVING_PISTON_MAP.put(pos, ppi); + } else ISlidingRail.MOVING_PISTON_MAP.put(pos, ppi); } if (level.isClientSide()) return; if (!powered) return; - if (!MOVING_PISTON_MAP.containsKey(pos)) return; - BlockPos checkPos = MOVING_PISTON_MAP.get(pos) instanceof PistonPushInfo info ? info.fromPos : above; + if (!ISlidingRail.MOVING_PISTON_MAP.containsKey(pos)) return; + BlockPos checkPos = ISlidingRail.MOVING_PISTON_MAP.get(pos) instanceof PistonPushInfo info ? info.fromPos : above; BlockState blockState = level.getBlockState(checkPos); if (blockState.is(Blocks.MOVING_PISTON) || blockState.isAir()) return; level.scheduleTick(pos, this, 2); } private boolean isPowered(Level level, BlockPos pos, Direction facing) { - for (Direction side : SIGNAL_SOURCE_SIDES) { + for (Direction side : PoweredSlidingRailBlock.SIGNAL_SOURCE_SIDES) { if (level.getSignal(pos.relative(side), side) > 0) return true; } return this.findPoweredSlidingRailSignal(level, pos, facing, true) @@ -222,7 +223,7 @@ private boolean isPowered(Level level, BlockPos pos, Direction facing) { } private boolean isPowered(Level level, BlockPos pos) { - for (Direction side : SIGNAL_SOURCE_SIDES) { + for (Direction side : PoweredSlidingRailBlock.SIGNAL_SOURCE_SIDES) { if (level.getSignal(pos.relative(side), side) > 0) return true; } BlockState state = level.getBlockState(pos); @@ -236,7 +237,7 @@ public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { if (entity.getType() == EntityType.ITEM && magnetizedNodeExist) return; if (entity.getType() != EntityType.ITEM && !(entity instanceof LivingEntity)) return; boolean isSneakPlayer = entity instanceof Player player && player.isShiftKeyDown(); - if (!state.getValue(POWERED)) { + if (!state.getValue(PoweredSlidingRailBlock.POWERED)) { if (!isSneakPlayer) { Vec3 blockPos = pos.getCenter(); Vec3 entityPos = entity.position(); @@ -249,7 +250,7 @@ public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { } } else { if (!isSneakPlayer) { - entity.setDeltaMovement(Vec3.ZERO.relative(state.getValue(FACING), 0.35)); + entity.setDeltaMovement(Vec3.ZERO.relative(state.getValue(PoweredSlidingRailBlock.FACING), 0.35)); } } } @@ -257,23 +258,23 @@ public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState bs = level.getBlockState(blockPos); - level.setBlockAndUpdate(blockPos, bs.cycle(FACING)); + level.setBlockAndUpdate(blockPos, bs.cycle(PoweredSlidingRailBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return PoweredSlidingRailBlock.FACING; } @Override public void onSlidingAbove(Level level, BlockPos pos, BlockState state, SlidingBlockEntity entity) { - if (!state.getValue(POWERED)) { + if (!state.getValue(PoweredSlidingRailBlock.POWERED)) { ISlidingRail.stopSlidingBlock(entity); return; } Vec3 entityPos = entity.position(); - Direction facing = state.getValue(FACING); + Direction facing = state.getValue(PoweredSlidingRailBlock.FACING); Direction.Axis horizontalAnother = facing.getClockWise().getAxis(); double single = entityPos.get(horizontalAnother); double should = Math.ceil(single) - 0.5; @@ -283,21 +284,21 @@ public void onSlidingAbove(Level level, BlockPos pos, BlockState state, SlidingB @Override public boolean canMoveBlockToTop(LevelReader level, BlockPos pos, BlockState state, BlockState top, Direction side) { - return state.getValue(POWERED) && state.getValue(FACING) == side.getOpposite(); + return state.getValue(PoweredSlidingRailBlock.POWERED) && state.getValue(PoweredSlidingRailBlock.FACING) == side.getOpposite(); } @Override public boolean canMoveSlidingToTop(LevelReader level, BlockPos pos, BlockState state, Direction side) { - return state.getValue(POWERED) && state.getValue(FACING) == side.getOpposite(); + return state.getValue(PoweredSlidingRailBlock.POWERED) && state.getValue(PoweredSlidingRailBlock.FACING) == side.getOpposite(); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(PoweredSlidingRailBlock.FACING, rotation.rotate(state.getValue(PoweredSlidingRailBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(PoweredSlidingRailBlock.FACING, mirror.mirror(state.getValue(PoweredSlidingRailBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailBlock.java index c1cf08fa5c..f9935e8501 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailBlock.java @@ -56,7 +56,7 @@ public class SlidingRailBlock extends BaseSlidingRailBlock implements IHammerCha public SlidingRailBlock(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(AXIS, Axis.X)); + this.registerDefaultState(this.getStateDefinition().any().setValue(SlidingRailBlock.AXIS, Axis.X)); } @Nullable @@ -73,12 +73,12 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { ) { axis = Axis.Y; } - return this.defaultBlockState().setValue(AXIS, axis); + return this.defaultBlockState().setValue(SlidingRailBlock.AXIS, axis); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(AXIS); + builder.add(SlidingRailBlock.AXIS); } @Override @@ -93,10 +93,10 @@ public VoxelShape getShape( BlockPos blockPos, CollisionContext collisionContext ) { - return switch (blockState.getValue(AXIS)) { - case X -> AABB_X; - case Y -> AABB_Y; - case Z -> AABB_Z; + return switch (blockState.getValue(SlidingRailBlock.AXIS)) { + case X -> SlidingRailBlock.AABB_X; + case Y -> SlidingRailBlock.AABB_Y; + case Z -> SlidingRailBlock.AABB_Z; }; } @@ -115,27 +115,27 @@ protected BlockState updateShape( if (this.isOtherRailInAxis(level, pos, Axis.X, -1) == TriState.TRUE || this.isOtherRailInAxis(level, pos, Axis.X, 1) == TriState.TRUE ) { - if (state.getValue(AXIS) != Axis.Y + if (state.getValue(SlidingRailBlock.AXIS) != Axis.Y && (this.isOtherRailInAxis(level, pos, Axis.Z, -1) == TriState.TRUE || this.isOtherRailInAxis(level, pos, Axis.Z, 1) == TriState.TRUE) ) { - state = state.setValue(AXIS, Axis.Y); + state = state.setValue(SlidingRailBlock.AXIS, Axis.Y); } - if (state.getValue(AXIS) == Axis.Y + if (state.getValue(SlidingRailBlock.AXIS) == Axis.Y && this.isOtherRailInAxis(level, pos, Axis.Z, -1) != TriState.TRUE && this.isOtherRailInAxis(level, pos, Axis.Z, 1) != TriState.TRUE ) { - state = state.setValue(AXIS, Axis.X); + state = state.setValue(SlidingRailBlock.AXIS, Axis.X); } } else if ( this.isOtherRailInAxis(level, pos, Axis.Z, -1) == TriState.TRUE || this.isOtherRailInAxis(level, pos, Axis.Z, 1) == TriState.TRUE ) { - if (state.getValue(AXIS) == Axis.Y + if (state.getValue(SlidingRailBlock.AXIS) == Axis.Y && this.isOtherRailInAxis(level, pos, Axis.X, -1) != TriState.TRUE && this.isOtherRailInAxis(level, pos, Axis.X, 1) != TriState.TRUE ) { - state = state.setValue(AXIS, Axis.Z); + state = state.setValue(SlidingRailBlock.AXIS, Axis.Z); } } super.onNeighborChange(state, level, pos, neighbourPos); @@ -146,7 +146,7 @@ private TriState isOtherRailInAxis(LevelReader level, BlockPos pos, Axis axis, i BlockState other = level.getBlockState(pos.relative(axis, relative)); Axis otherAxis; if (other.getBlock() instanceof SlidingRailBlock) { - otherAxis = other.getValue(AXIS); + otherAxis = other.getValue(SlidingRailBlock.AXIS); } else if (other.getBlock() instanceof PoweredSlidingRailBlock) { otherAxis = other.getValue(PoweredSlidingRailBlock.FACING).getAxis(); } else if (other.getBlock() instanceof ActivatorSlidingRailBlock) { @@ -162,13 +162,13 @@ private TriState isOtherRailInAxis(LevelReader level, BlockPos pos, Axis axis, i @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState bs = level.getBlockState(blockPos); - level.setBlockAndUpdate(blockPos, bs.cycle(AXIS)); + level.setBlockAndUpdate(blockPos, bs.cycle(SlidingRailBlock.AXIS)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return AXIS; + return SlidingRailBlock.AXIS; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailStopBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailStopBlock.java index f3daf939fc..f2ae79d63b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailStopBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/logistics/sliding/SlidingRailStopBlock.java @@ -49,7 +49,7 @@ protected VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return SHAPE; + return SlidingRailStopBlock.SHAPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/multipart/IMultiPartBlockModelHolder.java b/src/main/java/dev/dubhe/anvilcraft/block/multipart/IMultiPartBlockModelHolder.java index 0f7343639b..917c5ed0a9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/multipart/IMultiPartBlockModelHolder.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/multipart/IMultiPartBlockModelHolder.java @@ -17,7 +17,7 @@ default ModelRenderTarget getModelRenderTarget( BlockState stateAtModelPos = level.getBlockState(modelPos); if (stateAtModelPos.is(modelState.getBlock())) { for (Property property : modelState.getProperties()) { - stateAtModelPos = copyChangedProperty(stateAtModelPos, original, modelState, property); + stateAtModelPos = IMultiPartBlockModelHolder.copyChangedProperty(stateAtModelPos, original, modelState, property); } modelState = stateAtModelPos; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/multipart/SimpleMultiPartBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/multipart/SimpleMultiPartBlock.java index 582725364d..c2c0b2a8c3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/multipart/SimpleMultiPartBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/multipart/SimpleMultiPartBlock.java @@ -75,7 +75,7 @@ public BlockState getPlacementState(BlockPlaceContext context) { /// 是否有足够的空间放下方块 public boolean hasEnoughSpace(BlockPos pos, LevelReader level) { - for (P part : getParts()) { + for (P part : this.getParts()) { BlockPos pos1 = pos.offset(part.getOffset()); if (level.isOutsideBuildHeight(pos1)) return false; BlockState state = level.getBlockState(pos1); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/multipart/WaterloggedFlexibleMultiPartBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/multipart/WaterloggedFlexibleMultiPartBlock.java index 8ba85ae4bf..a6aac6ab5c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/multipart/WaterloggedFlexibleMultiPartBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/multipart/WaterloggedFlexibleMultiPartBlock.java @@ -31,17 +31,18 @@ public abstract class WaterloggedFlexibleMultiPartBlock< protected WaterloggedFlexibleMultiPartBlock(Properties properties) { super(properties); - this.registerDefaultState(this.defaultBlockState().setValue(WATERLOGGED, false)); + this.registerDefaultState(this.defaultBlockState().setValue(WaterloggedFlexibleMultiPartBlock.WATERLOGGED, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(WATERLOGGED); + builder.add(WaterloggedFlexibleMultiPartBlock.WATERLOGGED); } protected final BlockState waterloggedStateForPlacement(BlockPlaceContext context, BlockState state) { - return state.setValue(WATERLOGGED, context.getLevel().getFluidState(context.getClickedPos()).is(Fluids.WATER)); + return state.setValue( + WaterloggedFlexibleMultiPartBlock.WATERLOGGED, context.getLevel().getFluidState(context.getClickedPos()).is(Fluids.WATER)); } @Override @@ -56,14 +57,14 @@ public void setPlacedBy( if (part == state.getValue(this.getPart())) continue; BlockPos partPos = pos.offset(this.offsetFrom(state, part)); BlockState partState = this.placedState(part, state) - .setValue(WATERLOGGED, level.getFluidState(partPos).is(Fluids.WATER)); + .setValue(WaterloggedFlexibleMultiPartBlock.WATERLOGGED, level.getFluidState(partPos).is(Fluids.WATER)); level.setBlockAndUpdate(partPos, partState); } } @Override public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); + return state.getValue(WaterloggedFlexibleMultiPartBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override @@ -77,7 +78,7 @@ public BlockState updateShape( BlockState neighborState, RandomSource random ) { - if (state.getValue(WATERLOGGED)) { + if (state.getValue(WaterloggedFlexibleMultiPartBlock.WATERLOGGED)) { ticks.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); } return super.updateShape(state, level, ticks, pos, direction, neighborPos, neighborState, random); @@ -110,7 +111,7 @@ public void change(BlockPos pos, Level level, NonNullFunction fi @Override protected int getSignalStrength(Level level, AABB box, Set> entityClasses) { - return Math.clamp(getEntityCountWithFilter(level, box, this.filter), 0, 15); + return Math.clamp(EntityCountPressurePlateBlock.getEntityCountWithFilter(level, box, this.filter), 0, 15); } protected static int getEntityCountWithFilter(Level level, AABB box, Predicate filter) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/EntityTypePressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/EntityTypePressurePlateBlock.java index 5893b7657f..75b15b7ccd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/EntityTypePressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/EntityTypePressurePlateBlock.java @@ -23,7 +23,7 @@ protected Set> getEntityClasses() { @Override protected int getSignalStrength(Level level, AABB box, Set> entityClasses) { - return Math.clamp(getEntityTypes(level, box, entityClasses), 0, 15); + return Math.clamp(EntityTypePressurePlateBlock.getEntityTypes(level, box, entityClasses), 0, 15); } protected static int getEntityTypes(Level level, AABB box, Set> entityClasses) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/FireImmunePressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/FireImmunePressurePlateBlock.java index 161ce6d9ad..4057fb075f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/FireImmunePressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/FireImmunePressurePlateBlock.java @@ -24,7 +24,7 @@ protected Set> getEntityClasses() { @Override protected int getSignalStrength(Level level, AABB box, Set> entityClasses) { - return Math.clamp(getFireImmuneEntityCount(level, box, entityClasses), 0, 15); + return Math.clamp(FireImmunePressurePlateBlock.getFireImmuneEntityCount(level, box, entityClasses), 0, 15); } protected static int getFireImmuneEntityCount(Level level, AABB box, Set> entityClasses) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/HealthPercentPressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/HealthPercentPressurePlateBlock.java index ceedbaf6c7..417290e6b0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/HealthPercentPressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/HealthPercentPressurePlateBlock.java @@ -34,7 +34,7 @@ protected Set> getEntityClasses() { protected int getSignalStrength( Level level, AABB box, Set> entityClasses ) { - Pair minAndMax = getEntitiesHealthPercentMinAndMax(level, box, entityClasses); + Pair minAndMax = HealthPercentPressurePlateBlock.getEntitiesHealthPercentMinAndMax(level, box, entityClasses); float value = this.useMin ? minAndMax.getFirst() : minAndMax.getSecond(); return (int) (value * 15); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/ItemDurabilityPressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/ItemDurabilityPressurePlateBlock.java index 23f1359841..0d80939822 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/ItemDurabilityPressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/ItemDurabilityPressurePlateBlock.java @@ -29,7 +29,7 @@ protected Set> getEntityClasses() { @Override protected int getSignalStrength(Level level, AABB box, Set> entityClasses) { - Pair minAndMax = getItemDurabilityPercentMinAndMax(level, box); + Pair minAndMax = ItemDurabilityPressurePlateBlock.getItemDurabilityPercentMinAndMax(level, box); float value = this.useMin ? minAndMax.getFirst() : minAndMax.getSecond(); return (int) (value * 15); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerHungerPressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerHungerPressurePlateBlock.java index aefbfbd64a..a7b782d838 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerHungerPressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerHungerPressurePlateBlock.java @@ -23,7 +23,7 @@ protected Set> getEntityClasses() { @Override protected int getSignalStrength(Level level, AABB box, Set> entityClasses) { - return (int) Math.clamp(getMaxHungerPercent(level, box) * 15, 0, 15); + return (int) Math.clamp(PlayerHungerPressurePlateBlock.getMaxHungerPercent(level, box) * 15, 0, 15); } protected static float getMaxHungerPercent(Level level, AABB box) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerInventoryPressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerInventoryPressurePlateBlock.java index d5a7b2c772..b48cbcfc52 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerInventoryPressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/PlayerInventoryPressurePlateBlock.java @@ -24,7 +24,7 @@ protected Set> getEntityClasses() { @Override protected int getSignalStrength(Level level, AABB box, Set> entityClasses) { - return (int) Math.clamp(getInventoryOccupiedCapacityMaxPercent(level, box) * 15, 0, 15); + return (int) Math.clamp(PlayerInventoryPressurePlateBlock.getInventoryOccupiedCapacityMaxPercent(level, box) * 15, 0, 15); } protected static float getInventoryOccupiedCapacityMaxPercent(Level level, AABB box) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/PowerLevelPressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/PowerLevelPressurePlateBlock.java index 2bf96186aa..8ff53da1a0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/PowerLevelPressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/PowerLevelPressurePlateBlock.java @@ -14,6 +14,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BasePressurePlateBlock; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockSetType; @@ -29,7 +30,7 @@ public class PowerLevelPressurePlateBlock extends BasePressurePlateBlock { public static final MapCodec CODEC = RecordCodecBuilder.mapCodec( instance -> instance.group( - BlockSetType.CODEC.fieldOf("block_set_type").forGetter(block -> block.type), propertiesCodec() + BlockSetType.CODEC.fieldOf("block_set_type").forGetter(block -> block.type), BlockBehaviour.propertiesCodec() ).apply(instance, PowerLevelPressurePlateBlock::new) ); @@ -37,12 +38,12 @@ public class PowerLevelPressurePlateBlock extends BasePressurePlateBlock { public PowerLevelPressurePlateBlock(BlockSetType type, Properties properties) { super(properties, type); - this.registerDefaultState(this.stateDefinition.any().setValue(POWER, 0)); + this.registerDefaultState(this.stateDefinition.any().setValue(PowerLevelPressurePlateBlock.POWER, 0)); } @Override protected MapCodec codec() { - return CODEC; + return PowerLevelPressurePlateBlock.CODEC; } @Override @@ -72,7 +73,7 @@ protected void entityInside( @Override protected int getSignalForState(BlockState state) { - return state.getValue(POWER); + return state.getValue(PowerLevelPressurePlateBlock.POWER); } protected void checkPressed(@Nullable Entity entity, Level level, BlockPos pos, BlockState state, int currentSignal) { @@ -90,7 +91,7 @@ protected void checkPressed(@Nullable Entity entity, Level level, BlockPos pos, @Override protected int getSignalStrength(Level level, BlockPos pos) { - return this.getSignalStrength(level, TOUCH_AABB.move(pos), this.getEntityClasses()); + return this.getSignalStrength(level, BasePressurePlateBlock.TOUCH_AABB.move(pos), this.getEntityClasses()); } protected int getSignalStrength(Level level, AABB box, Set> entityClasses) { @@ -137,11 +138,11 @@ protected void sendEvent(@Nullable Entity entity, Level level, BlockPos pos, boo @Override protected BlockState setSignalForState(BlockState state, int strength) { - return state.setValue(POWER, Math.clamp(strength, 0, 15)); + return state.setValue(PowerLevelPressurePlateBlock.POWER, Math.clamp(strength, 0, 15)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWER); + builder.add(PowerLevelPressurePlateBlock.POWER); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/plate/TimeCountedPressurePlateBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/plate/TimeCountedPressurePlateBlock.java index 454d8aa68a..2c1b0dad27 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/plate/TimeCountedPressurePlateBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/plate/TimeCountedPressurePlateBlock.java @@ -24,13 +24,17 @@ public class TimeCountedPressurePlateBlock extends PressurePlateBlock implements public TimeCountedPressurePlateBlock(BlockSetType type, Properties properties, int needTick) { super(type, properties); this.needTick = needTick; - this.registerDefaultState(this.stateDefinition.any().setValue(POWER, 0).setValue(BlockStateProperties.POWERED, false)); + this.registerDefaultState( + this.stateDefinition.any() + .setValue(TimeCountedPressurePlateBlock.POWER, 0) + .setValue(BlockStateProperties.POWERED, false) + ); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(POWER); + builder.add(TimeCountedPressurePlateBlock.POWER); } @Override @@ -40,12 +44,13 @@ protected int getSignalStrength(Level level, BlockPos pos) { @Override protected int getSignalForState(BlockState state) { - return state.getValue(POWER); + return state.getValue(TimeCountedPressurePlateBlock.POWER); } @Override protected BlockState setSignalForState(BlockState state, int signal) { - return state.setValue(POWER, Math.clamp(signal, 0, 15)).setValue(BlockStateProperties.POWERED, signal > 0); + return state.setValue(TimeCountedPressurePlateBlock.POWER, Math.clamp(signal, 0, 15)) + .setValue(BlockStateProperties.POWERED, signal > 0); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/HeliostatsBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/HeliostatsBlock.java index 890241f410..b8aea71203 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/HeliostatsBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/HeliostatsBlock.java @@ -13,6 +13,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.CollisionContext; @@ -42,7 +43,7 @@ public HeliostatsBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(HeliostatsBlock::new); + return BlockBehaviour.simpleCodec(HeliostatsBlock::new); } @Override @@ -51,7 +52,7 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return HeliostatsBlock.SHAPE; } @Override @@ -67,7 +68,7 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override protected VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return COLLISION_SHAPE; + return HeliostatsBlock.COLLISION_SHAPE; } @Nullable @@ -77,7 +78,7 @@ public BlockEntityTicker getTicker( BlockState state, BlockEntityType type ) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.HELIOSTATS.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.tick()); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/LoadMonitorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/LoadMonitorBlock.java index 44657f015a..7759e2a125 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/LoadMonitorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/LoadMonitorBlock.java @@ -15,6 +15,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BooleanProperty; @@ -39,17 +40,17 @@ public class LoadMonitorBlock extends BaseEntityBlock implements IHammerRemovabl public LoadMonitorBlock(Properties properties) { super(properties); - registerDefaultState(this.defaultBlockState().setValue(OVERLOAD, true).setValue(LOAD, 10)); + this.registerDefaultState(this.defaultBlockState().setValue(LoadMonitorBlock.OVERLOAD, true).setValue(LoadMonitorBlock.LOAD, 10)); } @Override protected MapCodec codec() { - return simpleCodec(LoadMonitorBlock::new); + return BlockBehaviour.simpleCodec(LoadMonitorBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(OVERLOAD, LOAD); + builder.add(LoadMonitorBlock.OVERLOAD, LoadMonitorBlock.LOAD); } @Override @@ -59,7 +60,7 @@ protected boolean isSignalSource(BlockState state) { @Override protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { - return state.getValue(OVERLOAD) ? 15 : 0; + return state.getValue(LoadMonitorBlock.OVERLOAD) ? 15 : 0; } @Override @@ -79,7 +80,7 @@ protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, @Override public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.LOAD_MONITOR.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.tick() @@ -99,7 +100,7 @@ public RenderShape getRenderShape(BlockState state) { @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return LoadMonitorBlock.SHAPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/PiezoelectricCrystalBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/PiezoelectricCrystalBlock.java index 5bc13452ae..6057e9ebf5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/PiezoelectricCrystalBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/PiezoelectricCrystalBlock.java @@ -26,14 +26,14 @@ public class PiezoelectricCrystalBlock extends Block implements IHammerRemovable public static final Map> ANVIL_TYPES = new HashMap<>(); static { - ANVIL_TYPES.put(ModBlocks.SPECTRAL_ANVIL.get(), List.of(1, 2, 3, 4)); - ANVIL_TYPES.put(ModBlocks.ROYAL_ANVIL.get(), List.of(1, 2, 4, 8)); - ANVIL_TYPES.put(Blocks.ANVIL, List.of(1, 2, 4, 8)); - ANVIL_TYPES.put(Blocks.CHIPPED_ANVIL, List.of(1, 2, 4, 8)); - ANVIL_TYPES.put(Blocks.DAMAGED_ANVIL, List.of(1, 2, 4, 8)); - ANVIL_TYPES.put(ModBlocks.EMBER_ANVIL.get(), List.of(1, 2, 5, 12)); - ANVIL_TYPES.put(ModBlocks.TRANSCENDENCE_ANVIL.get(), List.of(2, 5, 15, 60)); - ANVIL_TYPES.put(ModBlocks.GIANT_ANVIL.get(), List.of(1, 2, 3, 4, 5, 6, 7, 8)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(ModBlocks.SPECTRAL_ANVIL.get(), List.of(1, 2, 3, 4)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(ModBlocks.ROYAL_ANVIL.get(), List.of(1, 2, 4, 8)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(Blocks.ANVIL, List.of(1, 2, 4, 8)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(Blocks.CHIPPED_ANVIL, List.of(1, 2, 4, 8)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(Blocks.DAMAGED_ANVIL, List.of(1, 2, 4, 8)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(ModBlocks.EMBER_ANVIL.get(), List.of(1, 2, 5, 12)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(ModBlocks.TRANSCENDENCE_ANVIL.get(), List.of(2, 5, 15, 60)); + PiezoelectricCrystalBlock.ANVIL_TYPES.put(ModBlocks.GIANT_ANVIL.get(), List.of(1, 2, 3, 4, 5, 6, 7, 8)); } public static VoxelShape SHAPE = @@ -54,7 +54,7 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return PiezoelectricCrystalBlock.SHAPE; } @Override @@ -65,7 +65,7 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu /// 被铁砧砸事件 public void onHitByAnvil(FallingBlockEntity entity, float fallDistance, Level level, BlockPos blockPos) { if (level.getBlockTicks().hasScheduledTick(blockPos, this)) return; - List chargeNums = ANVIL_TYPES.get(entity.blockState.getBlock()); + List chargeNums = PiezoelectricCrystalBlock.ANVIL_TYPES.get(entity.blockState.getBlock()); if (chargeNums == null) return; int distance = (int) Math.min(chargeNums.size() - 1, fallDistance); int chargeNum = chargeNums.get(distance); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/batch/BaseBatchCraftingBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/batch/BaseBatchCraftingBlock.java index 000418022d..42fd1d43b7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/batch/BaseBatchCraftingBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/batch/BaseBatchCraftingBlock.java @@ -52,9 +52,9 @@ protected BaseBatchCraftingBlock(Properties properties) { this.registerDefaultState( this.stateDefinition .any() - .setValue(POWERED, false) - .setValue(OVERLOAD, true) - .setValue(FACING, Direction.NORTH) + .setValue(BaseBatchCraftingBlock.POWERED, false) + .setValue(BaseBatchCraftingBlock.OVERLOAD, true) + .setValue(BaseBatchCraftingBlock.FACING, Direction.NORTH) ); } @@ -158,14 +158,14 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { Direction dir = context.getNearestLookingDirection().getOpposite(); if (context.getPlayer() != null && context.getPlayer().isShiftKeyDown()) dir = dir.getOpposite(); return this.defaultBlockState() - .setValue(FACING, dir) - .setValue(POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())) - .setValue(OVERLOAD, true); + .setValue(BaseBatchCraftingBlock.FACING, dir) + .setValue(BaseBatchCraftingBlock.POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())) + .setValue(BaseBatchCraftingBlock.OVERLOAD, true); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED).add(OVERLOAD).add(FACING); + builder.add(BaseBatchCraftingBlock.POWERED).add(BaseBatchCraftingBlock.OVERLOAD).add(BaseBatchCraftingBlock.FACING); } @Override @@ -178,7 +178,7 @@ protected void neighborChanged( boolean movedByPiston ) { if (level.isClientSide()) return; - level.setBlock(pos, state.setValue(POWERED, level.hasNeighborSignal(pos)), 2); + level.setBlock(pos, state.setValue(BaseBatchCraftingBlock.POWERED, level.hasNeighborSignal(pos)), 2); } @Override @@ -188,19 +188,19 @@ public void tick( BlockPos pos, RandomSource random ) { - if (state.getValue(POWERED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(POWERED), 2); + if (state.getValue(BaseBatchCraftingBlock.POWERED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(BaseBatchCraftingBlock.POWERED), 2); } } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(BaseBatchCraftingBlock.FACING, rotation.rotate(state.getValue(BaseBatchCraftingBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(BaseBatchCraftingBlock.FACING))); } public static BlockState copy(BlockState from, BlockState to) { @@ -211,9 +211,9 @@ public static BlockState copy(BlockState from, BlockState to) { return to; } return to - .setValue(POWERED, from.getValue(POWERED)) - .setValue(OVERLOAD, from.getValue(OVERLOAD)) - .setValue(FACING, from.getValue(FACING)); + .setValue(BaseBatchCraftingBlock.POWERED, from.getValue(BaseBatchCraftingBlock.POWERED)) + .setValue(BaseBatchCraftingBlock.OVERLOAD, from.getValue(BaseBatchCraftingBlock.OVERLOAD)) + .setValue(BaseBatchCraftingBlock.FACING, from.getValue(BaseBatchCraftingBlock.FACING)); } private static final List> BATCH_CRAFTING_BLOCK_GETTERS = new ArrayList<>(); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/DischargerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/DischargerBlock.java index a479626ee7..320d756e5c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/DischargerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/DischargerBlock.java @@ -14,6 +14,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import org.jspecify.annotations.Nullable; @@ -25,7 +26,7 @@ public DischargerBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(DischargerBlock::new); + return BlockBehaviour.simpleCodec(DischargerBlock::new); } @Nullable @@ -42,7 +43,7 @@ public BlockEntityTicker getTicker( BlockEntityType type ) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.DISCHARGER.get(), (level1, blockPos, _, be) -> be.tick(level1, blockPos) diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ExpCollectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ExpCollectorBlock.java index 360c607f52..8c00291986 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ExpCollectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ExpCollectorBlock.java @@ -26,6 +26,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -41,13 +42,13 @@ public class ExpCollectorBlock extends BetterBaseEntityBlock implements IHammerR public ExpCollectorBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any() - .setValue(POWERED, false) - .setValue(OVERLOAD, true)); + .setValue(ExpCollectorBlock.POWERED, false) + .setValue(ExpCollectorBlock.OVERLOAD, true)); } @Override protected MapCodec codec() { - return simpleCodec(ExpCollectorBlock::new); + return BlockBehaviour.simpleCodec(ExpCollectorBlock::new); } @Override @@ -67,7 +68,7 @@ public boolean hasAnalogOutputSignal(BlockState blockState) { BlockEntityType type ) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.EXP_COLLECTOR.get(), (currentLevel, pos, currentState, blockEntity) -> blockEntity.tick(currentLevel, pos) @@ -78,13 +79,13 @@ public boolean hasAnalogOutputSignal(BlockState blockState) { public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { Level level = context.getLevel(); return this.defaultBlockState() - .setValue(POWERED, level.hasNeighborSignal(context.getClickedPos())) - .setValue(OVERLOAD, true); + .setValue(ExpCollectorBlock.POWERED, level.hasNeighborSignal(context.getClickedPos())) + .setValue(ExpCollectorBlock.OVERLOAD, true); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED, OVERLOAD); + builder.add(ExpCollectorBlock.POWERED, ExpCollectorBlock.OVERLOAD); } @Override @@ -139,13 +140,13 @@ protected void neighborChanged( boolean movedByPiston ) { if (level.isClientSide()) return; - level.setBlock(pos, state.setValue(POWERED, level.hasNeighborSignal(pos)), Block.UPDATE_CLIENTS); + level.setBlock(pos, state.setValue(ExpCollectorBlock.POWERED, level.hasNeighborSignal(pos)), Block.UPDATE_CLIENTS); } @Override public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (state.getValue(POWERED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(POWERED), Block.UPDATE_CLIENTS); + if (state.getValue(ExpCollectorBlock.POWERED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(ExpCollectorBlock.POWERED), Block.UPDATE_CLIENTS); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/HeaterBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/HeaterBlock.java index e0afbcc7c4..5fdb9fff86 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/HeaterBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/HeaterBlock.java @@ -18,6 +18,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -36,20 +37,20 @@ public class HeaterBlock extends BaseEntityBlock implements IHammerRemovable, ID public HeaterBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(POWERED, false).setValue(OVERLOAD, true)); + this.registerDefaultState(this.stateDefinition.any().setValue(HeaterBlock.POWERED, false).setValue(HeaterBlock.OVERLOAD, true)); } @Override protected MapCodec codec() { - return simpleCodec(HeaterBlock::new); + return BlockBehaviour.simpleCodec(HeaterBlock::new); } @Override @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())) - .setValue(OVERLOAD, true); + .setValue(HeaterBlock.POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())) + .setValue(HeaterBlock.OVERLOAD, true); } @Nullable @@ -60,7 +61,7 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED, OVERLOAD); + builder.add(HeaterBlock.POWERED, HeaterBlock.OVERLOAD); } @Override @@ -74,8 +75,8 @@ protected void neighborChanged( ) { if (level.isClientSide()) return; boolean powered = level.hasNeighborSignal(pos); - if (state.getValue(POWERED) != powered) { - level.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); + if (state.getValue(HeaterBlock.POWERED) != powered) { + level.setBlock(pos, state.setValue(HeaterBlock.POWERED, powered), Block.UPDATE_CLIENTS); } } @@ -89,7 +90,7 @@ public RenderShape getRenderShape(BlockState state) { public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.HEATER.get(), (level1, pos, state1, entity) -> entity.tick(level1, pos)); } @@ -101,7 +102,7 @@ public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { @Override public boolean isActive(BlockState state) { - return !state.getValue(POWERED) && !state.getValue(OVERLOAD); + return !state.getValue(HeaterBlock.POWERED) && !state.getValue(HeaterBlock.OVERLOAD); } @Override @@ -111,7 +112,7 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return HeaterBlock.SHAPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/InductionLightBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/InductionLightBlock.java index 92366b82b3..a1755c6dc2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/InductionLightBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/InductionLightBlock.java @@ -30,6 +30,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -57,34 +58,34 @@ public class InductionLightBlock extends BetterBaseEntityBlock implements IHamme @Override protected MapCodec codec() { - return simpleCodec(InductionLightBlock::new); + return BlockBehaviour.simpleCodec(InductionLightBlock::new); } public InductionLightBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(POWERED, false) - .setValue(OVERLOAD, true) - .setValue(AXIS, Direction.Axis.Y) - .setValue(WATERLOGGED, false) - .setValue(COLOR, LightColor.PRIMARY)); + .setValue(InductionLightBlock.POWERED, false) + .setValue(InductionLightBlock.OVERLOAD, true) + .setValue(InductionLightBlock.AXIS, Direction.Axis.Y) + .setValue(InductionLightBlock.WATERLOGGED, false) + .setValue(InductionLightBlock.COLOR, LightColor.PRIMARY)); } public static boolean isLit(BlockState state) { - return !(state.getValue(POWERED) || state.getValue(OVERLOAD)); + return !(state.getValue(InductionLightBlock.POWERED) || state.getValue(InductionLightBlock.OVERLOAD)); } public static boolean canCropGrow(BlockState state) { - return state.getValue(COLOR).equals(LightColor.PINK); + return state.getValue(InductionLightBlock.COLOR).equals(LightColor.PINK); } public static boolean canBlockMobSummoning(BlockState state) { - return state.getValue(COLOR).equals(LightColor.YELLOW); + return state.getValue(InductionLightBlock.COLOR).equals(LightColor.YELLOW); } public static boolean canBlockAnimalSummoning(BlockState state) { - return state.getValue(COLOR).equals(LightColor.DARK); + return state.getValue(InductionLightBlock.COLOR).equals(LightColor.DARK); } @Override @@ -94,10 +95,10 @@ public RenderShape getRenderShape(BlockState state) { @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(AXIS)) { - case Y -> SHAPE_Y; - case Z -> SHAPE_Z; - case X -> SHAPE_X; + return switch (state.getValue(InductionLightBlock.AXIS)) { + case Y -> InductionLightBlock.SHAPE_Y; + case Z -> InductionLightBlock.SHAPE_Z; + case X -> InductionLightBlock.SHAPE_X; }; } @@ -115,15 +116,15 @@ public boolean hasAnalogOutputSignal(BlockState blockState) { @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(POWERED, false) - .setValue(OVERLOAD, true) - .setValue(AXIS, context.getClickedFace().getAxis()) + .setValue(InductionLightBlock.POWERED, false) + .setValue(InductionLightBlock.OVERLOAD, true) + .setValue(InductionLightBlock.AXIS, context.getClickedFace().getAxis()) .setValue( - WATERLOGGED, + InductionLightBlock.WATERLOGGED, context.getLevel().getFluidState(context.getClickedPos()) .getType() == Fluids.WATER ) - .setValue(COLOR, LightColor.PRIMARY); + .setValue(InductionLightBlock.COLOR, LightColor.PRIMARY); } @Nullable @@ -134,12 +135,13 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); + return state.getValue(InductionLightBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED).add(OVERLOAD).add(AXIS).add(WATERLOGGED).add(COLOR); + builder.add(InductionLightBlock.POWERED).add( + InductionLightBlock.OVERLOAD).add(InductionLightBlock.AXIS).add(InductionLightBlock.WATERLOGGED).add(InductionLightBlock.COLOR); } @Override @@ -157,21 +159,21 @@ public InteractionResult use( return BlockPlaceAssist.tryPlace( state, level, pos, player, hand, hit, ModBlocks.INDUCTION_LIGHT.asItem(), - AXIS, + InductionLightBlock.AXIS, ModBlocks.INDUCTION_LIGHT.getDefaultState() ); } else if (itemInHand.is(Items.REDSTONE)) { - level.setBlockAndUpdate(pos, state.setValue(COLOR, LightColor.PINK)); + level.setBlockAndUpdate(pos, state.setValue(InductionLightBlock.COLOR, LightColor.PINK)); return InteractionResult.SUCCESS; } else if (itemInHand.is(Items.GLOWSTONE_DUST)) { - level.setBlockAndUpdate(pos, state.setValue(COLOR, LightColor.YELLOW)); + level.setBlockAndUpdate(pos, state.setValue(InductionLightBlock.COLOR, LightColor.YELLOW)); return InteractionResult.SUCCESS; } else if (itemInHand.is(ItemTags.AXES)) { - level.setBlockAndUpdate(pos, state.setValue(COLOR, LightColor.PRIMARY)); + level.setBlockAndUpdate(pos, state.setValue(InductionLightBlock.COLOR, LightColor.PRIMARY)); itemInHand.hurtAndBreak(1, player, hand); return InteractionResult.SUCCESS; } else if (itemInHand.is(ModItems.VOID_MATTER.asItem())) { - level.setBlockAndUpdate(pos, state.setValue(COLOR, LightColor.DARK)); + level.setBlockAndUpdate(pos, state.setValue(InductionLightBlock.COLOR, LightColor.DARK)); return InteractionResult.SUCCESS; } return super.use(state, level, pos, player, hand, hit); @@ -183,7 +185,7 @@ public BlockEntityTicker getTicker(Level level, Block if (level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.INDUCTION_LIGHT.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.tick(level1) @@ -200,9 +202,9 @@ protected void neighborChanged( boolean movedByPiston ) { if (level.isClientSide()) return; - if (state.getValue(WATERLOGGED)) level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); - if (state.getValue(OVERLOAD)) return; - level.setBlock(pos, state.setValue(POWERED, level.hasNeighborSignal(pos)), 2); + if (state.getValue(InductionLightBlock.WATERLOGGED)) level.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(level)); + if (state.getValue(InductionLightBlock.OVERLOAD)) return; + level.setBlock(pos, state.setValue(InductionLightBlock.POWERED, level.hasNeighborSignal(pos)), 2); } @Override @@ -212,8 +214,8 @@ public void tick( BlockPos pos, RandomSource random ) { - if (state.getValue(POWERED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(POWERED), 2); + if (state.getValue(InductionLightBlock.POWERED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(InductionLightBlock.POWERED), 2); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ItemCollectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ItemCollectorBlock.java index a35c339d9e..2fa80e11dc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ItemCollectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/ItemCollectorBlock.java @@ -22,7 +22,6 @@ import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.GameType; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; @@ -31,6 +30,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -43,8 +43,6 @@ import net.neoforged.neoforge.transfer.item.ItemResource; import org.jspecify.annotations.Nullable; -import java.util.List; - public class ItemCollectorBlock extends BetterBaseEntityBlock implements IHammerRemovable { public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public static final BooleanProperty OVERLOAD = IPowerComponent.OVERLOAD; @@ -54,14 +52,14 @@ public ItemCollectorBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition.any() - .setValue(POWERED, false) - .setValue(OVERLOAD, true) + .setValue(ItemCollectorBlock.POWERED, false) + .setValue(ItemCollectorBlock.OVERLOAD, true) ); } @Override protected MapCodec codec() { - return simpleCodec(ItemCollectorBlock::new); + return BlockBehaviour.simpleCodec(ItemCollectorBlock::new); } @Override @@ -103,7 +101,7 @@ public BlockEntityTicker getTicker( if (level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.ITEM_COLLECTOR.get(), (level1, blockPos, _, blockEntity) -> blockEntity.tick(level1, blockPos) @@ -115,13 +113,13 @@ public BlockEntityTicker getTicker( public BlockState getStateForPlacement(BlockPlaceContext context) { Level level = context.getLevel(); return this.defaultBlockState() - .setValue(POWERED, level.hasNeighborSignal(context.getClickedPos())) - .setValue(OVERLOAD, true); + .setValue(ItemCollectorBlock.POWERED, level.hasNeighborSignal(context.getClickedPos())) + .setValue(ItemCollectorBlock.OVERLOAD, true); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED).add(OVERLOAD); + builder.add(ItemCollectorBlock.POWERED).add(ItemCollectorBlock.OVERLOAD); } @Override @@ -167,13 +165,13 @@ protected void neighborChanged( if (level.isClientSide()) { return; } - level.setBlock(pos, state.setValue(POWERED, level.hasNeighborSignal(pos)), 2); + level.setBlock(pos, state.setValue(ItemCollectorBlock.POWERED, level.hasNeighborSignal(pos)), 2); } @Override public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (state.getValue(POWERED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(POWERED), 2); + if (state.getValue(ItemCollectorBlock.POWERED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(ItemCollectorBlock.POWERED), 2); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/SmartBlockPlacerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/SmartBlockPlacerBlock.java index dd89cfadbe..3f094a0634 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/SmartBlockPlacerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/SmartBlockPlacerBlock.java @@ -15,6 +15,7 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; @@ -51,23 +52,23 @@ public class SmartBlockPlacerBlock extends BetterBaseEntityBlock implements IHam ); // 使用 ShapeUtil.rotate 自动生成其他水平朝向 - private static final VoxelShape SHAPE_WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, SHAPE_NORTH); - private static final VoxelShape SHAPE_SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, SHAPE_NORTH); - private static final VoxelShape SHAPE_EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, SHAPE_NORTH); + private static final VoxelShape SHAPE_WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, SmartBlockPlacerBlock.SHAPE_NORTH); + private static final VoxelShape SHAPE_SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, SmartBlockPlacerBlock.SHAPE_NORTH); + private static final VoxelShape SHAPE_EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, SmartBlockPlacerBlock.SHAPE_NORTH); // 倒挂状态:使用 Axis.X 旋转 180 度实现 Y 轴翻转 - private static final VoxelShape SHAPE_NORTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_SOUTH); - private static final VoxelShape SHAPE_WEST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_WEST); - private static final VoxelShape SHAPE_SOUTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_NORTH); - private static final VoxelShape SHAPE_EAST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_EAST); + private static final VoxelShape SHAPE_NORTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SmartBlockPlacerBlock.SHAPE_SOUTH); + private static final VoxelShape SHAPE_WEST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SmartBlockPlacerBlock.SHAPE_WEST); + private static final VoxelShape SHAPE_SOUTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SmartBlockPlacerBlock.SHAPE_NORTH); + private static final VoxelShape SHAPE_EAST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SmartBlockPlacerBlock.SHAPE_EAST); public SmartBlockPlacerBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any() .setValue(HorizontalDirectionalBlock.FACING, Direction.NORTH) - .setValue(UPSIDE_DOWN, false) - .setValue(POWERED, false) - .setValue(OVERLOAD, true)); + .setValue(SmartBlockPlacerBlock.UPSIDE_DOWN, false) + .setValue(SmartBlockPlacerBlock.POWERED, false) + .setValue(SmartBlockPlacerBlock.OVERLOAD, true)); } public RenderShape getRenderShape(BlockState state) { @@ -80,8 +81,13 @@ protected MapCodec codec() { } @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HorizontalDirectionalBlock.FACING, UPSIDE_DOWN, POWERED, OVERLOAD); + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add( + HorizontalDirectionalBlock.FACING, + SmartBlockPlacerBlock.UPSIDE_DOWN, + SmartBlockPlacerBlock.POWERED, + SmartBlockPlacerBlock.OVERLOAD + ); } @Override @@ -100,9 +106,9 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() .setValue(HorizontalDirectionalBlock.FACING, horizontalFacing) - .setValue(UPSIDE_DOWN, upsideDown) - .setValue(POWERED, level.hasNeighborSignal(context.getClickedPos())) - .setValue(OVERLOAD, true); + .setValue(SmartBlockPlacerBlock.UPSIDE_DOWN, upsideDown) + .setValue(SmartBlockPlacerBlock.POWERED, level.hasNeighborSignal(context.getClickedPos())) + .setValue(SmartBlockPlacerBlock.OVERLOAD, true); } @Override @@ -113,13 +119,13 @@ public VoxelShape getShape( CollisionContext context ) { Direction facing = state.getValue(HorizontalDirectionalBlock.FACING); - boolean upsideDown = state.getValue(UPSIDE_DOWN); + boolean upsideDown = state.getValue(SmartBlockPlacerBlock.UPSIDE_DOWN); return switch (facing) { - case SOUTH -> upsideDown ? SHAPE_SOUTH_UPSIDE : SHAPE_SOUTH; - case WEST -> upsideDown ? SHAPE_WEST_UPSIDE : SHAPE_WEST; - case EAST -> upsideDown ? SHAPE_EAST_UPSIDE : SHAPE_EAST; - default -> upsideDown ? SHAPE_NORTH_UPSIDE : SHAPE_NORTH; + case SOUTH -> upsideDown ? SmartBlockPlacerBlock.SHAPE_SOUTH_UPSIDE : SmartBlockPlacerBlock.SHAPE_SOUTH; + case WEST -> upsideDown ? SmartBlockPlacerBlock.SHAPE_WEST_UPSIDE : SmartBlockPlacerBlock.SHAPE_WEST; + case EAST -> upsideDown ? SmartBlockPlacerBlock.SHAPE_EAST_UPSIDE : SmartBlockPlacerBlock.SHAPE_EAST; + default -> upsideDown ? SmartBlockPlacerBlock.SHAPE_NORTH_UPSIDE : SmartBlockPlacerBlock.SHAPE_NORTH; }; } @@ -181,7 +187,7 @@ protected void neighborChanged( if (level.isClientSide()) { return; } - level.setBlock(pos, state.setValue(POWERED, level.hasNeighborSignal(pos)), 2); + level.setBlock(pos, state.setValue(SmartBlockPlacerBlock.POWERED, level.hasNeighborSignal(pos)), 2); } @Override @@ -194,7 +200,7 @@ public BlockState playerWillDestroy(Level level, BlockPos pos, BlockState state, ItemStack stack = placerEntity.getDiskInventory().getItem(i); if (!stack.isEmpty()) { Vec3 vec3 = pos.getCenter(); - net.minecraft.world.entity.item.ItemEntity itemEntity = new net.minecraft.world.entity.item.ItemEntity( + ItemEntity itemEntity = new ItemEntity( level, vec3.x, vec3.y, @@ -211,7 +217,7 @@ public BlockState playerWillDestroy(Level level, BlockPos pos, BlockState state, ItemStack stack = placerEntity.getBookInventory().getItem(i); if (!stack.isEmpty()) { Vec3 vec3 = pos.getCenter(); - net.minecraft.world.entity.item.ItemEntity itemEntity = new net.minecraft.world.entity.item.ItemEntity( + ItemEntity itemEntity = new ItemEntity( level, vec3.x, vec3.y, @@ -229,8 +235,8 @@ public BlockState playerWillDestroy(Level level, BlockPos pos, BlockState state, @Override public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (state.getValue(POWERED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(POWERED), 2); + if (state.getValue(SmartBlockPlacerBlock.POWERED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(SmartBlockPlacerBlock.POWERED), 2); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/TeslaTowerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/TeslaTowerBlock.java index 24212c9871..3a5d4f0321 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/TeslaTowerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/consumer/TeslaTowerBlock.java @@ -57,9 +57,9 @@ public TeslaTowerBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(HALF, Vertical4PartHalf.BOTTOM) - .setValue(OVERLOAD, true) - .setValue(SWITCH, IPowerComponent.Switch.ON)); + .setValue(TeslaTowerBlock.HALF, Vertical4PartHalf.BOTTOM) + .setValue(TeslaTowerBlock.OVERLOAD, true) + .setValue(TeslaTowerBlock.SWITCH, IPowerComponent.Switch.ON)); } @Override @@ -80,14 +80,14 @@ public BlockState getPlacementState(BlockPlaceContext context) { IPowerComponent.Switch sw = level.hasNeighborSignal(pos) ? IPowerComponent.Switch.OFF : IPowerComponent.Switch.ON; return this.defaultBlockState() - .setValue(HALF, Vertical4PartHalf.BOTTOM) - .setValue(OVERLOAD, true) - .setValue(SWITCH, sw); + .setValue(TeslaTowerBlock.HALF, Vertical4PartHalf.BOTTOM) + .setValue(TeslaTowerBlock.OVERLOAD, true) + .setValue(TeslaTowerBlock.SWITCH, sw); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF).add(OVERLOAD).add(SWITCH); + builder.add(TeslaTowerBlock.HALF).add(TeslaTowerBlock.OVERLOAD).add(TeslaTowerBlock.SWITCH); } @Override @@ -101,11 +101,11 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(HALF)) { - case BOTTOM -> BOTTOM_SHAPE; - case MID_LOWER -> LOWER_SHAPE; - case MID_UPPER -> UPPER_SHAPE; - case TOP -> TOP_SHAPE; + return switch (state.getValue(TeslaTowerBlock.HALF)) { + case BOTTOM -> TeslaTowerBlock.BOTTOM_SHAPE; + case MID_LOWER -> TeslaTowerBlock.LOWER_SHAPE; + case MID_UPPER -> TeslaTowerBlock.UPPER_SHAPE; + case TOP -> TeslaTowerBlock.TOP_SHAPE; }; } @@ -116,7 +116,7 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public BlockState placedState(Vertical4PartHalf part, BlockState state) { - return super.placedState(part, state).setValue(SWITCH, IPowerComponent.Switch.ON); + return super.placedState(part, state).setValue(TeslaTowerBlock.SWITCH, IPowerComponent.Switch.ON); } @Override @@ -159,20 +159,20 @@ protected void neighborChanged( if (level.isClientSide()) { return; } - if (state.getValue(HALF) != Vertical4PartHalf.BOTTOM) return; + if (state.getValue(TeslaTowerBlock.HALF) != Vertical4PartHalf.BOTTOM) return; BlockPos topPos = pos.above(3); BlockState topState = level.getBlockState(topPos); if (!topState.is(ModBlocks.TESLA_TOWER.get())) return; - if (topState.getValue(HALF) != Vertical4PartHalf.TOP) return; - IPowerComponent.Switch sw = state.getValue(SWITCH); + if (topState.getValue(TeslaTowerBlock.HALF) != Vertical4PartHalf.TOP) return; + IPowerComponent.Switch sw = state.getValue(TeslaTowerBlock.SWITCH); boolean bl = sw == IPowerComponent.Switch.ON; if (bl == level.hasNeighborSignal(pos)) { if (bl) { - state = state.setValue(SWITCH, IPowerComponent.Switch.OFF); - topState = topState.setValue(SWITCH, IPowerComponent.Switch.OFF); + state = state.setValue(TeslaTowerBlock.SWITCH, IPowerComponent.Switch.OFF); + topState = topState.setValue(TeslaTowerBlock.SWITCH, IPowerComponent.Switch.OFF); } else { - state = state.setValue(SWITCH, IPowerComponent.Switch.ON); - topState = topState.setValue(SWITCH, IPowerComponent.Switch.ON); + state = state.setValue(TeslaTowerBlock.SWITCH, IPowerComponent.Switch.ON); + topState = topState.setValue(TeslaTowerBlock.SWITCH, IPowerComponent.Switch.ON); } level.setBlockAndUpdate(pos, state); level.setBlockAndUpdate(topPos, topState); @@ -199,7 +199,7 @@ protected InteractionResult useWithoutItem( return InteractionResult.SUCCESS; } if (state.is(this)) { - BlockPos mainPartPos = getMainPartPos(pos, state); + BlockPos mainPartPos = this.getMainPartPos(pos, state); BlockEntity blockEntity = level.getBlockEntity(mainPartPos); if (blockEntity instanceof TeslaTowerBlockEntity teslaTowerBlockEntity && player instanceof ServerPlayer sp) { if (sp.gameMode.getGameModeForPlayer() == GameType.SPECTATOR) return InteractionResult.PASS; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/BasePowerConverterBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/BasePowerConverterBlock.java index 568eafc55c..ad13a40f2b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/BasePowerConverterBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/BasePowerConverterBlock.java @@ -10,6 +10,7 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.RenderShape; @@ -38,36 +39,36 @@ public abstract class BasePowerConverterBlock extends BetterBaseEntityBlock impl /// 基本电源转换器模块 public BasePowerConverterBlock(Properties properties, int inputPower) { super(properties); - registerDefaultState( - stateDefinition.any() - .setValue(FACING, Direction.DOWN) - .setValue(POWERED, false) - .setValue(OVERLOAD, true) + this.registerDefaultState( + this.stateDefinition.any() + .setValue(BasePowerConverterBlock.FACING, Direction.DOWN) + .setValue(BasePowerConverterBlock.POWERED, false) + .setValue(BasePowerConverterBlock.OVERLOAD, true) ); this.inputPower = inputPower; } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED, OVERLOAD); + builder.add(BasePowerConverterBlock.FACING, BasePowerConverterBlock.POWERED, BasePowerConverterBlock.OVERLOAD); } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(BasePowerConverterBlock.FACING, rotation.rotate(state.getValue(BasePowerConverterBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(BasePowerConverterBlock.FACING))); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return defaultBlockState() - .setValue(FACING, context.getClickedFace().getOpposite()) - .setValue(POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); + return this.defaultBlockState() + .setValue(BasePowerConverterBlock.FACING, context.getClickedFace().getOpposite()) + .setValue(BasePowerConverterBlock.POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); } @Override @@ -81,8 +82,8 @@ protected void neighborChanged( ) { if (level.isClientSide()) return; boolean powered = level.hasNeighborSignal(pos); - if (state.getValue(POWERED) != powered) { - level.setBlock(pos, state.setValue(POWERED, powered), Block.UPDATE_CLIENTS); + if (state.getValue(BasePowerConverterBlock.POWERED) != powered) { + level.setBlock(pos, state.setValue(BasePowerConverterBlock.POWERED, powered), Block.UPDATE_CLIENTS); } } @@ -96,7 +97,7 @@ public BlockEntityTicker getTicker( if (level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.POWER_CONVERTER.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.tick() diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterBigBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterBigBlock.java index 7d33c77bec..d160fb9d34 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterBigBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterBigBlock.java @@ -6,6 +6,7 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; @@ -21,23 +22,23 @@ public class PowerConverterBigBlock extends BasePowerConverterBlock implements I public static final int INPUT_TIME = 256; public PowerConverterBigBlock(Properties properties) { - super(properties, INPUT_TIME); + super(properties, PowerConverterBigBlock.INPUT_TIME); } @Override protected MapCodec codec() { - return simpleCodec(PowerConverterBigBlock::new); + return BlockBehaviour.simpleCodec(PowerConverterBigBlock::new); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case UP -> SHAPE_UP; - case DOWN -> SHAPE_DOWN; - case NORTH -> SHAPE_NORTH; - case EAST -> SHAPE_EASE; - case SOUTH -> SHAPE_SOUTH; - case WEST -> SHAPE_WEST; + return switch (state.getValue(BasePowerConverterBlock.FACING)) { + case UP -> PowerConverterBigBlock.SHAPE_UP; + case DOWN -> PowerConverterBigBlock.SHAPE_DOWN; + case NORTH -> PowerConverterBigBlock.SHAPE_NORTH; + case EAST -> PowerConverterBigBlock.SHAPE_EASE; + case SOUTH -> PowerConverterBigBlock.SHAPE_SOUTH; + case WEST -> PowerConverterBigBlock.SHAPE_WEST; }; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterMiddleBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterMiddleBlock.java index 389feebdc3..f79963b6df 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterMiddleBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterMiddleBlock.java @@ -6,6 +6,7 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; @@ -21,23 +22,23 @@ public class PowerConverterMiddleBlock extends BasePowerConverterBlock implement public static final int INPUT_TIME = 16; public PowerConverterMiddleBlock(Properties properties) { - super(properties, INPUT_TIME); + super(properties, PowerConverterMiddleBlock.INPUT_TIME); } @Override protected MapCodec codec() { - return simpleCodec(PowerConverterMiddleBlock::new); + return BlockBehaviour.simpleCodec(PowerConverterMiddleBlock::new); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case UP -> SHAPE_UP; - case DOWN -> SHAPE_DOWN; - case NORTH -> SHAPE_NORTH; - case EAST -> SHAPE_EASE; - case SOUTH -> SHAPE_SOUTH; - case WEST -> SHAPE_WEST; + return switch (state.getValue(BasePowerConverterBlock.FACING)) { + case UP -> PowerConverterMiddleBlock.SHAPE_UP; + case DOWN -> PowerConverterMiddleBlock.SHAPE_DOWN; + case NORTH -> PowerConverterMiddleBlock.SHAPE_NORTH; + case EAST -> PowerConverterMiddleBlock.SHAPE_EASE; + case SOUTH -> PowerConverterMiddleBlock.SHAPE_SOUTH; + case WEST -> PowerConverterMiddleBlock.SHAPE_WEST; }; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterSmallBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterSmallBlock.java index 4535b0a6b3..8786a35a7e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterSmallBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/converter/PowerConverterSmallBlock.java @@ -6,6 +6,7 @@ import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; @@ -21,23 +22,23 @@ public class PowerConverterSmallBlock extends BasePowerConverterBlock implements public static final int INPUT_TIME = 1; public PowerConverterSmallBlock(Properties properties) { - super(properties, INPUT_TIME); + super(properties, PowerConverterSmallBlock.INPUT_TIME); } @Override protected MapCodec codec() { - return simpleCodec(PowerConverterSmallBlock::new); + return BlockBehaviour.simpleCodec(PowerConverterSmallBlock::new); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(FACING)) { - case UP -> SHAPE_UP; - case DOWN -> SHAPE_DOWN; - case NORTH -> SHAPE_NORTH; - case EAST -> SHAPE_EASE; - case SOUTH -> SHAPE_SOUTH; - case WEST -> SHAPE_WEST; + return switch (state.getValue(BasePowerConverterBlock.FACING)) { + case UP -> PowerConverterSmallBlock.SHAPE_UP; + case DOWN -> PowerConverterSmallBlock.SHAPE_DOWN; + case NORTH -> PowerConverterSmallBlock.SHAPE_NORTH; + case EAST -> PowerConverterSmallBlock.SHAPE_EASE; + case SOUTH -> PowerConverterSmallBlock.SHAPE_SOUTH; + case WEST -> PowerConverterSmallBlock.SHAPE_WEST; }; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargeCollectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargeCollectorBlock.java index 12ad2e6a85..0575e50b8b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargeCollectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargeCollectorBlock.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -33,17 +34,17 @@ public class ChargeCollectorBlock extends BetterBaseEntityBlock implements IHamm public ChargeCollectorBlock(Properties properties) { super(properties); - this.registerDefaultState(this.getStateDefinition().any().setValue(POWERED, false)); + this.registerDefaultState(this.getStateDefinition().any().setValue(ChargeCollectorBlock.POWERED, false)); } @Override protected MapCodec codec() { - return simpleCodec(ChargeCollectorBlock::new); + return BlockBehaviour.simpleCodec(ChargeCollectorBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED); + builder.add(ChargeCollectorBlock.POWERED); } @Override @@ -57,7 +58,7 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return SHAPE; + return ChargeCollectorBlock.SHAPE; } @Nullable @@ -67,30 +68,30 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { } public void activate(Level level, BlockPos pos, BlockState state) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, true)); + level.setBlockAndUpdate(pos, state.setValue(ChargeCollectorBlock.POWERED, true)); this.updateNeighbours(level, pos); level.scheduleTick(pos, this, 2); } @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (!state.getValue(POWERED)) return; - level.setBlockAndUpdate(pos, state.setValue(POWERED, false)); + if (!state.getValue(ChargeCollectorBlock.POWERED)) return; + level.setBlockAndUpdate(pos, state.setValue(ChargeCollectorBlock.POWERED, false)); this.updateNeighbours(level, pos); } @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean movedByPiston) { if (level.isClientSide() || state.is(oldState.getBlock())) return; - if (state.getValue(POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { - level.setBlock(pos, state.setValue(POWERED, false), 18); + if (state.getValue(ChargeCollectorBlock.POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { + level.setBlock(pos, state.setValue(ChargeCollectorBlock.POWERED, false), 18); } } @Override protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); - if (state.getValue(POWERED)) { + if (state.getValue(ChargeCollectorBlock.POWERED)) { this.updateNeighbours(level, pos); } } @@ -105,7 +106,7 @@ private void updateNeighbours(Level level, BlockPos pos) { public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.CHARGE_COLLECTOR.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.clientTick() diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargerBlock.java index cb55fde353..7bc02ae096 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/ChargerBlock.java @@ -28,6 +28,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -45,18 +46,22 @@ public class ChargerBlock extends BaseEntityBlock implements IHammerRemovable, I public ChargerBlock(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(POWERED, false).setValue(OVERLOAD, true)); + this.registerDefaultState( + this.getStateDefinition().any() + .setValue(ChargerBlock.POWERED, false) + .setValue(ChargerBlock.OVERLOAD, true) + ); } @Override protected MapCodec codec() { - return simpleCodec(ChargerBlock::new); + return BlockBehaviour.simpleCodec(ChargerBlock::new); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return defaultBlockState().setValue(POWERED, false).setValue(OVERLOAD, true); + return this.defaultBlockState().setValue(ChargerBlock.POWERED, false).setValue(ChargerBlock.OVERLOAD, true); } @Nullable @@ -69,7 +74,7 @@ public BlockEntityTicker getTicker( if (level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.CHARGER.get(), (level1, blockPos, _, be) -> be.tick(level1, blockPos) @@ -86,7 +91,7 @@ protected void neighborChanged( boolean movedByPiston ) { if (level.isClientSide()) return; - level.setBlock(pos, state.setValue(POWERED, level.hasNeighborSignal(pos)), 2); + level.setBlock(pos, state.setValue(ChargerBlock.POWERED, level.hasNeighborSignal(pos)), 2); } @Nullable @@ -97,7 +102,7 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED).add(OVERLOAD); + builder.add(ChargerBlock.POWERED).add(ChargerBlock.OVERLOAD); } @Override @@ -112,8 +117,8 @@ protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, @Override public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (state.getValue(POWERED) && !level.hasNeighborSignal(pos)) { - level.setBlock(pos, state.cycle(POWERED), 2); + if (state.getValue(ChargerBlock.POWERED) && !level.hasNeighborSignal(pos)) { + level.setBlock(pos, state.cycle(ChargerBlock.POWERED), 2); } } @@ -167,7 +172,7 @@ protected InteractionResult useItemOn( : ((DischargerBlockEntity) be).getFilteredItemStackHandler(); if (stack.isEmpty()) { - return tryExtract(player, level, pos, handler, be); + return ChargerBlock.tryExtract(player, level, pos, handler, be); } if (!handler.getStacks().get(0).isEmpty()) return InteractionResult.PASS; @@ -197,7 +202,7 @@ protected InteractionResult useWithoutItem(BlockState state, Level level, BlockP ? charger.getFilteredItemStackHandler() : ((DischargerBlockEntity) be).getFilteredItemStackHandler(); - return tryExtract(player, level, pos, handler, be); + return ChargerBlock.tryExtract(player, level, pos, handler, be); } private static InteractionResult tryExtract( diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/CreativeGeneratorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/CreativeGeneratorBlock.java index 0d8aec219b..d3bc18e79c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/CreativeGeneratorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/CreativeGeneratorBlock.java @@ -20,6 +20,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; @@ -36,7 +37,7 @@ public CreativeGeneratorBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(CreativeGeneratorBlock::new); + return BlockBehaviour.simpleCodec(CreativeGeneratorBlock::new); } @Override @@ -69,7 +70,7 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.CREATIVE_GENERATOR.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.tick() diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/FeCollectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/FeCollectorBlock.java index 1e64733223..6e2cbf01ee 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/FeCollectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/FeCollectorBlock.java @@ -21,6 +21,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -38,7 +39,7 @@ public class FeCollectorBlock extends BetterBaseEntityBlock implements HammerRot Block.box(0, 4, 4, 2, 12, 12), Block.box(14, 4, 4, 16, 12, 12) ); - private static final VoxelShape SHAPE_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, SHAPE_X); + private static final VoxelShape SHAPE_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, FeCollectorBlock.SHAPE_X); public static final EnumProperty AXIS = BlockStateProperties.HORIZONTAL_AXIS; public static BooleanProperty POWERED = BlockStateProperties.POWERED; @@ -47,19 +48,19 @@ public FeCollectorBlock(Properties properties) { this.registerDefaultState( this.getStateDefinition() .any() - .setValue(AXIS, Direction.Axis.X) - .setValue(POWERED, false) + .setValue(FeCollectorBlock.AXIS, Direction.Axis.X) + .setValue(FeCollectorBlock.POWERED, false) ); } @Override protected MapCodec codec() { - return simpleCodec(FeCollectorBlock::new); + return BlockBehaviour.simpleCodec(FeCollectorBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(AXIS).add(POWERED); + builder.add(FeCollectorBlock.AXIS).add(FeCollectorBlock.POWERED); } @Override @@ -70,15 +71,15 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { case WEST, EAST -> Direction.Axis.Z; default -> Direction.Axis.X; }; - return this.defaultBlockState().setValue(AXIS, axis); + return this.defaultBlockState().setValue(FeCollectorBlock.AXIS, axis); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { return switch (rotation) { - case COUNTERCLOCKWISE_90, CLOCKWISE_90 -> switch (state.getValue(AXIS)) { - case Z -> state.setValue(AXIS, Direction.Axis.X); - case X -> state.setValue(AXIS, Direction.Axis.Z); + case COUNTERCLOCKWISE_90, CLOCKWISE_90 -> switch (state.getValue(FeCollectorBlock.AXIS)) { + case Z -> state.setValue(FeCollectorBlock.AXIS, Direction.Axis.X); + case X -> state.setValue(FeCollectorBlock.AXIS, Direction.Axis.Z); default -> state; }; default -> state; @@ -97,7 +98,7 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return state.getValue(AXIS) == Direction.Axis.X ? SHAPE_X : SHAPE_Z; + return state.getValue(FeCollectorBlock.AXIS) == Direction.Axis.X ? FeCollectorBlock.SHAPE_X : FeCollectorBlock.SHAPE_Z; } @Nullable @@ -107,23 +108,23 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { } public void activate(Level level, BlockPos pos, BlockState state) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, true)); + level.setBlockAndUpdate(pos, state.setValue(FeCollectorBlock.POWERED, true)); this.updateNeighbours(level, pos); level.scheduleTick(pos, this, 2); } @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (!state.getValue(POWERED)) return; - level.setBlockAndUpdate(pos, state.setValue(POWERED, false)); + if (!state.getValue(FeCollectorBlock.POWERED)) return; + level.setBlockAndUpdate(pos, state.setValue(FeCollectorBlock.POWERED, false)); this.updateNeighbours(level, pos); } @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean movedByPiston) { if (level.isClientSide() || state.is(oldState.getBlock())) return; - if (state.getValue(POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { - level.setBlock(pos, state.setValue(POWERED, false), 18); + if (state.getValue(FeCollectorBlock.POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { + level.setBlock(pos, state.setValue(FeCollectorBlock.POWERED, false), 18); } } @@ -136,7 +137,7 @@ private void updateNeighbours(Level level, BlockPos pos) { @Override public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.FE_COLLECTOR.get(), FeCollectorBlockEntity::tick diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/HeatCollectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/HeatCollectorBlock.java index ed0fb067ee..9a1062d802 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/HeatCollectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/HeatCollectorBlock.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -31,17 +32,17 @@ public class HeatCollectorBlock extends BaseEntityBlock implements IHammerRemova public HeatCollectorBlock(Properties properties) { super(properties); - this.registerDefaultState(this.getStateDefinition().any().setValue(POWERED, false)); + this.registerDefaultState(this.getStateDefinition().any().setValue(HeatCollectorBlock.POWERED, false)); } @Override protected MapCodec codec() { - return simpleCodec(HeatCollectorBlock::new); + return BlockBehaviour.simpleCodec(HeatCollectorBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED); + builder.add(HeatCollectorBlock.POWERED); } @Override @@ -51,7 +52,7 @@ public RenderShape getRenderShape(BlockState state) { @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return HeatCollectorBlock.SHAPE; } @Override @@ -60,15 +61,15 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, } public void activate(Level level, BlockPos pos, BlockState state) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, true)); + level.setBlockAndUpdate(pos, state.setValue(HeatCollectorBlock.POWERED, true)); this.updateNeighbours(level, pos); level.scheduleTick(pos, this, 2); } @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (!state.getValue(POWERED)) return; - level.setBlockAndUpdate(pos, state.setValue(POWERED, false)); + if (!state.getValue(HeatCollectorBlock.POWERED)) return; + level.setBlockAndUpdate(pos, state.setValue(HeatCollectorBlock.POWERED, false)); this.updateNeighbours(level, pos); } @@ -83,8 +84,8 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean movedByPiston) { if (level.isClientSide() || state.is(oldState.getBlock())) return; - if (state.getValue(POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { - level.setBlock(pos, state.setValue(POWERED, false), 18); + if (state.getValue(HeatCollectorBlock.POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { + level.setBlock(pos, state.setValue(HeatCollectorBlock.POWERED, false), 18); } } @@ -96,7 +97,7 @@ private void updateNeighbours(Level level, BlockPos pos) { @Override protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); - if (state.getValue(POWERED)) { + if (state.getValue(HeatCollectorBlock.POWERED)) { this.updateNeighbours(level, pos); } } @@ -105,7 +106,7 @@ protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, @Override public BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.HEAT_COLLECTOR.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.clientTick()); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/InfiniteCollectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/InfiniteCollectorBlock.java index bb3fcbed6b..335052bbe7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/InfiniteCollectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/InfiniteCollectorBlock.java @@ -17,6 +17,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -32,17 +33,17 @@ public class InfiniteCollectorBlock extends BaseEntityBlock implements IHammerRe public InfiniteCollectorBlock(Properties properties) { super(properties); - this.registerDefaultState(this.getStateDefinition().any().setValue(POWERED, false)); + this.registerDefaultState(this.getStateDefinition().any().setValue(InfiniteCollectorBlock.POWERED, false)); } @Override protected MapCodec codec() { - return simpleCodec(InfiniteCollectorBlock::new); + return BlockBehaviour.simpleCodec(InfiniteCollectorBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED); + builder.add(InfiniteCollectorBlock.POWERED); } @Override @@ -52,7 +53,7 @@ public RenderShape getRenderShape(BlockState state) { @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return InfiniteCollectorBlock.SHAPE; } @Override @@ -69,30 +70,30 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, } public void activate(Level level, BlockPos pos, BlockState state) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, true)); + level.setBlockAndUpdate(pos, state.setValue(InfiniteCollectorBlock.POWERED, true)); this.updateNeighbours(level, pos); level.scheduleTick(pos, this, 2); } @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (!state.getValue(POWERED)) return; - level.setBlockAndUpdate(pos, state.setValue(POWERED, false)); + if (!state.getValue(InfiniteCollectorBlock.POWERED)) return; + level.setBlockAndUpdate(pos, state.setValue(InfiniteCollectorBlock.POWERED, false)); this.updateNeighbours(level, pos); } @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean movedByPiston) { if (level.isClientSide() || state.is(oldState.getBlock())) return; - if (state.getValue(POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { - level.setBlock(pos, state.setValue(POWERED, false), 18); + if (state.getValue(InfiniteCollectorBlock.POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { + level.setBlock(pos, state.setValue(InfiniteCollectorBlock.POWERED, false), 18); } } @Override protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); - if (state.getValue(POWERED)) { + if (state.getValue(InfiniteCollectorBlock.POWERED)) { this.updateNeighbours(level, pos); } } @@ -106,7 +107,7 @@ private void updateNeighbours(Level level, BlockPos pos) { @Override public BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.INFINITE_COLLECTOR.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.clientTick()); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/VoidEnergyCollectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/VoidEnergyCollectorBlock.java index 33509d7d21..9a08b4880c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/generator/VoidEnergyCollectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/generator/VoidEnergyCollectorBlock.java @@ -19,6 +19,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -42,7 +43,7 @@ public VoidEnergyCollectorBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(VoidEnergyCollectorBlock::new); + return BlockBehaviour.simpleCodec(VoidEnergyCollectorBlock::new); } @Nullable @@ -53,19 +54,19 @@ public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED); + builder.add(VoidEnergyCollectorBlock.POWERED); } public void activate(Level level, BlockPos pos, BlockState state) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, true)); + level.setBlockAndUpdate(pos, state.setValue(VoidEnergyCollectorBlock.POWERED, true)); this.updateNeighbours(level, pos); level.scheduleTick(pos, this, 2); } @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { - if (!state.getValue(POWERED)) return; - level.setBlockAndUpdate(pos, state.setValue(POWERED, false)); + if (!state.getValue(VoidEnergyCollectorBlock.POWERED)) return; + level.setBlockAndUpdate(pos, state.setValue(VoidEnergyCollectorBlock.POWERED, false)); this.updateNeighbours(level, pos); } @@ -77,15 +78,15 @@ private void updateNeighbours(Level level, BlockPos pos) { @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean movedByPiston) { if (level.isClientSide() || state.is(oldState.getBlock())) return; - if (state.getValue(POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { - level.setBlock(pos, state.setValue(POWERED, false), 18); + if (state.getValue(VoidEnergyCollectorBlock.POWERED) && !level.getBlockTicks().hasScheduledTick(pos, this)) { + level.setBlock(pos, state.setValue(VoidEnergyCollectorBlock.POWERED, false), 18); } } @Override protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); - if (state.getValue(POWERED)) { + if (state.getValue(VoidEnergyCollectorBlock.POWERED)) { this.updateNeighbours(level, pos); } } @@ -105,7 +106,7 @@ protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type) { if (level.isClientSide()) { - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.VOID_ENERGY_COLLECTOR.get(), (level1, blockPos, blockState, blockEntity) -> blockEntity.clientTick() @@ -125,6 +126,6 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return SHAPE; + return VoidEnergyCollectorBlock.SHAPE; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/ring/AccelerationRingBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/ring/AccelerationRingBlock.java index 9e98bfabf5..fbac0b340b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/ring/AccelerationRingBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/ring/AccelerationRingBlock.java @@ -62,23 +62,33 @@ public class AccelerationRingBlock new AABB(-10, 0, 0, 26, 16, 16) ); private static final Map> COLLISION_SHAPES = - makeCollisionShapes(); + AccelerationRingBlock.makeCollisionShapes(); public AccelerationRingBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(HALF, DirectionCube3x3PartHalf.BOTTOM_CENTER) - .setValue(FACING, Direction.NORTH) - .setValue(OVERLOAD, true) - .setValue(SWITCH, IPowerComponent.Switch.ON)); + .setValue(AccelerationRingBlock.HALF, DirectionCube3x3PartHalf.BOTTOM_CENTER) + .setValue(AccelerationRingBlock.FACING, Direction.NORTH) + .setValue(AccelerationRingBlock.OVERLOAD, true) + .setValue(AccelerationRingBlock.SWITCH, IPowerComponent.Switch.ON)); } private static Map> makeCollisionShapes() { Map> shapes = new EnumMap<>(Direction.Axis.class); - shapes.put(Direction.Axis.Y, makePartShapes(Y_AXIS_COLLISION_SHAPE)); - shapes.put(Direction.Axis.Z, makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 90, Y_AXIS_COLLISION_SHAPE))); - shapes.put(Direction.Axis.X, makePartShapes(ShapeUtil.rotate(Direction.Axis.Z, 90, Y_AXIS_COLLISION_SHAPE))); + shapes.put(Direction.Axis.Y, AccelerationRingBlock.makePartShapes(AccelerationRingBlock.Y_AXIS_COLLISION_SHAPE)); + shapes.put( + Direction.Axis.Z, + AccelerationRingBlock.makePartShapes( + ShapeUtil.rotate(Direction.Axis.X, 90, AccelerationRingBlock.Y_AXIS_COLLISION_SHAPE) + ) + ); + shapes.put( + Direction.Axis.X, + AccelerationRingBlock.makePartShapes( + ShapeUtil.rotate(Direction.Axis.Z, 90, AccelerationRingBlock.Y_AXIS_COLLISION_SHAPE) + ) + ); return shapes; } @@ -87,7 +97,7 @@ private static Map makePartShapes(VoxelSha for (DirectionCube3x3PartHalf part : DirectionCube3x3PartHalf.values()) { ArrayList partBoxes = new ArrayList<>(); for (AABB box : shape.toAabbs()) { - AABB clipped = clipToPart(scale16(box), part); + AABB clipped = AccelerationRingBlock.clipToPart(AccelerationRingBlock.scale16(box), part); if (clipped != null) partBoxes.add(clipped); } shapes.put( @@ -128,7 +138,7 @@ private static AABB clipToPart(AABB box, DirectionCube3x3PartHalf part) { @Override public Property getPart() { - return HALF; + return AccelerationRingBlock.HALF; } @Override @@ -138,12 +148,12 @@ public DirectionCube3x3PartHalf[] getParts() { @Override public EnumProperty getAdditionalProperty() { - return FACING; + return AccelerationRingBlock.FACING; } protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(OVERLOAD, SWITCH); + builder.add(AccelerationRingBlock.OVERLOAD, AccelerationRingBlock.SWITCH); } @Override @@ -156,7 +166,7 @@ public BlockState placedState(DirectionCube3x3PartHalf part, BlockState state) { public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { BlockState state = this.defaultBlockState() .setValue( - FACING, + AccelerationRingBlock.FACING, context.getPlayer() != null && context.getPlayer().isShiftKeyDown() ? context.getNearestLookingDirection().getOpposite() : context.getNearestLookingDirection() @@ -165,11 +175,11 @@ public BlockState placedState(DirectionCube3x3PartHalf part, BlockState state) { } public boolean isChannelWaterlogged(Level level, BlockPos mainPos, BlockState mainState) { - Direction.Axis axis = mainState.getValue(FACING).getAxis(); + Direction.Axis axis = mainState.getValue(AccelerationRingBlock.FACING).getAxis(); for (DirectionCube3x3PartHalf part : this.getParts()) { - if (!isChannelPart(part, axis)) continue; + if (!AccelerationRingBlock.isChannelPart(part, axis)) continue; BlockState partState = level.getBlockState(mainPos.offset(this.offsetFrom(mainState, part))); - if (partState.is(this) && partState.getValue(WATERLOGGED)) return true; + if (partState.is(this) && partState.getValue(WaterloggedFlexibleMultiPartBlock.WATERLOGGED)) return true; } return false; } @@ -196,11 +206,11 @@ protected void neighborChanged( pos.subtract(state.getValue(this.getPart()).getOffset()) .offset(it.getOffset()) )); - if (isSignal && state.getValue(SWITCH) == IPowerComponent.Switch.ON) { - updateState(level, pos, SWITCH, IPowerComponent.Switch.OFF, 3); - } else if (!isSignal && state.getValue(SWITCH) == IPowerComponent.Switch.OFF) { - updateState(level, pos, SWITCH, IPowerComponent.Switch.ON, 3); - BlockPos centerPos = pos.subtract(state.getValue(HALF).getOffset()).offset(0, 1, 0); + if (isSignal && state.getValue(AccelerationRingBlock.SWITCH) == IPowerComponent.Switch.ON) { + this.updateState(level, pos, AccelerationRingBlock.SWITCH, IPowerComponent.Switch.OFF, 3); + } else if (!isSignal && state.getValue(AccelerationRingBlock.SWITCH) == IPowerComponent.Switch.OFF) { + this.updateState(level, pos, AccelerationRingBlock.SWITCH, IPowerComponent.Switch.ON, 3); + BlockPos centerPos = pos.subtract(state.getValue(AccelerationRingBlock.HALF).getOffset()).offset(0, 1, 0); if (level.getBlockEntity(centerPos) instanceof IPowerConsumer powerConsumer) { if (powerConsumer.getGrid() == null) return; powerConsumer.getGrid().flush(); @@ -213,18 +223,18 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, if (context.isHoldingItem(state.getBlock().asItem())) { return Shapes.block(); } - return getPreciseShape(state); + return AccelerationRingBlock.getPreciseShape(state); } @Override protected VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return getPreciseShape(state); + return AccelerationRingBlock.getPreciseShape(state); } private static VoxelShape getPreciseShape(BlockState state) { - Direction.Axis axis = state.getValue(FACING).getAxis(); - if (isChannelPart(state.getValue(HALF), axis)) return Shapes.empty(); - return COLLISION_SHAPES.get(axis).get(state.getValue(HALF)); + Direction.Axis axis = state.getValue(AccelerationRingBlock.FACING).getAxis(); + if (AccelerationRingBlock.isChannelPart(state.getValue(AccelerationRingBlock.HALF), axis)) return Shapes.empty(); + return AccelerationRingBlock.COLLISION_SHAPES.get(axis).get(state.getValue(AccelerationRingBlock.HALF)); } @Override @@ -266,24 +276,24 @@ protected float getShadeBrightness(BlockState state, BlockGetter getter, BlockPo @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { - this.change(blockPos, level, state -> state.cycle(FACING)); + this.change(blockPos, level, state -> state.cycle(AccelerationRingBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return AccelerationRingBlock.FACING; } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)) - .setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(AccelerationRingBlock.HALF, state.getValue(AccelerationRingBlock.HALF).rotate(rotation)) + .setValue(AccelerationRingBlock.FACING, rotation.rotate(state.getValue(AccelerationRingBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)) - .setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(AccelerationRingBlock.HALF, state.getValue(AccelerationRingBlock.HALF).mirror(mirror)) + .setValue(AccelerationRingBlock.FACING, mirror.mirror(state.getValue(AccelerationRingBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/ring/DeflectionRingBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/ring/DeflectionRingBlock.java index 705e5dc8a6..02d3fe91e6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/ring/DeflectionRingBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/ring/DeflectionRingBlock.java @@ -59,23 +59,33 @@ public class DeflectionRingBlock new AABB(-3, 16, -16, 19, 32, 32) ); private static final Map> COLLISION_SHAPES = - makeCollisionShapes(); + DeflectionRingBlock.makeCollisionShapes(); public DeflectionRingBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(HALF, DirectionCube3x3PartHalf.BOTTOM_CENTER) - .setValue(FACING, Direction.NORTH) - .setValue(OVERLOAD, true) - .setValue(SWITCH, IPowerComponent.Switch.ON)); + .setValue(DeflectionRingBlock.HALF, DirectionCube3x3PartHalf.BOTTOM_CENTER) + .setValue(DeflectionRingBlock.FACING, Direction.NORTH) + .setValue(DeflectionRingBlock.OVERLOAD, true) + .setValue(DeflectionRingBlock.SWITCH, IPowerComponent.Switch.ON)); } private static Map> makeCollisionShapes() { Map> shapes = new EnumMap<>(Direction.Axis.class); - shapes.put(Direction.Axis.Y, makePartShapes(Y_AXIS_COLLISION_SHAPE)); - shapes.put(Direction.Axis.Z, makePartShapes(ShapeUtil.rotate(Direction.Axis.X, 90, Y_AXIS_COLLISION_SHAPE))); - shapes.put(Direction.Axis.X, makePartShapes(ShapeUtil.rotate(Direction.Axis.Z, 90, Y_AXIS_COLLISION_SHAPE))); + shapes.put(Direction.Axis.Y, DeflectionRingBlock.makePartShapes(DeflectionRingBlock.Y_AXIS_COLLISION_SHAPE)); + shapes.put( + Direction.Axis.Z, + DeflectionRingBlock.makePartShapes( + ShapeUtil.rotate(Direction.Axis.X, 90, DeflectionRingBlock.Y_AXIS_COLLISION_SHAPE) + ) + ); + shapes.put( + Direction.Axis.X, + DeflectionRingBlock.makePartShapes( + ShapeUtil.rotate(Direction.Axis.Z, 90, DeflectionRingBlock.Y_AXIS_COLLISION_SHAPE) + ) + ); return shapes; } @@ -84,7 +94,7 @@ private static Map makePartShapes(VoxelSha for (DirectionCube3x3PartHalf part : DirectionCube3x3PartHalf.values()) { ArrayList partBoxes = new ArrayList<>(); for (AABB box : shape.toAabbs()) { - AABB clipped = clipToPart(scale16(box), part); + AABB clipped = DeflectionRingBlock.clipToPart(DeflectionRingBlock.scale16(box), part); if (clipped != null) partBoxes.add(clipped); } shapes.put( @@ -125,7 +135,7 @@ private static AABB clipToPart(AABB box, DirectionCube3x3PartHalf part) { @Override public Property getPart() { - return HALF; + return DeflectionRingBlock.HALF; } @Override @@ -135,12 +145,12 @@ public DirectionCube3x3PartHalf[] getParts() { @Override public EnumProperty getAdditionalProperty() { - return FACING; + return DeflectionRingBlock.FACING; } protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(OVERLOAD, SWITCH); + builder.add(DeflectionRingBlock.OVERLOAD, DeflectionRingBlock.SWITCH); } @Override @@ -152,7 +162,7 @@ public BlockState placedState(DirectionCube3x3PartHalf part, BlockState state) { @Override public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { BlockState state = this.defaultBlockState().setValue( - FACING, + DeflectionRingBlock.FACING, context.getPlayer() != null && context.getPlayer().isShiftKeyDown() ? context.getNearestLookingDirection().getOpposite() : context.getNearestLookingDirection() @@ -161,11 +171,11 @@ public BlockState placedState(DirectionCube3x3PartHalf part, BlockState state) { } public boolean isChannelWaterlogged(Level level, BlockPos mainPos, BlockState mainState) { - Direction.Axis axis = mainState.getValue(FACING).getAxis(); + Direction.Axis axis = mainState.getValue(DeflectionRingBlock.FACING).getAxis(); for (DirectionCube3x3PartHalf part : this.getParts()) { - if (!isChannelPart(part, axis)) continue; + if (!DeflectionRingBlock.isChannelPart(part, axis)) continue; BlockState partState = level.getBlockState(mainPos.offset(this.offsetFrom(mainState, part))); - if (partState.is(this) && partState.getValue(WATERLOGGED)) return true; + if (partState.is(this) && partState.getValue(WaterloggedFlexibleMultiPartBlock.WATERLOGGED)) return true; } return false; } @@ -191,11 +201,11 @@ protected void neighborChanged( .anyMatch(it -> level.hasNeighborSignal( pos.subtract(state.getValue(this.getPart()).getOffset()).offset(it.getOffset()) )); - if (isSignal && state.getValue(SWITCH) == IPowerComponent.Switch.ON) { - updateState(level, pos, SWITCH, IPowerComponent.Switch.OFF, 3); - } else if (!isSignal && state.getValue(SWITCH) == IPowerComponent.Switch.OFF) { - updateState(level, pos, SWITCH, IPowerComponent.Switch.ON, 3); - BlockPos centerPos = pos.subtract(state.getValue(HALF).getOffset()).offset(0, 1, 0); + if (isSignal && state.getValue(DeflectionRingBlock.SWITCH) == IPowerComponent.Switch.ON) { + this.updateState(level, pos, DeflectionRingBlock.SWITCH, IPowerComponent.Switch.OFF, 3); + } else if (!isSignal && state.getValue(DeflectionRingBlock.SWITCH) == IPowerComponent.Switch.OFF) { + this.updateState(level, pos, DeflectionRingBlock.SWITCH, IPowerComponent.Switch.ON, 3); + BlockPos centerPos = pos.subtract(state.getValue(DeflectionRingBlock.HALF).getOffset()).offset(0, 1, 0); if (level.getBlockEntity(centerPos) instanceof IPowerConsumer powerConsumer) { if (powerConsumer.getGrid() == null) return; powerConsumer.getGrid().flush(); @@ -213,16 +223,18 @@ protected VoxelShape getShape( if (context.isHoldingItem(state.getBlock().asItem())) { return Shapes.block(); } - return getPreciseShape(state); + return DeflectionRingBlock.getPreciseShape(state); } @Override protected VoxelShape getCollisionShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return getPreciseShape(state); + return DeflectionRingBlock.getPreciseShape(state); } private static VoxelShape getPreciseShape(BlockState state) { - return COLLISION_SHAPES.get(state.getValue(FACING).getAxis()).get(state.getValue(HALF)); + return DeflectionRingBlock.COLLISION_SHAPES + .get(state.getValue(DeflectionRingBlock.FACING).getAxis()) + .get(state.getValue(DeflectionRingBlock.HALF)); } @Override @@ -272,24 +284,24 @@ protected float getShadeBrightness(BlockState state, BlockGetter getter, BlockPo @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { - this.change(blockPos, level, state -> state.cycle(FACING)); + this.change(blockPos, level, state -> state.cycle(DeflectionRingBlock.FACING)); return true; } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return DeflectionRingBlock.FACING; } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)) - .setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(DeflectionRingBlock.HALF, state.getValue(DeflectionRingBlock.HALF).rotate(rotation)) + .setValue(DeflectionRingBlock.FACING, rotation.rotate(state.getValue(DeflectionRingBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)) - .setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(DeflectionRingBlock.HALF, state.getValue(DeflectionRingBlock.HALF).mirror(mirror)) + .setValue(DeflectionRingBlock.FACING, mirror.mirror(state.getValue(DeflectionRingBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/RemoteTransmissionPoleBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/RemoteTransmissionPoleBlock.java index 215ed7451a..bff1c44cfb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/RemoteTransmissionPoleBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/RemoteTransmissionPoleBlock.java @@ -50,9 +50,9 @@ public RemoteTransmissionPoleBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(HALF, Vertical4PartHalf.BOTTOM) - .setValue(OVERLOAD, true) - .setValue(SWITCH, IPowerComponent.Switch.ON)); + .setValue(RemoteTransmissionPoleBlock.HALF, Vertical4PartHalf.BOTTOM) + .setValue(RemoteTransmissionPoleBlock.OVERLOAD, true) + .setValue(RemoteTransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON)); } @Override @@ -73,14 +73,14 @@ public BlockState getPlacementState(BlockPlaceContext context) { IPowerComponent.Switch sw = level.hasNeighborSignal(pos) ? IPowerComponent.Switch.OFF : IPowerComponent.Switch.ON; return this.defaultBlockState() - .setValue(HALF, Vertical4PartHalf.BOTTOM) - .setValue(OVERLOAD, true) - .setValue(SWITCH, sw); + .setValue(RemoteTransmissionPoleBlock.HALF, Vertical4PartHalf.BOTTOM) + .setValue(RemoteTransmissionPoleBlock.OVERLOAD, true) + .setValue(RemoteTransmissionPoleBlock.SWITCH, sw); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF).add(OVERLOAD).add(SWITCH); + builder.add(RemoteTransmissionPoleBlock.HALF).add(RemoteTransmissionPoleBlock.OVERLOAD).add(RemoteTransmissionPoleBlock.SWITCH); } @Override @@ -94,10 +94,10 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(HALF)) { - case BOTTOM -> TRANSMISSION_POLE_BASE; - case MID_UPPER, MID_LOWER -> TRANSMISSION_POLE_MID; - case TOP -> TRANSMISSION_POLE_TOP; + return switch (state.getValue(RemoteTransmissionPoleBlock.HALF)) { + case BOTTOM -> RemoteTransmissionPoleBlock.TRANSMISSION_POLE_BASE; + case MID_UPPER, MID_LOWER -> RemoteTransmissionPoleBlock.TRANSMISSION_POLE_MID; + case TOP -> RemoteTransmissionPoleBlock.TRANSMISSION_POLE_TOP; }; } @@ -108,7 +108,7 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public BlockState placedState(Vertical4PartHalf part, BlockState state) { - return super.placedState(part, state).setValue(SWITCH, IPowerComponent.Switch.ON); + return super.placedState(part, state).setValue(RemoteTransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON); } @Override @@ -147,20 +147,20 @@ protected void neighborChanged( if (level.isClientSide()) { return; } - if (state.getValue(HALF) != Vertical4PartHalf.BOTTOM) return; + if (state.getValue(RemoteTransmissionPoleBlock.HALF) != Vertical4PartHalf.BOTTOM) return; BlockPos topPos = pos.above(3); BlockState topState = level.getBlockState(topPos); if (!topState.is(ModBlocks.REMOTE_TRANSMISSION_POLE.get())) return; - if (topState.getValue(HALF) != Vertical4PartHalf.TOP) return; - IPowerComponent.Switch sw = state.getValue(SWITCH); + if (topState.getValue(RemoteTransmissionPoleBlock.HALF) != Vertical4PartHalf.TOP) return; + IPowerComponent.Switch sw = state.getValue(RemoteTransmissionPoleBlock.SWITCH); boolean bl = sw == IPowerComponent.Switch.ON; if (bl == level.hasNeighborSignal(pos)) { if (bl) { - state = state.setValue(SWITCH, IPowerComponent.Switch.OFF); - topState = topState.setValue(SWITCH, IPowerComponent.Switch.OFF); + state = state.setValue(RemoteTransmissionPoleBlock.SWITCH, IPowerComponent.Switch.OFF); + topState = topState.setValue(RemoteTransmissionPoleBlock.SWITCH, IPowerComponent.Switch.OFF); } else { - state = state.setValue(SWITCH, IPowerComponent.Switch.ON); - topState = topState.setValue(SWITCH, IPowerComponent.Switch.ON); + state = state.setValue(RemoteTransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON); + topState = topState.setValue(RemoteTransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON); } level.setBlockAndUpdate(pos, state); level.setBlockAndUpdate(topPos, topState); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/TransmissionPoleBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/TransmissionPoleBlock.java index 7a58ec654e..31b999e830 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/TransmissionPoleBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/power/transmitting/TransmissionPoleBlock.java @@ -49,9 +49,9 @@ public TransmissionPoleBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(HALF, Vertical3PartHalf.BOTTOM) - .setValue(OVERLOAD, true) - .setValue(SWITCH, IPowerComponent.Switch.ON)); + .setValue(TransmissionPoleBlock.HALF, Vertical3PartHalf.BOTTOM) + .setValue(TransmissionPoleBlock.OVERLOAD, true) + .setValue(TransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON)); } @Override @@ -72,14 +72,14 @@ public BlockState getPlacementState(BlockPlaceContext context) { IPowerComponent.Switch sw = level.hasNeighborSignal(pos) ? IPowerComponent.Switch.OFF : IPowerComponent.Switch.ON; return this.defaultBlockState() - .setValue(HALF, Vertical3PartHalf.BOTTOM) - .setValue(OVERLOAD, true) - .setValue(SWITCH, sw); + .setValue(TransmissionPoleBlock.HALF, Vertical3PartHalf.BOTTOM) + .setValue(TransmissionPoleBlock.OVERLOAD, true) + .setValue(TransmissionPoleBlock.SWITCH, sw); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF).add(OVERLOAD).add(SWITCH); + builder.add(TransmissionPoleBlock.HALF).add(TransmissionPoleBlock.OVERLOAD).add(TransmissionPoleBlock.SWITCH); } @Override @@ -94,9 +94,9 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - if (state.getValue(HALF) == Vertical3PartHalf.BOTTOM) return TRANSMISSION_POLE_BASE; - if (state.getValue(HALF) == Vertical3PartHalf.MID) return TRANSMISSION_POLE_MID; - if (state.getValue(HALF) == Vertical3PartHalf.TOP) return TRANSMISSION_POLE_TOP; + if (state.getValue(TransmissionPoleBlock.HALF) == Vertical3PartHalf.BOTTOM) return TransmissionPoleBlock.TRANSMISSION_POLE_BASE; + if (state.getValue(TransmissionPoleBlock.HALF) == Vertical3PartHalf.MID) return TransmissionPoleBlock.TRANSMISSION_POLE_MID; + if (state.getValue(TransmissionPoleBlock.HALF) == Vertical3PartHalf.TOP) return TransmissionPoleBlock.TRANSMISSION_POLE_TOP; return super.getShape(state, level, pos, context); } @@ -107,7 +107,7 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public BlockState placedState(Vertical3PartHalf part, BlockState state) { - return super.placedState(part, state).setValue(SWITCH, IPowerComponent.Switch.ON); + return super.placedState(part, state).setValue(TransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON); } @Override @@ -136,20 +136,20 @@ protected void neighborChanged( boolean movedByPiston ) { if (level.isClientSide()) return; - if (state.getValue(HALF) != Vertical3PartHalf.BOTTOM) return; + if (state.getValue(TransmissionPoleBlock.HALF) != Vertical3PartHalf.BOTTOM) return; BlockPos topPos = pos.above(2); BlockState topState = level.getBlockState(topPos); if (!topState.is(ModBlocks.TRANSMISSION_POLE.get())) return; - if (topState.getValue(HALF) != Vertical3PartHalf.TOP) return; - IPowerComponent.Switch sw = state.getValue(SWITCH); + if (topState.getValue(TransmissionPoleBlock.HALF) != Vertical3PartHalf.TOP) return; + IPowerComponent.Switch sw = state.getValue(TransmissionPoleBlock.SWITCH); boolean bl = sw == IPowerComponent.Switch.ON; if (bl == level.hasNeighborSignal(pos)) { if (bl) { - state = state.setValue(SWITCH, IPowerComponent.Switch.OFF); - topState = topState.setValue(SWITCH, IPowerComponent.Switch.OFF); + state = state.setValue(TransmissionPoleBlock.SWITCH, IPowerComponent.Switch.OFF); + topState = topState.setValue(TransmissionPoleBlock.SWITCH, IPowerComponent.Switch.OFF); } else { - state = state.setValue(SWITCH, IPowerComponent.Switch.ON); - topState = topState.setValue(SWITCH, IPowerComponent.Switch.ON); + state = state.setValue(TransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON); + topState = topState.setValue(TransmissionPoleBlock.SWITCH, IPowerComponent.Switch.ON); } level.setBlockAndUpdate(pos, state); level.setBlockAndUpdate(topPos, topState); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/production/CrabTrapBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/production/CrabTrapBlock.java index 5cdbc9a0ed..78aa5816c3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/production/CrabTrapBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/production/CrabTrapBlock.java @@ -45,11 +45,11 @@ public class CrabTrapBlock extends Block implements SimpleWaterloggedBlock, IHam public CrabTrapBlock(Properties properties) { super(properties); - registerDefaultState( - getStateDefinition().any() - .setValue(FACING, Direction.NORTH) - .setValue(WATERLOGGED, false) - .setValue(FISHING, 0) + this.registerDefaultState( + this.getStateDefinition().any() + .setValue(CrabTrapBlock.FACING, Direction.NORTH) + .setValue(CrabTrapBlock.WATERLOGGED, false) + .setValue(CrabTrapBlock.FISHING, 0) ); } @@ -57,9 +57,9 @@ public CrabTrapBlock(Properties properties) { @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(FACING, context.getHorizontalDirection().getOpposite()) + .setValue(CrabTrapBlock.FACING, context.getHorizontalDirection().getOpposite()) .setValue( - WATERLOGGED, + CrabTrapBlock.WATERLOGGED, context.getLevel() .getFluidState(context.getClickedPos()) .getType() @@ -68,17 +68,17 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, WATERLOGGED, FISHING); + builder.add(CrabTrapBlock.FACING, CrabTrapBlock.WATERLOGGED, CrabTrapBlock.FISHING); } @Override public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); + return state.getValue(CrabTrapBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); } @Override public boolean isRandomlyTicking(BlockState state) { - return state.getValue(WATERLOGGED); + return state.getValue(CrabTrapBlock.WATERLOGGED); } @Override @@ -94,8 +94,8 @@ public void randomTick( } } - if (times >= 3 && state.getValue(FISHING) < 15) { - level.setBlock(pos, state.setValue(FISHING, state.getValue(FISHING) + 1), 2); + if (times >= 3 && state.getValue(CrabTrapBlock.FISHING) < 15) { + level.setBlock(pos, state.setValue(CrabTrapBlock.FISHING, state.getValue(CrabTrapBlock.FISHING) + 1), 2); } } @@ -106,7 +106,7 @@ protected boolean hasAnalogOutputSignal(BlockState state) { @Override protected int getAnalogOutputSignal(BlockState state, Level level, BlockPos pos, Direction direction) { - return state.getValue(FISHING); + return state.getValue(CrabTrapBlock.FISHING); } @Override @@ -115,13 +115,13 @@ protected InteractionResult useWithoutItem(BlockState state, Level level, BlockP return InteractionResult.PASS; } List items = new ObjectArrayList<>(); - for (int i = 1; i < state.getValue(FISHING) + 1; i++) { - items.addAll(generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_COMMON)); - items.addAll(generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_RIVER)); - items.addAll(generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_OCEAN)); - items.addAll(generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_WARM_OCEAN)); - items.addAll(generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_SWAMP)); - items.addAll(generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_JUNGLE)); + for (int i = 1; i < state.getValue(CrabTrapBlock.FISHING) + 1; i++) { + items.addAll(CrabTrapBlock.generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_COMMON)); + items.addAll(CrabTrapBlock.generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_RIVER)); + items.addAll(CrabTrapBlock.generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_OCEAN)); + items.addAll(CrabTrapBlock.generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_WARM_OCEAN)); + items.addAll(CrabTrapBlock.generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_SWAMP)); + items.addAll(CrabTrapBlock.generateLoot((ServerLevel) level, pos, ModLootTables.CRAB_TRAP_JUNGLE)); if (i % 5 == 0) { items.add(ModItems.CRAB_CLAW.asStack()); } @@ -132,18 +132,18 @@ protected InteractionResult useWithoutItem(BlockState state, Level level, BlockP itemEntity.setDefaultPickUpDelay(); level.addFreshEntity(itemEntity); } - level.setBlockAndUpdate(pos, state.setValue(FISHING, 0)); + level.setBlockAndUpdate(pos, state.setValue(CrabTrapBlock.FISHING, 0)); return InteractionResult.CONSUME; } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(CrabTrapBlock.FACING, rotation.rotate(state.getValue(CrabTrapBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(CrabTrapBlock.FACING))); } public static List generateLoot(ServerLevel level, BlockPos pos, ResourceKey loot) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/production/MineralFountainBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/production/MineralFountainBlock.java index 4d86357220..0d3504a0c8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/production/MineralFountainBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/production/MineralFountainBlock.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import org.jspecify.annotations.Nullable; @@ -26,7 +27,7 @@ public MineralFountainBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(MineralFountainBlock::new); + return BlockBehaviour.simpleCodec(MineralFountainBlock::new); } @Nullable @@ -40,7 +41,7 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { public BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType blockEntityType) { if (level.isClientSide()) return null; - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( blockEntityType, ModBlockEntities.MINERAL_FOUNTAIN.get(), (_, _, _, entity) -> entity.tick()); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/special/BlackHoleBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/special/BlackHoleBlock.java index cb71c6558e..5576c47ff8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/special/BlackHoleBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/special/BlackHoleBlock.java @@ -21,7 +21,7 @@ public BlackHoleBlock(Properties properties) { @Override public VoxelShape getShape(BlockState blockState, BlockGetter blockGetter, BlockPos blockPos, CollisionContext collisionContext) { - return MODEL; + return BlackHoleBlock.MODEL; } @Override @@ -34,4 +34,4 @@ public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldS public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new BlackHoleBlockEntity(pos, state); } -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/block/special/PlasmaJetsBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/special/PlasmaJetsBlock.java index aac7ad0d59..69c268154b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/special/PlasmaJetsBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/special/PlasmaJetsBlock.java @@ -17,6 +17,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; @@ -30,7 +31,7 @@ public PlasmaJetsBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(PlasmaJetsBlock::new); + return BlockBehaviour.simpleCodec(PlasmaJetsBlock::new); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") @@ -72,7 +73,7 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, @Override public @Nullable BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { - return createTickerHelper(type, ModBlockEntities.PLASMA_JETS.get(), PlasmaJetsBlockEntity::tick); + return BaseEntityBlock.createTickerHelper(type, ModBlockEntities.PLASMA_JETS.get(), PlasmaJetsBlockEntity::tick); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/special/WhiteHoleBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/special/WhiteHoleBlock.java index 2851a798b8..827a676221 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/special/WhiteHoleBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/special/WhiteHoleBlock.java @@ -18,7 +18,7 @@ public class WhiteHoleBlock extends Block implements EntityBlock { @Override public VoxelShape getShape(BlockState blockState, BlockGetter blockGetter, BlockPos blockPos, CollisionContext collisionContext) { - return MODEL; + return WhiteHoleBlock.MODEL; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/Color.java b/src/main/java/dev/dubhe/anvilcraft/block/state/Color.java index 575ccde30d..18a457480b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/Color.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/Color.java @@ -56,44 +56,44 @@ public String getSerializedName() { @Nullable public static Color getColorByDyeItem(Item dyeItem) { if (dyeItem == Items.BLACK_DYE) { - return BLACK; + return Color.BLACK; } else if (dyeItem == Items.BLUE_DYE) { - return BLUE; + return Color.BLUE; } else if (dyeItem == Items.BROWN_DYE) { - return BROWN; + return Color.BROWN; } else if (dyeItem == Items.CYAN_DYE) { - return CYAN; + return Color.CYAN; } else if (dyeItem == Items.GRAY_DYE) { - return GRAY; + return Color.GRAY; } else if (dyeItem == Items.GREEN_DYE) { - return GREEN; + return Color.GREEN; } else if (dyeItem == Items.LIGHT_BLUE_DYE) { - return LIGHT_BLUE; + return Color.LIGHT_BLUE; } else if (dyeItem == Items.LIGHT_GRAY_DYE) { - return LIGHT_GRAY; + return Color.LIGHT_GRAY; } else if (dyeItem == Items.LIME_DYE) { - return LIME; + return Color.LIME; } else if (dyeItem == Items.MAGENTA_DYE) { - return MAGENTA; + return Color.MAGENTA; } else if (dyeItem == Items.ORANGE_DYE) { - return ORANGE; + return Color.ORANGE; } else if (dyeItem == Items.PINK_DYE) { - return PINK; + return Color.PINK; } else if (dyeItem == Items.PURPLE_DYE) { - return PURPLE; + return Color.PURPLE; } else if (dyeItem == Items.RED_DYE) { - return RED; + return Color.RED; } else if (dyeItem == Items.WHITE_DYE) { - return WHITE; + return Color.WHITE; } else if (dyeItem == Items.YELLOW_DYE) { - return YELLOW; + return Color.YELLOW; } else { return null; } } public static Color getColorByIndex(int index) { - Color[] values = values(); + Color[] values = Color.values(); if (index >= 0 && index < values.length) { return values[index]; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/Cube3x3PartHalf.java b/src/main/java/dev/dubhe/anvilcraft/block/state/Cube3x3PartHalf.java index 9241ae8443..0fa85abfef 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/Cube3x3PartHalf.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/Cube3x3PartHalf.java @@ -62,11 +62,11 @@ public static Cube3x3PartHalf findByOffset(int offsetX, int offsetY, int offsetZ int x = half.offsetX; int y = half.offsetY; int z = half.offsetZ; - half.clockwise90 = findByOffset(-z, y, x); - half.clockwise180 = findByOffset(-x, y, -z); - half.clockwise270 = findByOffset(z, y, -x); - half.mirrorX = findByOffset(-x, y, z); - half.mirrorZ = findByOffset(x, y, -z); + half.clockwise90 = Cube3x3PartHalf.findByOffset(-z, y, x); + half.clockwise180 = Cube3x3PartHalf.findByOffset(-x, y, -z); + half.clockwise270 = Cube3x3PartHalf.findByOffset(z, y, -x); + half.mirrorX = Cube3x3PartHalf.findByOffset(-x, y, z); + half.mirrorZ = Cube3x3PartHalf.findByOffset(x, y, -z); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube232PartHalf.java b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube232PartHalf.java index 6008e734e1..eb9cd96ebb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube232PartHalf.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube232PartHalf.java @@ -49,11 +49,11 @@ public static DirectionCube232PartHalf findByOffset(int offsetX, int offsetY, in int x = half.offsetX; int y = half.offsetY; int z = half.offsetZ; - half.clockwise90 = findByOffset(-z, y, x); - half.clockwise180 = findByOffset(-x, y, -z); - half.clockwise270 = findByOffset(z, y, -x); - half.mirrorX = findByOffset(-x, y, z); - half.mirrorZ = findByOffset(x, y, -z); + half.clockwise90 = DirectionCube232PartHalf.findByOffset(-z, y, x); + half.clockwise180 = DirectionCube232PartHalf.findByOffset(-x, y, -z); + half.clockwise270 = DirectionCube232PartHalf.findByOffset(z, y, -x); + half.mirrorX = DirectionCube232PartHalf.findByOffset(-x, y, z); + half.mirrorZ = DirectionCube232PartHalf.findByOffset(x, y, -z); } } @@ -90,7 +90,7 @@ public int getOffsetZ(Direction value) { @Override public boolean isMain() { - return this == BOTTOM_PART; + return this == DirectionCube232PartHalf.BOTTOM_PART; } public DirectionCube232PartHalf rotate(Rotation rotation) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube3x3PartHalf.java b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube3x3PartHalf.java index c208569e49..3b0ac54190 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube3x3PartHalf.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionCube3x3PartHalf.java @@ -64,11 +64,11 @@ public static DirectionCube3x3PartHalf findByOffset(int offsetX, int offsetY, in int x = half.offsetX; int y = half.offsetY; int z = half.offsetZ; - half.clockwise90 = findByOffset(-z, y, x); - half.clockwise180 = findByOffset(-x, y, -z); - half.clockwise270 = findByOffset(z, y, -x); - half.mirrorX = findByOffset(-x, y, z); - half.mirrorZ = findByOffset(x, y, -z); + half.clockwise90 = DirectionCube3x3PartHalf.findByOffset(-z, y, x); + half.clockwise180 = DirectionCube3x3PartHalf.findByOffset(-x, y, -z); + half.clockwise270 = DirectionCube3x3PartHalf.findByOffset(z, y, -x); + half.mirrorX = DirectionCube3x3PartHalf.findByOffset(-x, y, z); + half.mirrorZ = DirectionCube3x3PartHalf.findByOffset(x, y, -z); } } @@ -105,7 +105,7 @@ public int getOffsetZ(Direction value) { @Override public boolean isMain() { - return this == MID_CENTER; + return this == DirectionCube3x3PartHalf.MID_CENTER; } public DirectionCube3x3PartHalf rotate(Rotation rotation) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionGate331PartHalf.java b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionGate331PartHalf.java index 0b8bd99ec2..b9d14216a6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionGate331PartHalf.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionGate331PartHalf.java @@ -50,7 +50,7 @@ public int getOffsetZ(Direction facing) { @Override public boolean isMain() { - return this == BOTTOM_CENTER; + return this == DirectionGate331PartHalf.BOTTOM_CENTER; } public boolean isCenterColumn() { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionVertical2PartHalf.java b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionVertical2PartHalf.java index d6f6a1f51e..acfebcaf00 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionVertical2PartHalf.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/DirectionVertical2PartHalf.java @@ -37,7 +37,7 @@ public int getOffsetZ(Direction value) { @Override public boolean isMain() { - return this == BOTTOM; + return this == DirectionVertical2PartHalf.BOTTOM; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/FacingWithAxis.java b/src/main/java/dev/dubhe/anvilcraft/block/state/FacingWithAxis.java index 1b0cf153ce..3cd2560c09 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/FacingWithAxis.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/FacingWithAxis.java @@ -38,12 +38,12 @@ public String getSerializedName() { } public static FacingWithAxis of(Direction facing, Direction.Axis axis) { - for (FacingWithAxis fwa : values()) { + for (FacingWithAxis fwa : FacingWithAxis.values()) { if (fwa.facing == facing && fwa.axis == axis) { return fwa; } } - return NORTH_X; + return FacingWithAxis.NORTH_X; } public FacingWithAxis rotate(Rotation rotation) { @@ -53,27 +53,27 @@ public FacingWithAxis rotate(Rotation rotation) { Direction axisDir = Direction.fromAxisAndDirection(this.axis, Direction.AxisDirection.POSITIVE); newAxis = rotation.rotate(axisDir).getAxis(); } - return of(newFacing, newAxis); + return FacingWithAxis.of(newFacing, newAxis); } public FacingWithAxis mirror(Mirror mirror) { - return of(mirror.mirror(this.facing), this.axis); + return FacingWithAxis.of(mirror.mirror(this.facing), this.axis); } public FacingWithAxis toggleAxis() { return switch (this) { - case NORTH_X -> NORTH_Y; - case NORTH_Y -> NORTH_X; - case SOUTH_X -> SOUTH_Y; - case SOUTH_Y -> SOUTH_X; - case EAST_Z -> EAST_Y; - case EAST_Y -> EAST_Z; - case WEST_Z -> WEST_Y; - case WEST_Y -> WEST_Z; - case UP_X -> UP_Z; - case UP_Z -> UP_X; - case DOWN_X -> DOWN_Z; - case DOWN_Z -> DOWN_X; + case NORTH_X -> FacingWithAxis.NORTH_Y; + case NORTH_Y -> FacingWithAxis.NORTH_X; + case SOUTH_X -> FacingWithAxis.SOUTH_Y; + case SOUTH_Y -> FacingWithAxis.SOUTH_X; + case EAST_Z -> FacingWithAxis.EAST_Y; + case EAST_Y -> FacingWithAxis.EAST_Z; + case WEST_Z -> FacingWithAxis.WEST_Y; + case WEST_Y -> FacingWithAxis.WEST_Z; + case UP_X -> FacingWithAxis.UP_Z; + case UP_Z -> FacingWithAxis.UP_X; + case DOWN_X -> FacingWithAxis.DOWN_Z; + case DOWN_Z -> FacingWithAxis.DOWN_X; }; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/FragmentationDegree.java b/src/main/java/dev/dubhe/anvilcraft/block/state/FragmentationDegree.java index 09df344af7..6575c12b4e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/FragmentationDegree.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/FragmentationDegree.java @@ -23,9 +23,9 @@ public String getSerializedName() { public FragmentationDegree next() { return switch (this) { - case ZERO -> ONE; - case ONE -> TWO; - case TWO, THREE -> THREE; + case ZERO -> FragmentationDegree.ONE; + case ONE -> FragmentationDegree.TWO; + case TWO, THREE -> FragmentationDegree.THREE; }; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/state/OpenedCube3x3PartHalf.java b/src/main/java/dev/dubhe/anvilcraft/block/state/OpenedCube3x3PartHalf.java index f16f408cf0..0b0854dcbe 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/state/OpenedCube3x3PartHalf.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/state/OpenedCube3x3PartHalf.java @@ -6,6 +6,7 @@ import org.jspecify.annotations.Nullable; import java.util.Arrays; +import java.util.Objects; @Getter public enum OpenedCube3x3PartHalf implements IFlexibleMultiPartBlockState, @@ -63,11 +64,11 @@ public static OpenedCube3x3PartHalf findByOffset(int offsetX, int offsetY, int o int x = half.offsetX; int y = half.offsetY; int z = half.offsetZ; - half.clockwise90 = findByOffset(-z, y, x); - half.clockwise180 = findByOffset(-x, y, -z); - half.clockwise270 = findByOffset(z, y, -x); - half.mirrorX = findByOffset(-x, y, z); - half.mirrorZ = findByOffset(x, y, -z); + half.clockwise90 = Objects.requireNonNull(OpenedCube3x3PartHalf.findByOffset(-z, y, x)); + half.clockwise180 = Objects.requireNonNull(OpenedCube3x3PartHalf.findByOffset(-x, y, -z)); + half.clockwise270 = Objects.requireNonNull(OpenedCube3x3PartHalf.findByOffset(z, y, -x)); + half.mirrorX = Objects.requireNonNull(OpenedCube3x3PartHalf.findByOffset(-x, y, z)); + half.mirrorZ = Objects.requireNonNull(OpenedCube3x3PartHalf.findByOffset(x, y, -z)); } } @@ -76,6 +77,11 @@ public static OpenedCube3x3PartHalf findByOffset(int offsetX, int offsetY, int o this.offsetX = offsetX; this.offsetY = offsetY; this.offsetZ = offsetZ; + this.clockwise90 = this; + this.clockwise180 = this; + this.clockwise270 = this; + this.mirrorX = this; + this.mirrorZ = this; } public String toString() { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/AmberBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/AmberBlock.java index 0b1baa6a33..5f6653bb81 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/AmberBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/AmberBlock.java @@ -5,6 +5,7 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.HorizontalDirectionalBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.EnumProperty; @@ -16,23 +17,23 @@ public class AmberBlock extends HorizontalDirectionalBlock { public AmberBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any() - .setValue(FACING, Direction.NORTH)); + .setValue(AmberBlock.FACING, Direction.NORTH)); } @Override protected MapCodec codec() { - return simpleCodec(AmberBlock::new); + return BlockBehaviour.simpleCodec(AmberBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING); + builder.add(AmberBlock.FACING); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { Direction facing = context.getHorizontalDirection().getOpposite(); - return this.defaultBlockState().setValue(FACING, facing); + return this.defaultBlockState().setValue(AmberBlock.FACING, facing); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/ExcitedStateVoidMatterBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/ExcitedStateVoidMatterBlock.java index 622bceda24..f8b09b8c5d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/ExcitedStateVoidMatterBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/ExcitedStateVoidMatterBlock.java @@ -9,6 +9,7 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.redstone.Orientation; +import org.jspecify.annotations.Nullable; import java.util.ArrayList; import java.util.List; @@ -31,7 +32,7 @@ protected void neighborChanged( Level level, BlockPos pos, Block neighborBlock, - Orientation orientation, + @Nullable Orientation orientation, boolean movedByPiston ) { if (!level.isClientSide()) { @@ -66,7 +67,7 @@ private void triggerDecayChain(Level level, BlockPos pos) { private void decaySelf(Level level, BlockPos pos) { RandomSource random = level.getRandom(); - List decayProducts = getDecayProducts(); + List decayProducts = ExcitedStateVoidMatterBlock.getDecayProducts(); BlockState decayResult = decayProducts.get(random.nextInt(decayProducts.size())).defaultBlockState(); level.setBlockAndUpdate(pos, decayResult); @@ -78,7 +79,7 @@ private void decaySelf(Level level, BlockPos pos) { } } if (!adjacentChambers.isEmpty()) { - List confinedAnvilons = getConfinedAnvilons(); + List confinedAnvilons = ExcitedStateVoidMatterBlock.getConfinedAnvilons(); BlockPos targetPos = adjacentChambers.get(random.nextInt(adjacentChambers.size())); Block anvilon = confinedAnvilons.get(random.nextInt(confinedAnvilons.size())); level.setBlockAndUpdate(targetPos, anvilon.defaultBlockState()); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/FerriteCoreMagnetBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/FerriteCoreMagnetBlock.java index 441c89a3b6..d0602be429 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/FerriteCoreMagnetBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/FerriteCoreMagnetBlock.java @@ -32,8 +32,8 @@ public void randomTick( } if (randomSource.nextInt(7) <= times) { BlockState blockState1 = ModBlocks.MAGNET_BLOCK.get().defaultBlockState(); - if (blockState1.hasProperty(LIT)) { - blockState1 = blockState1.setValue(LIT, serverLevel.hasNeighborSignal(blockPos)); + if (blockState1.hasProperty(MagnetBlock.LIT)) { + blockState1 = blockState1.setValue(MagnetBlock.LIT, serverLevel.hasNeighborSignal(blockPos)); } serverLevel.setBlockAndUpdate(blockPos, blockState1); } @@ -46,8 +46,8 @@ protected InteractionResult useWithoutItem(BlockState state, Level level, BlockP if (player.isShiftKeyDown()) { player.addItem(Items.IRON_INGOT.getDefaultInstance()); BlockState blockState = ModBlocks.HOLLOW_MAGNET_BLOCK.get().defaultBlockState(); - if (blockState.hasProperty(LIT)) { - blockState = blockState.setValue(LIT, level.hasNeighborSignal(pos)); + if (blockState.hasProperty(MagnetBlock.LIT)) { + blockState = blockState.setValue(MagnetBlock.LIT, level.hasNeighborSignal(pos)); } level.setBlockAndUpdate(pos, blockState); level.playSound(null, pos, SoundEvents.ITEM_FRAME_REMOVE_ITEM, SoundSource.BLOCKS, 1.0F, 1.0F); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/FlintBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/FlintBlock.java index 1024463f43..b4f3265317 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/FlintBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/FlintBlock.java @@ -79,7 +79,7 @@ public static void ignite(LevelAccessor level, BlockPos pos, boolean isFlint) { @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean movedByPiston) { if (movedByPiston) { - ignite(level, pos, true); + FlintBlock.ignite(level, pos, true); } } @@ -87,7 +87,7 @@ protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState o protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); if (movedByPiston) { - ignite(level, pos, true); + FlintBlock.ignite(level, pos, true); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/HollowMagnetBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/HollowMagnetBlock.java index 162920fd43..9e3f549840 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/HollowMagnetBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/HollowMagnetBlock.java @@ -41,17 +41,21 @@ public class HollowMagnetBlock extends MagnetBlock implements SimpleWaterloggedB public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; public static final String TAG = AnvilCraft.MOD_ID + ":hollow_magnet_block"; private static final VoxelShape REDUCE_AABB = Block.box(5.0, 0.0, 5.0, 11.0, 16.0, 11.0); - private static final VoxelShape AABB = Shapes.join(Shapes.block(), REDUCE_AABB, BooleanOp.ONLY_FIRST); + private static final VoxelShape AABB = Shapes.join(Shapes.block(), HollowMagnetBlock.REDUCE_AABB, BooleanOp.ONLY_FIRST); public HollowMagnetBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, false).setValue(LIT, false)); + this.registerDefaultState( + this.stateDefinition.any() + .setValue(HollowMagnetBlock.WATERLOGGED, false) + .setValue(MagnetBlock.LIT, false) + ); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(WATERLOGGED); + builder.add(HollowMagnetBlock.WATERLOGGED); } @Override @@ -61,7 +65,7 @@ public VoxelShape getShape( BlockGetter blockGetter, BlockPos blockPos, CollisionContext collisionContext) { - return AABB; + return HollowMagnetBlock.AABB; } @Override @@ -85,12 +89,12 @@ public BlockState getStateForPlacement(BlockPlaceContext blockPlaceContext) { FluidState fluidState = blockPlaceContext.getLevel().getFluidState(blockPos); BlockState state = super.getStateForPlacement(blockPlaceContext); state = null != state ? state : this.defaultBlockState(); - return state.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); + return state.setValue(HollowMagnetBlock.WATERLOGGED, fluidState.getType() == Fluids.WATER); } @Override public FluidState getFluidState(BlockState blockState) { - return blockState.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(blockState); + return blockState.getValue(HollowMagnetBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(blockState); } @Override @@ -104,7 +108,7 @@ protected BlockState updateShape( BlockState blockState2, RandomSource random ) { - if (blockState.getValue(WATERLOGGED)) { + if (blockState.getValue(HollowMagnetBlock.WATERLOGGED)) { ticks.scheduleTick(blockPos, Fluids.WATER, Fluids.WATER.getTickDelay(levelReader)); } return super.updateShape(blockState, levelReader, ticks, blockPos, direction, blockPos2, blockState2, random); @@ -122,14 +126,14 @@ protected void entityInside( if (level.isClientSide()) { return; } - if (state.getValue(LIT)) { + if (state.getValue(MagnetBlock.LIT)) { return; } if (entity instanceof ItemEntity itemEntity /*&& !itemEntity.getItem().tags().anyMatch(it -> it.equals(TAG))*/) { ItemStack item = itemEntity.getItem(); if (item.is(Items.IRON_INGOT) && item.getCount() == 1) { if (itemEntity.getOwner() instanceof ServerPlayer) { - itemEntity.addTag(TAG); + itemEntity.addTag(HollowMagnetBlock.TAG); if (level.getRandom().nextDouble() <= 0.005) { itemEntity.setItem(new ItemStack(ModItems.MAGNET_INGOT.get())); } @@ -152,8 +156,8 @@ protected InteractionResult useItemOn( if (stack.is(Items.IRON_INGOT)) { stack.consume(1, player); BlockState blockState = ModBlocks.FERRITE_CORE_MAGNET_BLOCK.get().defaultBlockState(); - if (blockState.hasProperty(LIT)) { - blockState = blockState.setValue(LIT, level.hasNeighborSignal(pos)); + if (blockState.hasProperty(MagnetBlock.LIT)) { + blockState = blockState.setValue(MagnetBlock.LIT, level.hasNeighborSignal(pos)); } level.setBlockAndUpdate(pos, blockState); level.playSound(null, pos, SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, 1.0F, 1.0F); @@ -161,8 +165,8 @@ protected InteractionResult useItemOn( } else if (stack.is(ModItems.MAGNET_INGOT)) { stack.consume(1, player); BlockState blockState = ModBlocks.MAGNET_BLOCK.get().defaultBlockState(); - if (blockState.hasProperty(LIT)) { - blockState = blockState.setValue(LIT, level.hasNeighborSignal(pos)); + if (blockState.hasProperty(MagnetBlock.LIT)) { + blockState = blockState.setValue(MagnetBlock.LIT, level.hasNeighborSignal(pos)); } level.setBlockAndUpdate(pos, blockState); level.playSound(null, pos, SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, 1.0F, 1.0F); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/LevitationPowderBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/LevitationPowderBlock.java index 7253d4fa0e..a1e4409085 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/LevitationPowderBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/LevitationPowderBlock.java @@ -12,6 +12,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.FallingBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.redstone.Orientation; import net.minecraft.world.phys.Vec3; @@ -26,7 +27,7 @@ public LevitationPowderBlock(Properties properties) { @Override protected MapCodec codec() { - return null; + return BlockBehaviour.simpleCodec(LevitationPowderBlock::new); } @Override @@ -37,7 +38,7 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou Vec3.atCenterOf(pos), GravityManager.getFallingBlockGravityType(this) ); - if (gravity.lengthSqr() < MIN_GRAVITY_SQR) return; + if (gravity.lengthSqr() < LevitationPowderBlock.MIN_GRAVITY_SQR) return; Direction gravityDirection = Direction.getApproximateNearest(gravity.x, gravity.y, gravity.z); BlockPos targetPos = pos.relative(gravityDirection); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetBlock.java index dc1c1bc82d..655f3e7795 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetBlock.java @@ -38,13 +38,13 @@ public class MagnetBlock extends Block implements IHammerRemovable { public MagnetBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(LIT, false)); + this.registerDefaultState(this.stateDefinition.any().setValue(MagnetBlock.LIT, false)); } @Override @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { - return this.defaultBlockState().setValue(LIT, context.getLevel().hasNeighborSignal(context.getClickedPos())); + return this.defaultBlockState().setValue(MagnetBlock.LIT, context.getLevel().hasNeighborSignal(context.getClickedPos())); } @Override @@ -62,7 +62,7 @@ public void onPlace( @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(LIT); + builder.add(MagnetBlock.LIT); } @Override @@ -78,19 +78,19 @@ protected void neighborChanged( return; } this.attract(state, level, pos); - boolean bl = state.getValue(LIT); + boolean bl = state.getValue(MagnetBlock.LIT); if (bl != level.hasNeighborSignal(pos)) { if (bl) { level.scheduleTick(pos, this, 4); } else { - level.setBlockAndUpdate(pos, state.cycle(LIT)); + level.setBlockAndUpdate(pos, state.cycle(MagnetBlock.LIT)); } } } private void attract(BlockState state, Level level, BlockPos magnetPos) { if (level.isClientSide()) return; - if (!(state.getBlock() instanceof MagnetBlock) || state.getValue(LIT)) return; + if (!(state.getBlock() instanceof MagnetBlock) || state.getValue(MagnetBlock.LIT)) return; if (level.getBlockState(magnetPos.below()).is(BlockTags.ANVIL)) return; int distance = AnvilCraft.CONFIG.magnetAttractsDistance; BlockPos currentPos = magnetPos; @@ -157,8 +157,8 @@ public void tick( ServerLevel level, BlockPos pos, RandomSource random) { - if (state.getValue(LIT) && !level.hasNeighborSignal(pos)) { - level.setBlockAndUpdate(pos, state.cycle(LIT)); + if (state.getValue(MagnetBlock.LIT) && !level.hasNeighborSignal(pos)) { + level.setBlockAndUpdate(pos, state.cycle(MagnetBlock.LIT)); } } @@ -169,8 +169,8 @@ protected InteractionResult useWithoutItem(BlockState state, Level level, BlockP if (player.isShiftKeyDown()) { player.addItem(ModItems.MAGNET_INGOT.get().getDefaultInstance()); BlockState blockState = ModBlocks.HOLLOW_MAGNET_BLOCK.get().defaultBlockState(); - if (blockState.hasProperty(LIT)) { - blockState = blockState.setValue(LIT, level.hasNeighborSignal(pos)); + if (blockState.hasProperty(MagnetBlock.LIT)) { + blockState = blockState.setValue(MagnetBlock.LIT, level.hasNeighborSignal(pos)); } level.setBlockAndUpdate(pos, blockState); level.playSound(null, pos, SoundEvents.ITEM_FRAME_REMOVE_ITEM, SoundSource.BLOCKS, 1.0F, 1.0F); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetoElectricCoreBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetoElectricCoreBlock.java index 22973ba224..5dafc941fd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetoElectricCoreBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/MagnetoElectricCoreBlock.java @@ -5,14 +5,15 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; public class MagnetoElectricCoreBlock extends Block implements IHammerRemovable { - public static final MapCodec CODEC = simpleCodec(MagnetoElectricCoreBlock::new); - public static final VoxelShape SHAPE = box(2, 2, 2, 14, 14, 14); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(MagnetoElectricCoreBlock::new); + public static final VoxelShape SHAPE = Block.box(2, 2, 2, 14, 14, 14); public MagnetoElectricCoreBlock(Properties properties) { super(properties); @@ -20,7 +21,7 @@ public MagnetoElectricCoreBlock(Properties properties) { @Override protected MapCodec codec() { - return CODEC; + return MagnetoElectricCoreBlock.CODEC; } @Override @@ -30,7 +31,7 @@ protected VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return SHAPE; + return MagnetoElectricCoreBlock.SHAPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/MobAmberBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/MobAmberBlock.java index 09fe456dc5..ffc6372423 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/MobAmberBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/MobAmberBlock.java @@ -13,6 +13,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -25,35 +26,35 @@ public class MobAmberBlock extends HasMobBlock { public MobAmberBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any() - .setValue(FACING, Direction.NORTH)); + .setValue(MobAmberBlock.FACING, Direction.NORTH)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING); + builder.add(MobAmberBlock.FACING); } @Override protected MapCodec codec() { - return simpleCodec(MobAmberBlock::new); + return BlockBehaviour.simpleCodec(MobAmberBlock::new); } @Override protected BlockState rotate(BlockState state, Rotation rot) { - return state.setValue(FACING, rot.rotate(state.getValue(FACING))); + return state.setValue(MobAmberBlock.FACING, rot.rotate(state.getValue(MobAmberBlock.FACING))); } @Override @SuppressWarnings("deprecation") protected BlockState mirror(BlockState state, Mirror mirror) { - return state.rotate(mirror.getRotation(state.getValue(FACING))); + return state.rotate(mirror.getRotation(state.getValue(MobAmberBlock.FACING))); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { Direction facing = context.getHorizontalDirection().getOpposite(); - return this.defaultBlockState().setValue(FACING, facing); + return this.defaultBlockState().setValue(MobAmberBlock.FACING, facing); } @Nullable @@ -72,7 +73,7 @@ public BlockEntityTicker getTicker( if (!level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.MOB_AMBER_BLOCK.get(), (level1, blockPos, _, blockEntity) -> blockEntity.clientTick(level1, blockPos) diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/ResentfulAmberBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/ResentfulAmberBlock.java index 2e46583acb..6e0e0db493 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/ResentfulAmberBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/ResentfulAmberBlock.java @@ -3,6 +3,7 @@ import dev.dubhe.anvilcraft.init.block.ModBlockEntities; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -27,7 +28,7 @@ public BlockEntityTicker getTicker( if (!level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( type, ModBlockEntities.RESENTFUL_AMBER_BLOCK.get(), (level1, blockPos, _, blockEntity) -> blockEntity.clientTick(level1, blockPos) diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/SugarBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/SugarBlock.java index a97aeab128..4653f490a9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/SugarBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/SugarBlock.java @@ -30,7 +30,7 @@ public class SugarBlock extends Block { public SugarBlock(Properties properties) { super(properties); - this.stateDefinition.any().setValue(FRAGMENTATION_DEGREE, FragmentationDegree.ZERO); + this.stateDefinition.any().setValue(SugarBlock.FRAGMENTATION_DEGREE, FragmentationDegree.ZERO); } public static void loot(RegistrumBlockLootTables tables, Block block) { @@ -66,9 +66,15 @@ public void onHit(Level level, BlockPos pos) { protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { double chance = random.nextDouble(); if (!level.isClientSide()) { - if (state.getValue(FRAGMENTATION_DEGREE) != FragmentationDegree.THREE) { + if (state.getValue(SugarBlock.FRAGMENTATION_DEGREE) != FragmentationDegree.THREE) { if (chance <= 0.05) { - level.setBlockAndUpdate(pos, state.setValue(FRAGMENTATION_DEGREE, state.getValue(FRAGMENTATION_DEGREE).next())); + level.setBlockAndUpdate( + pos, + state.setValue( + SugarBlock.FRAGMENTATION_DEGREE, + state.getValue(SugarBlock.FRAGMENTATION_DEGREE).next() + ) + ); } } else { if (chance <= 0.05) { @@ -80,11 +86,11 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou @Override public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { - return this.defaultBlockState().setValue(FRAGMENTATION_DEGREE, FragmentationDegree.ZERO); + return this.defaultBlockState().setValue(SugarBlock.FRAGMENTATION_DEGREE, FragmentationDegree.ZERO); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FRAGMENTATION_DEGREE); + builder.add(SugarBlock.FRAGMENTATION_DEGREE); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/storage/VoidMatterBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/storage/VoidMatterBlock.java index 1c94bcb0f4..433009f23d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/storage/VoidMatterBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/storage/VoidMatterBlock.java @@ -43,8 +43,8 @@ protected void randomTick(BlockState state, ServerLevel level, BlockPos pos, Ran neighborVoidMatterCount++; } } - if (neighborVoidMatterCount >= VOID_DECAY_THRESHOLD) { - level.setBlockAndUpdate(pos, voidDecay(level, random)); + if (neighborVoidMatterCount >= VoidMatterBlock.VOID_DECAY_THRESHOLD) { + level.setBlockAndUpdate(pos, VoidMatterBlock.voidDecay(level, random)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/ActiveSilencerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/ActiveSilencerBlock.java index b3a0c7be38..5b93b2d665 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/ActiveSilencerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/ActiveSilencerBlock.java @@ -22,6 +22,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -41,17 +42,17 @@ public class ActiveSilencerBlock extends BaseEntityBlock implements IHammerRemov public ActiveSilencerBlock(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(POWERED, false)); + this.registerDefaultState(this.getStateDefinition().any().setValue(ActiveSilencerBlock.POWERED, false)); } @Override protected MapCodec codec() { - return simpleCodec(ActiveSilencerBlock::new); + return BlockBehaviour.simpleCodec(ActiveSilencerBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED); + builder.add(ActiveSilencerBlock.POWERED); } @Nullable @@ -62,7 +63,8 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Override public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { - return defaultBlockState().setValue(POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); + return this.defaultBlockState().setValue( + ActiveSilencerBlock.POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); } @Override @@ -74,7 +76,7 @@ protected void neighborChanged( @Nullable Orientation orientation, boolean movedByPiston ) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, level.hasNeighborSignal(pos))); + level.setBlockAndUpdate(pos, state.setValue(ActiveSilencerBlock.POWERED, level.hasNeighborSignal(pos))); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/ArrowBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/ArrowBlock.java index dc44cbae41..4c00ec937a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/ArrowBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/ArrowBlock.java @@ -14,7 +14,7 @@ public class ArrowBlock extends DirectionalBlock implements IHammerRemovable { public ArrowBlock(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH)); + this.registerDefaultState(this.getStateDefinition().any().setValue(DirectionalBlock.FACING, Direction.NORTH)); } @Override @@ -25,22 +25,22 @@ protected MapCodec codec() { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(FACING); + builder.add(DirectionalBlock.FACING); } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(DirectionalBlock.FACING, rotation.rotate(state.getValue(DirectionalBlock.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(DirectionalBlock.FACING))); } @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(FACING, context.getNearestLookingDirection().getOpposite()); + .setValue(DirectionalBlock.FACING, context.getNearestLookingDirection().getOpposite()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockDevourerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockDevourerBlock.java index dd45298151..ec0d04f1b3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockDevourerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockDevourerBlock.java @@ -31,6 +31,7 @@ import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.entity.LecternBlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -66,19 +67,19 @@ public BlockDevourerBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition.any() - .setValue(FACING, Direction.NORTH) - .setValue(TRIGGERED, false) + .setValue(BlockDevourerBlock.FACING, Direction.NORTH) + .setValue(BlockDevourerBlock.TRIGGERED, false) ); } @Override protected MapCodec codec() { - return simpleCodec(BlockDevourerBlock::new); + return BlockBehaviour.simpleCodec(BlockDevourerBlock::new); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING).add(TRIGGERED); + builder.add(BlockDevourerBlock.FACING).add(BlockDevourerBlock.TRIGGERED); } @Override @@ -86,13 +87,13 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { Player player = context.getPlayer(); if (player == null) { return this.defaultBlockState() - .setValue(FACING, context.getNearestLookingDirection().getOpposite()); + .setValue(BlockDevourerBlock.FACING, context.getNearestLookingDirection().getOpposite()); } if (player.isShiftKeyDown()) { return this.defaultBlockState() - .setValue(FACING, context.getNearestLookingDirection().getOpposite()); + .setValue(BlockDevourerBlock.FACING, context.getNearestLookingDirection().getOpposite()); } else { - return this.defaultBlockState().setValue(FACING, context.getNearestLookingDirection()); + return this.defaultBlockState().setValue(BlockDevourerBlock.FACING, context.getNearestLookingDirection()); } } @@ -117,9 +118,9 @@ public void tick( RandomSource random ) { super.tick(state, level, pos, random); - if (!state.getValue(TRIGGERED)) return; - if (!BlockPlacerBlock.hasNeighborSignal(level, pos, state.getValue(FACING))) { - level.setBlock(pos, state.setValue(TRIGGERED, false), 2); + if (!state.getValue(BlockDevourerBlock.TRIGGERED)) return; + if (!BlockPlacerBlock.hasNeighborSignal(level, pos, state.getValue(BlockDevourerBlock.FACING))) { + level.setBlock(pos, state.setValue(BlockDevourerBlock.TRIGGERED, false), 2); } } @@ -138,12 +139,21 @@ protected void neighborChanged( } private void checkIfTriggered(Level level, BlockState blockState, BlockPos blockPos) { - boolean bl = blockState.getValue(TRIGGERED); - if (bl != BlockPlacerBlock.hasNeighborSignal(level, blockPos, blockState.getValue(FACING))) { - BlockState changedState = blockState.setValue(TRIGGERED, !bl); + boolean bl = blockState.getValue(BlockDevourerBlock.TRIGGERED); + if (bl != BlockPlacerBlock.hasNeighborSignal( + level, + blockPos, + blockState.getValue(BlockDevourerBlock.FACING) + )) { + BlockState changedState = blockState.setValue(BlockDevourerBlock.TRIGGERED, !bl); level.setBlock(blockPos, changedState, 2); if (!bl) { - this.devourBlock((ServerLevel) level, blockPos, blockState.getValue(FACING), 1); + this.devourBlock( + (ServerLevel) level, + blockPos, + blockState.getValue(BlockDevourerBlock.FACING), + 1 + ); } } } @@ -160,13 +170,13 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return switch (state.getValue(FACING)) { - case DOWN -> DOWN_SHAPE; - case UP -> UP_SHAPE; - case NORTH -> NORTH_SHAPE; - case SOUTH -> SOUTH_SHAPE; - case WEST -> WEST_SHAPE; - case EAST -> EAST_SHAPE; + return switch (state.getValue(BlockDevourerBlock.FACING)) { + case DOWN -> BlockDevourerBlock.DOWN_SHAPE; + case UP -> BlockDevourerBlock.UP_SHAPE; + case NORTH -> BlockDevourerBlock.NORTH_SHAPE; + case SOUTH -> BlockDevourerBlock.SOUTH_SHAPE; + case WEST -> BlockDevourerBlock.WEST_SHAPE; + case EAST -> BlockDevourerBlock.EAST_SHAPE; }; } @@ -247,10 +257,14 @@ public void devourBlock( } } - devourSingleBlockInternalLogic(level, anvil, devourBlockPos, filteredBlockPosList, itemHandlerList, center); + BlockDevourerBlock.devourSingleBlockInternalLogic( + level, anvil, devourBlockPos, filteredBlockPosList, itemHandlerList, center + ); } for (BlockPos devourBlockPos : chainDevourBlockPosList) { - devourSingleBlockInternalLogic(level, anvil, devourBlockPos, filteredBlockPosList, itemHandlerList, center); + BlockDevourerBlock.devourSingleBlockInternalLogic( + level, anvil, devourBlockPos, filteredBlockPosList, itemHandlerList, center + ); } } @@ -317,7 +331,9 @@ private static void devourSingleBlockInternalLogic( } } if (level.getBlockEntity(devourBlockPos) instanceof LecternBlockEntity lectern) { - transferLecternContents(level, itemHandlerList, center, lectern, insertEnabled, dropOriginalPlace); + BlockDevourerBlock.transferLecternContents( + level, itemHandlerList, center, lectern, insertEnabled, dropOriginalPlace + ); } if (!(devourBlockState.getBlock() instanceof DoublePlantBlock)) { ServerPlayer player = AnvilCraftFakePlayers.getBlockPlacer().offerPlayer(level); @@ -360,11 +376,17 @@ private static void transferLecternContents( @Override protected BlockState rotate(BlockState state, Rotation rot) { - return state.setValue(FACING, rot.rotate(state.getValue(FACING))); + return state.setValue( + BlockDevourerBlock.FACING, + rot.rotate(state.getValue(BlockDevourerBlock.FACING)) + ); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue( + BlockDevourerBlock.FACING, + mirror.mirror(state.getValue(BlockDevourerBlock.FACING)) + ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockPlacerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockPlacerBlock.java index 1b80309987..17a10dbd52 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockPlacerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/BlockPlacerBlock.java @@ -82,13 +82,13 @@ public BlockPlacerBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(ORIENTATION, Orientation.NORTH_UP) - .setValue(TRIGGERED, false)); + .setValue(BlockPlacerBlock.ORIENTATION, Orientation.NORTH_UP) + .setValue(BlockPlacerBlock.TRIGGERED, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(ORIENTATION).add(TRIGGERED); + builder.add(BlockPlacerBlock.ORIENTATION).add(BlockPlacerBlock.TRIGGERED); } @Override @@ -109,9 +109,9 @@ public void tick( BlockPos pos, RandomSource random) { super.tick(state, level, pos, random); - if (!state.getValue(TRIGGERED)) return; - if (!hasNeighborSignal(level, pos, state.getValue(ORIENTATION).getDirection())) { - level.setBlock(pos, state.setValue(TRIGGERED, false), 2); + if (!state.getValue(BlockPlacerBlock.TRIGGERED)) return; + if (!BlockPlacerBlock.hasNeighborSignal(level, pos, state.getValue(BlockPlacerBlock.ORIENTATION).getDirection())) { + level.setBlock(pos, state.setValue(BlockPlacerBlock.TRIGGERED, false), 2); } } @@ -130,14 +130,15 @@ protected void neighborChanged( } private void checkIfTriggered(Level level, BlockState blockState, BlockPos blockPos) { - boolean triggered = blockState.getValue(TRIGGERED); - if (triggered != hasNeighborSignal(level, blockPos, blockState.getValue(ORIENTATION).getDirection())) { - BlockState changedState = blockState.setValue(TRIGGERED, !triggered); + boolean triggered = blockState.getValue(BlockPlacerBlock.TRIGGERED); + if (triggered != BlockPlacerBlock.hasNeighborSignal( + level, blockPos, blockState.getValue(BlockPlacerBlock.ORIENTATION).getDirection())) { + BlockState changedState = blockState.setValue(BlockPlacerBlock.TRIGGERED, !triggered); level.setBlock(blockPos, changedState, 2); if (triggered) { return; } - this.placeBlock(1, level, blockPos, blockState.getValue(ORIENTATION)); + this.placeBlock(1, level, blockPos, blockState.getValue(BlockPlacerBlock.ORIENTATION)); } } @@ -163,19 +164,19 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return switch (state.getValue(ORIENTATION)) { - case NORTH_UP -> NORTH_UP_SHAPE; - case SOUTH_UP -> SOUTH_UP_SHAPE; - case WEST_UP -> WEST_UP_SHAPE; - case EAST_UP -> EAST_UP_SHAPE; - case UP_NORTH -> UP_NORTH_SHAPE; - case UP_SOUTH -> UP_SOUTH_SHAPE; - case UP_WEST -> UP_WEST_SHAPE; - case UP_EAST -> UP_EAST_SHAPE; - case DOWN_NORTH -> DOWN_NORTH_SHAPE; - case DOWN_SOUTH -> DOWN_SOUTH_SHAPE; - case DOWN_WEST -> DOWN_WEST_SHAPE; - case DOWN_EAST -> DOWN_EAST_SHAPE; + return switch (state.getValue(BlockPlacerBlock.ORIENTATION)) { + case NORTH_UP -> BlockPlacerBlock.NORTH_UP_SHAPE; + case SOUTH_UP -> BlockPlacerBlock.SOUTH_UP_SHAPE; + case WEST_UP -> BlockPlacerBlock.WEST_UP_SHAPE; + case EAST_UP -> BlockPlacerBlock.EAST_UP_SHAPE; + case UP_NORTH -> BlockPlacerBlock.UP_NORTH_SHAPE; + case UP_SOUTH -> BlockPlacerBlock.UP_SOUTH_SHAPE; + case UP_WEST -> BlockPlacerBlock.UP_WEST_SHAPE; + case UP_EAST -> BlockPlacerBlock.UP_EAST_SHAPE; + case DOWN_NORTH -> BlockPlacerBlock.DOWN_NORTH_SHAPE; + case DOWN_SOUTH -> BlockPlacerBlock.DOWN_SOUTH_SHAPE; + case DOWN_WEST -> BlockPlacerBlock.DOWN_WEST_SHAPE; + case DOWN_EAST -> BlockPlacerBlock.DOWN_EAST_SHAPE; }; } @@ -214,7 +215,7 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { if (context.getPlayer() != null && context.getPlayer().isShiftKeyDown()) { orientation = orientation.opposite(); } - return defaultBlockState().setValue(ORIENTATION, orientation); + return this.defaultBlockState().setValue(BlockPlacerBlock.ORIENTATION, orientation); } /// 放置方块 @@ -253,7 +254,7 @@ public void placeBlock(int distance, Level level, BlockPos blockPos, Orientation int i = 0; do { if (level.getBlockState(inputPos).is(this) - && level.getBlockState(inputPos).getValue(ORIENTATION).getDirection() == direction + && level.getBlockState(inputPos).getValue(BlockPlacerBlock.ORIENTATION).getDirection() == direction ) { i++; inputPos = inputPos.relative(direction.getOpposite()); @@ -347,10 +348,10 @@ private boolean canNotBePlaced(Level level, BlockState blockState) { @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { - BlockState state = defaultBlockState(); + BlockState state = this.defaultBlockState(); state = state.setValue( - ORIENTATION, - level.getBlockState(blockPos).getValue(ORIENTATION).next() + BlockPlacerBlock.ORIENTATION, + level.getBlockState(blockPos).getValue(BlockPlacerBlock.ORIENTATION).next() ); level.setBlockAndUpdate(blockPos, state); return true; @@ -358,16 +359,16 @@ public boolean change(Player player, BlockPos blockPos, Level level, ItemStack a @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return ORIENTATION; + return BlockPlacerBlock.ORIENTATION; } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(ORIENTATION, state.getValue(ORIENTATION).rotate(rotation)); + return state.setValue(BlockPlacerBlock.ORIENTATION, state.getValue(BlockPlacerBlock.ORIENTATION).rotate(rotation)); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(ORIENTATION, state.getValue(ORIENTATION).mirror(mirror)); + return state.setValue(BlockPlacerBlock.ORIENTATION, state.getValue(BlockPlacerBlock.ORIENTATION).mirror(mirror)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/ImpactPileBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/ImpactPileBlock.java index e71492ddf6..1c3b361606 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/ImpactPileBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/ImpactPileBlock.java @@ -32,7 +32,7 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return ImpactPileBlock.SHAPE; } @Override @@ -58,7 +58,7 @@ public static void impact(Level level, BlockPos blockPos) { for (int z = blockPos.getZ() - 1; z <= blockPos.getZ() + 1; z++) { for (int y = minY; y <= minY + 5; y++) { BlockPos pos = new BlockPos(x, y, z); - if (y <= minY + 2) setSturdyDeepslate(level, pos); + if (y <= minY + 2) ImpactPileBlock.setSturdyDeepslate(level, pos); } } } @@ -70,11 +70,11 @@ public static void impact(Level level, BlockPos blockPos) { level.setBlockAndUpdate(pos.south().west(), Blocks.LAVA.defaultBlockState()); level.setBlockAndUpdate(pos.south().east(), Blocks.LAVA.defaultBlockState()); } - setSturdyDeepslate(level, pos); - setSturdyDeepslate(level, pos.north()); - setSturdyDeepslate(level, pos.south()); - setSturdyDeepslate(level, pos.west()); - setSturdyDeepslate(level, pos.east()); + ImpactPileBlock.setSturdyDeepslate(level, pos); + ImpactPileBlock.setSturdyDeepslate(level, pos.north()); + ImpactPileBlock.setSturdyDeepslate(level, pos.south()); + ImpactPileBlock.setSturdyDeepslate(level, pos.west()); + ImpactPileBlock.setSturdyDeepslate(level, pos.east()); } level.setBlockAndUpdate( new BlockPos(blockPos.getX(), minY + 5, blockPos.getZ()), diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/MengerSpongeBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/MengerSpongeBlock.java index 1c145002e3..d4c7834a16 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/MengerSpongeBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/MengerSpongeBlock.java @@ -35,7 +35,7 @@ public class MengerSpongeBlock extends SpongeBlock implements IHammerRemovable { .reduce((v1, v2) -> Shapes.join(v1, v2, BooleanOp.OR)) .get(); - private static final VoxelShape AABB = Shapes.join(Shapes.block(), REDUCE_AABB, BooleanOp.ONLY_FIRST); + private static final VoxelShape AABB = Shapes.join(Shapes.block(), MengerSpongeBlock.REDUCE_AABB, BooleanOp.ONLY_FIRST); private static final Direction[] ALL_DIRECTIONS = Direction.values(); @@ -68,7 +68,7 @@ private boolean removeFluidBreadthFirstSearch(Level level, BlockPos pos) { 6, 65, (posx, consumer) -> { - for (Direction direction : ALL_DIRECTIONS) { + for (Direction direction : MengerSpongeBlock.ALL_DIRECTIONS) { consumer.accept(posx.relative(direction)); } }, @@ -102,7 +102,7 @@ private boolean removeFluidBreadthFirstSearch(Level level, BlockPos pos) { BlockEntity blockEntity = blockState.hasBlockEntity() ? level.getBlockEntity(checkedPos) : null; - dropResources(blockState, level, checkedPos, blockEntity); + Block.dropResources(blockState, level, checkedPos, blockEntity); level.setBlock(checkedPos, Blocks.AIR.defaultBlockState(), 3); } return BlockPos.TraversalNodeStatus.ACCEPT; @@ -127,7 +127,7 @@ protected void neighborChanged( @Override public VoxelShape getInteractionShape(BlockState state, BlockGetter level, BlockPos pos) { - return REDUCE_AABB; + return MengerSpongeBlock.REDUCE_AABB; } @Override @@ -137,6 +137,6 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return AABB; + return MengerSpongeBlock.AABB; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/SpacetimeSupercomputerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/SpacetimeSupercomputerBlock.java index 5770b2477c..2e902f026c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/SpacetimeSupercomputerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/SpacetimeSupercomputerBlock.java @@ -25,6 +25,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -44,24 +45,25 @@ public class SpacetimeSupercomputerBlock extends BetterBaseEntityBlock implement public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public static final VoxelShape SHAPE = Stream.of( - box(3, 2, 3, 13, 14, 13), - box(0, 0, 0, 16, 2, 16), - box(0, 14, 0, 16, 16, 16) + Block.box(3, 2, 3, 13, 14, 13), + Block.box(0, 0, 0, 16, 2, 16), + Block.box(0, 14, 0, 16, 16, 16) ).reduce((v1, v2) -> Shapes.join(v1, v2, BooleanOp.OR)).get(); @Override protected MapCodec codec() { - return simpleCodec(SpacetimeSupercomputerBlock::new); + return BlockBehaviour.simpleCodec(SpacetimeSupercomputerBlock::new); } public SpacetimeSupercomputerBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(POWERED, false)); + this.registerDefaultState(this.stateDefinition.any().setValue(SpacetimeSupercomputerBlock.POWERED, false)); } @Override public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { - return this.defaultBlockState().setValue(POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); + return this.defaultBlockState().setValue( + SpacetimeSupercomputerBlock.POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); } @Override @@ -76,9 +78,9 @@ protected void neighborChanged( if (level.isClientSide()) return; // 只在红石信号从无到有的那一刻触发,避免持续通电时每次邻居更新都重复执行命令 boolean powered = level.hasNeighborSignal(pos); - boolean wasPowered = state.getValue(POWERED); + boolean wasPowered = state.getValue(SpacetimeSupercomputerBlock.POWERED); if (powered != wasPowered) { - level.setBlock(pos, state.setValue(POWERED, powered), 2); + level.setBlock(pos, state.setValue(SpacetimeSupercomputerBlock.POWERED, powered), 2); } if (powered && !wasPowered) { level.scheduleTick(pos, this, 1); @@ -87,7 +89,7 @@ protected void neighborChanged( @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(POWERED); + builder.add(SpacetimeSupercomputerBlock.POWERED); } @Override @@ -117,7 +119,7 @@ public InteractionResult use(BlockState state, Level level, BlockPos pos, Player @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return SpacetimeSupercomputerBlock.SHAPE; } @Override @@ -139,7 +141,7 @@ protected VoxelShape getInteractionShape(BlockState state, BlockGetter level, Bl if (level.isClientSide()) { return null; } - return createTickerHelper( + return BaseEntityBlock.createTickerHelper( blockEntityType, ModBlockEntities.SPACETIME_SUPERCOMPUTER.get(), (world, pos, bs, be) -> be.tick() diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/AdvancedComparatorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/AdvancedComparatorBlock.java index cd1793fd4c..7f3e90341c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/AdvancedComparatorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/AdvancedComparatorBlock.java @@ -30,6 +30,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -50,7 +51,7 @@ import java.util.Optional; public class AdvancedComparatorBlock extends HorizontalDirectionalBlock implements IMoveableEntityBlock, IHammerRemovable { - public static final MapCodec CODEC = simpleCodec(AdvancedComparatorBlock::new); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(AdvancedComparatorBlock::new); public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public static final BooleanProperty INPUT = BooleanProperty.create("input"); @@ -66,27 +67,30 @@ public AdvancedComparatorBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition.any() - .setValue(FACING, Direction.NORTH) - .setValue(INPUT, false) - .setValue(POWER, 0) - .setValue(MODE, Mode.HYSTERESIS) - .setValue(POWERED, false) + .setValue(HorizontalDirectionalBlock.FACING, Direction.NORTH) + .setValue(AdvancedComparatorBlock.INPUT, false) + .setValue(AdvancedComparatorBlock.POWER, 0) + .setValue(AdvancedComparatorBlock.MODE, Mode.HYSTERESIS) + .setValue(AdvancedComparatorBlock.POWERED, false) ); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, INPUT, POWER, MODE, POWERED); + builder.add( + HorizontalDirectionalBlock.FACING, AdvancedComparatorBlock.INPUT, AdvancedComparatorBlock.POWER, AdvancedComparatorBlock.MODE, + AdvancedComparatorBlock.POWERED + ); } @Override protected MapCodec codec() { - return CODEC; + return AdvancedComparatorBlock.CODEC; } @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return AdvancedComparatorBlock.SHAPE; } @Override @@ -106,7 +110,7 @@ protected int getDirectSignal(BlockState state, BlockGetter level, BlockPos pos, @Override protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { - return state.getValue(FACING) == direction && state.getValue(POWERED) ? 15 : 0; + return state.getValue(HorizontalDirectionalBlock.FACING) == direction && state.getValue(AdvancedComparatorBlock.POWERED) ? 15 : 0; } @Override @@ -118,7 +122,7 @@ protected void neighborChanged( @Nullable Orientation orientation, boolean movedByPiston ) { - level.scheduleTick(pos, this, getDelay()); + level.scheduleTick(pos, this, AdvancedComparatorBlock.getDelay()); } @Override @@ -128,18 +132,18 @@ protected boolean isSignalSource(BlockState state) { @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return this.defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite()); + return this.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, context.getHorizontalDirection().getOpposite()); } @Override public void setPlacedBy(Level level, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { - level.scheduleTick(pos, this, getDelay()); + level.scheduleTick(pos, this, AdvancedComparatorBlock.getDelay()); } @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) { super.onPlace(state, level, pos, oldState, isMoving); - level.scheduleTick(pos, this, getDelay()); + level.scheduleTick(pos, this, AdvancedComparatorBlock.getDelay()); } @Override @@ -147,7 +151,7 @@ protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, if (!state.is(level.getBlockState(pos).getBlock())) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); } - Direction facing = state.getValue(FACING); + Direction facing = state.getValue(HorizontalDirectionalBlock.FACING); BlockPos front = pos.relative(facing.getOpposite()); if (EventHooks.onNeighborNotify(level, pos, level.getBlockState(pos), EnumSet.of(facing.getOpposite()), false).isCanceled()) return; Orientation orientation = ExperimentalRedstoneUtils.initialOrientation(level, facing.getOpposite(), null); @@ -186,7 +190,7 @@ public void update(Level level, BlockPos pos, BlockState state) { } public static int getInputSignal(Level level, BlockPos pos, BlockState state) { - Direction direction = state.getValue(FACING); + Direction direction = state.getValue(HorizontalDirectionalBlock.FACING); BlockPos blockpos = pos.relative(direction); BlockState blockstate = level.getBlockState(blockpos); int i = level.getSignal(blockpos, direction); @@ -195,7 +199,7 @@ public static int getInputSignal(Level level, BlockPos pos, BlockState state) { } else if (i < 15 && blockstate.isRedstoneConductor(level, blockpos)) { blockpos = blockpos.relative(direction); blockstate = level.getBlockState(blockpos); - ItemFrame itemframe = getItemFrame(level, direction, blockpos); + ItemFrame itemframe = AdvancedComparatorBlock.getItemFrame(level, direction, blockpos); int j = Integer.MIN_VALUE; if (blockstate.hasAnalogOutputSignal()) j = Math.max(j, blockstate.getAnalogOutputSignal(level, blockpos, direction)); if (itemframe != null) j = Math.max(j, itemframe.getAnalogOutput()); @@ -225,7 +229,7 @@ private static ItemFrame getItemFrame(Level level, Direction facing, BlockPos po } public static int getAlternateSignal(SignalGetter level, BlockPos pos, BlockState state, boolean isHigh) { - Direction direction = state.getValue(FACING); + Direction direction = state.getValue(HorizontalDirectionalBlock.FACING); Direction right = direction.getClockWise(); Direction left = direction.getCounterClockWise(); return isHigh ? Math.max(level.getSignal(pos.relative(right), right), level.getSignal(pos.relative(left), left)) @@ -240,7 +244,7 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou blockEntity.updateInputtingSignal(level, pos, state); this.updateBlockAndNeighbours(level, pos, state, blockEntity); this.update(level, pos, state); - level.scheduleTick(pos, this, getDelay()); + level.scheduleTick(pos, this, AdvancedComparatorBlock.getDelay()); } protected void updateBlockAndNeighbours(Level level, BlockPos pos, BlockState state, AdvancedComparatorBlockEntity blockEntity) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/BlockComparatorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/BlockComparatorBlock.java index 2812cde5b3..2b42c0f46b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/BlockComparatorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/BlockComparatorBlock.java @@ -21,6 +21,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Mirror; import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -38,7 +39,7 @@ public class BlockComparatorBlock extends Block implements IHammerRemovable, IHammerChangeable { - public static final MapCodec CODEC = simpleCodec(BlockComparatorBlock::new); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(BlockComparatorBlock::new); public static final EnumProperty FACING_WITH_AXIS = EnumProperty.create("facing_with_axis", FacingWithAxis.class); @@ -51,41 +52,41 @@ public class BlockComparatorBlock extends Block implements IHammerRemovable, IHa new AABB(0, 4.0, 0, 2.0, 12.0, 10.0), new AABB(14.0, 4.0, 0, 16, 12.0, 10.0) ); - private static final VoxelShape SHAPE_SOUTH_X = ShapeUtil.rotate(Direction.Axis.Y, 180, SHAPE_NORTH_X); + private static final VoxelShape SHAPE_SOUTH_X = ShapeUtil.rotate(Direction.Axis.Y, 180, BlockComparatorBlock.SHAPE_NORTH_X); - private static final VoxelShape SHAPE_WEST_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, SHAPE_NORTH_X); - private static final VoxelShape SHAPE_EAST_Z = ShapeUtil.rotate(Direction.Axis.Y, 270, SHAPE_NORTH_X); + private static final VoxelShape SHAPE_WEST_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, BlockComparatorBlock.SHAPE_NORTH_X); + private static final VoxelShape SHAPE_EAST_Z = ShapeUtil.rotate(Direction.Axis.Y, 270, BlockComparatorBlock.SHAPE_NORTH_X); - private static final VoxelShape SHAPE_NORTH_Y = ShapeUtil.rotate(Direction.Axis.Z, 90, SHAPE_NORTH_X); - private static final VoxelShape SHAPE_SOUTH_Y = ShapeUtil.rotate(Direction.Axis.Y, 180, SHAPE_NORTH_Y); - private static final VoxelShape SHAPE_WEST_Y = ShapeUtil.rotate(Direction.Axis.Y, 90, SHAPE_NORTH_Y); - private static final VoxelShape SHAPE_EAST_Y = ShapeUtil.rotate(Direction.Axis.Y, 270, SHAPE_NORTH_Y); + private static final VoxelShape SHAPE_NORTH_Y = ShapeUtil.rotate(Direction.Axis.Z, 90, BlockComparatorBlock.SHAPE_NORTH_X); + private static final VoxelShape SHAPE_SOUTH_Y = ShapeUtil.rotate(Direction.Axis.Y, 180, BlockComparatorBlock.SHAPE_NORTH_Y); + private static final VoxelShape SHAPE_WEST_Y = ShapeUtil.rotate(Direction.Axis.Y, 90, BlockComparatorBlock.SHAPE_NORTH_Y); + private static final VoxelShape SHAPE_EAST_Y = ShapeUtil.rotate(Direction.Axis.Y, 270, BlockComparatorBlock.SHAPE_NORTH_Y); - private static final VoxelShape SHAPE_UP_X = ShapeUtil.rotate(Direction.Axis.X, 270, SHAPE_NORTH_X); - private static final VoxelShape SHAPE_DOWN_X = ShapeUtil.rotate(Direction.Axis.X, 90, SHAPE_NORTH_X); + private static final VoxelShape SHAPE_UP_X = ShapeUtil.rotate(Direction.Axis.X, 270, BlockComparatorBlock.SHAPE_NORTH_X); + private static final VoxelShape SHAPE_DOWN_X = ShapeUtil.rotate(Direction.Axis.X, 90, BlockComparatorBlock.SHAPE_NORTH_X); - private static final VoxelShape SHAPE_UP_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, SHAPE_UP_X); - private static final VoxelShape SHAPE_DOWN_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, SHAPE_DOWN_X); + private static final VoxelShape SHAPE_UP_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, BlockComparatorBlock.SHAPE_UP_X); + private static final VoxelShape SHAPE_DOWN_Z = ShapeUtil.rotate(Direction.Axis.Y, 90, BlockComparatorBlock.SHAPE_DOWN_X); public BlockComparatorBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition .any() - .setValue(FACING_WITH_AXIS, FacingWithAxis.NORTH_X) - .setValue(PRECISE, false) - .setValue(POWERED, false) + .setValue(BlockComparatorBlock.FACING_WITH_AXIS, FacingWithAxis.NORTH_X) + .setValue(BlockComparatorBlock.PRECISE, false) + .setValue(BlockComparatorBlock.POWERED, false) ); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING_WITH_AXIS).add(PRECISE).add(POWERED); + builder.add(BlockComparatorBlock.FACING_WITH_AXIS).add(BlockComparatorBlock.PRECISE).add(BlockComparatorBlock.POWERED); } @Override protected MapCodec codec() { - return CODEC; + return BlockComparatorBlock.CODEC; } @Override @@ -95,23 +96,23 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return getShapeFor(state.getValue(FACING_WITH_AXIS)); + return BlockComparatorBlock.getShapeFor(state.getValue(BlockComparatorBlock.FACING_WITH_AXIS)); } private static VoxelShape getShapeFor(FacingWithAxis fwa) { return switch (fwa) { - case NORTH_X -> SHAPE_NORTH_X; - case SOUTH_X -> SHAPE_SOUTH_X; - case WEST_Z -> SHAPE_WEST_Z; - case EAST_Z -> SHAPE_EAST_Z; - case NORTH_Y -> SHAPE_NORTH_Y; - case SOUTH_Y -> SHAPE_SOUTH_Y; - case WEST_Y -> SHAPE_WEST_Y; - case EAST_Y -> SHAPE_EAST_Y; - case UP_X -> SHAPE_UP_X; - case UP_Z -> SHAPE_UP_Z; - case DOWN_X -> SHAPE_DOWN_X; - case DOWN_Z -> SHAPE_DOWN_Z; + case NORTH_X -> BlockComparatorBlock.SHAPE_NORTH_X; + case SOUTH_X -> BlockComparatorBlock.SHAPE_SOUTH_X; + case WEST_Z -> BlockComparatorBlock.SHAPE_WEST_Z; + case EAST_Z -> BlockComparatorBlock.SHAPE_EAST_Z; + case NORTH_Y -> BlockComparatorBlock.SHAPE_NORTH_Y; + case SOUTH_Y -> BlockComparatorBlock.SHAPE_SOUTH_Y; + case WEST_Y -> BlockComparatorBlock.SHAPE_WEST_Y; + case EAST_Y -> BlockComparatorBlock.SHAPE_EAST_Y; + case UP_X -> BlockComparatorBlock.SHAPE_UP_X; + case UP_Z -> BlockComparatorBlock.SHAPE_UP_Z; + case DOWN_X -> BlockComparatorBlock.SHAPE_DOWN_X; + case DOWN_Z -> BlockComparatorBlock.SHAPE_DOWN_Z; }; } @@ -127,7 +128,7 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { } else { axis = facing.getClockWise().getAxis(); } - return defaultBlockState().setValue(FACING_WITH_AXIS, FacingWithAxis.of(facing, axis)); + return this.defaultBlockState().setValue(BlockComparatorBlock.FACING_WITH_AXIS, FacingWithAxis.of(facing, axis)); } @Override @@ -135,12 +136,12 @@ protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState o if ( level.isClientSide() || (oldState.is(this) - && state.getValue(FACING_WITH_AXIS) == oldState.getValue(FACING_WITH_AXIS)) + && state.getValue(BlockComparatorBlock.FACING_WITH_AXIS) == oldState.getValue(BlockComparatorBlock.FACING_WITH_AXIS)) ) { return; } boolean newPowered = this.checkBlocks(level, pos, state); - level.setBlock(pos, state.setValue(POWERED, newPowered), 3); + level.setBlock(pos, state.setValue(BlockComparatorBlock.POWERED, newPowered), 3); this.updateNeighborsInFront(level, pos, state); } @@ -150,11 +151,11 @@ protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, if ( level.isClientSide() || (state.is(newState.getBlock()) - && state.getValue(FACING_WITH_AXIS) == newState.getValue(FACING_WITH_AXIS)) + && state.getValue(BlockComparatorBlock.FACING_WITH_AXIS) == newState.getValue(BlockComparatorBlock.FACING_WITH_AXIS)) ) { return; } - if (state.getValue(POWERED)) { + if (state.getValue(BlockComparatorBlock.POWERED)) { this.updateNeighborsInFront(level, pos, state); } } @@ -170,20 +171,20 @@ protected InteractionResult useWithoutItem( if (!player.getAbilities().mayBuild) { return InteractionResult.PASS; } else { - BlockState newState = state.cycle(PRECISE); - level.setBlock(pos, newState.setValue(POWERED, this.checkBlocks(level, pos, newState)), 2); + BlockState newState = state.cycle(BlockComparatorBlock.PRECISE); + level.setBlock(pos, newState.setValue(BlockComparatorBlock.POWERED, this.checkBlocks(level, pos, newState)), 2); this.updateNeighborsInFront(level, pos, state); return InteractionResult.SUCCESS; } } private boolean checkBlocks(LevelAccessor level, BlockPos pos, BlockState blockState) { - FacingWithAxis fwa = blockState.getValue(FACING_WITH_AXIS); + FacingWithAxis fwa = blockState.getValue(BlockComparatorBlock.FACING_WITH_AXIS); Direction.Axis axis = fwa.getAxis(); - Direction[] dirs = getCompareDirections(axis); + Direction[] dirs = BlockComparatorBlock.getCompareDirections(axis); BlockState state1 = level.getBlockState(pos.relative(dirs[0])); BlockState state2 = level.getBlockState(pos.relative(dirs[1])); - return blockState.getValue(PRECISE) + return blockState.getValue(BlockComparatorBlock.PRECISE) ? state1.equals(state2) : state1.getBlock() == state2.getBlock(); } @@ -206,7 +207,7 @@ protected BlockState updateShape( BlockState neighbourState, RandomSource random ) { - FacingWithAxis fwa = state.getValue(FACING_WITH_AXIS); + FacingWithAxis fwa = state.getValue(BlockComparatorBlock.FACING_WITH_AXIS); Direction facing = fwa.getFacing(); Direction.Axis compareAxis = fwa.getAxis(); if (directionToNeighbour.getAxis() == facing.getAxis()) return state; @@ -220,14 +221,14 @@ protected BlockState updateShape( @Override protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { boolean same = this.checkBlocks(level, pos, state); - if (same != state.getValue(POWERED)) { - level.setBlock(pos, state.setValue(POWERED, same), 2); + if (same != state.getValue(BlockComparatorBlock.POWERED)) { + level.setBlock(pos, state.setValue(BlockComparatorBlock.POWERED, same), 2); this.updateNeighborsInFront(level, pos, state); } } protected void updateNeighborsInFront(Level level, BlockPos pos, BlockState state) { - Direction direction = state.getValue(FACING_WITH_AXIS).getFacing(); + Direction direction = state.getValue(BlockComparatorBlock.FACING_WITH_AXIS).getFacing(); BlockPos blockpos = pos.relative(direction.getOpposite()); Orientation orientation = ExperimentalRedstoneUtils.initialOrientation(level, direction.getOpposite(), null); level.neighborChanged(blockpos, this, orientation); @@ -236,7 +237,7 @@ protected void updateNeighborsInFront(Level level, BlockPos pos, BlockState stat @Override public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction) { - return direction == state.getValue(FACING_WITH_AXIS).getFacing(); + return direction == state.getValue(BlockComparatorBlock.FACING_WITH_AXIS).getFacing(); } @Override @@ -256,7 +257,8 @@ protected int getDirectSignal( @Override protected int getSignal(BlockState blockState, BlockGetter blockAccess, BlockPos pos, Direction side) { - return blockState.getValue(POWERED) && blockState.getValue(FACING_WITH_AXIS).getFacing() == side ? 15 : 0; + return blockState.getValue(BlockComparatorBlock.POWERED) && blockState.getValue(BlockComparatorBlock.FACING_WITH_AXIS).getFacing() + == side ? 15 : 0; } @Override @@ -267,24 +269,25 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { BlockState state = level.getBlockState(blockPos); - FacingWithAxis fwa = state.getValue(FACING_WITH_AXIS); + FacingWithAxis fwa = state.getValue(BlockComparatorBlock.FACING_WITH_AXIS); FacingWithAxis newFwa = fwa.toggleAxis(); - level.setBlockAndUpdate(blockPos, state.setValue(FACING_WITH_AXIS, newFwa)); + level.setBlockAndUpdate(blockPos, state.setValue(BlockComparatorBlock.FACING_WITH_AXIS, newFwa)); return true; } @Override public Property getChangeableProperty(BlockState blockState) { - return FACING_WITH_AXIS; + return BlockComparatorBlock.FACING_WITH_AXIS; } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING_WITH_AXIS, state.getValue(FACING_WITH_AXIS).rotate(rotation)); + return state.setValue( + BlockComparatorBlock.FACING_WITH_AXIS, state.getValue(BlockComparatorBlock.FACING_WITH_AXIS).rotate(rotation)); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING_WITH_AXIS, state.getValue(FACING_WITH_AXIS).mirror(mirror)); + return state.setValue(BlockComparatorBlock.FACING_WITH_AXIS, state.getValue(BlockComparatorBlock.FACING_WITH_AXIS).mirror(mirror)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/ItemDetectorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/ItemDetectorBlock.java index d1e9500cae..a1326269fc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/ItemDetectorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/ItemDetectorBlock.java @@ -24,11 +24,11 @@ import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -46,7 +46,7 @@ public class ItemDetectorBlock extends BetterBaseEntityBlock implements EntityBlock, HammerRotateBehavior, IHammerRemovable { public static final EnumProperty FACING = HorizontalDirectionalBlock.FACING; public static final BooleanProperty POWERED = BlockStateProperties.POWERED; - public static final MapCodec CODEC = simpleCodec(ItemDetectorBlock::new); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(ItemDetectorBlock::new); public static final VoxelShape SHAPE = Block.box(0, 0, 0, 16, 4, 16); public ItemDetectorBlock(Properties properties) { @@ -54,19 +54,19 @@ public ItemDetectorBlock(Properties properties) { this.registerDefaultState( this.stateDefinition .any() - .setValue(FACING, Direction.NORTH) - .setValue(POWERED, false) + .setValue(ItemDetectorBlock.FACING, Direction.NORTH) + .setValue(ItemDetectorBlock.POWERED, false) ); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING).add(POWERED); + builder.add(ItemDetectorBlock.FACING).add(ItemDetectorBlock.POWERED); } @Override protected MapCodec codec() { - return CODEC; + return ItemDetectorBlock.CODEC; } @Override @@ -76,33 +76,31 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return SHAPE; - } - - @Override - protected RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; + return ItemDetectorBlock.SHAPE; } @Override public BlockState getStateForPlacement(BlockPlaceContext context) { Direction direction = context.getHorizontalDirection(); - return this.defaultBlockState().setValue(FACING, direction.getOpposite()); + return this.defaultBlockState().setValue(ItemDetectorBlock.FACING, direction.getOpposite()); } @Override protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldState, boolean isMoving) { - if (level.isClientSide() || (oldState.is(this) && state.getValue(FACING) == oldState.getValue(FACING))) return; + if (level.isClientSide() || (oldState.is(this) && state.getValue(ItemDetectorBlock.FACING) == oldState.getValue( + ItemDetectorBlock.FACING))) { + return; + } if (level.getBlockEntity(pos) instanceof ItemDetectorBlockEntity blockEntity) { blockEntity.recalcDetectionRange(); } - if (state.getValue(POWERED)) this.updateNeighborsInFront(level, pos, state); + if (state.getValue(ItemDetectorBlock.POWERED)) this.updateNeighborsInFront(level, pos, state); } @Override protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); - if (!state.getValue(POWERED)) { + if (!state.getValue(ItemDetectorBlock.POWERED)) { return; } this.updateNeighborsInFront(level, pos, state); @@ -132,7 +130,7 @@ public InteractionResult use( } public void updateNeighborsInFront(Level level, BlockPos pos, BlockState state) { - Direction direction = state.getValue(FACING); + Direction direction = state.getValue(ItemDetectorBlock.FACING); BlockPos blockpos = pos.relative(direction.getOpposite()); if (EventHooks.onNeighborNotify(level, pos, level.getBlockState(pos), EnumSet.of(direction.getOpposite()), false).isCanceled()) { return; @@ -148,7 +146,7 @@ public void updateNeighborsInFront(Level level, BlockPos pos, BlockState state) @Override public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction) { - return direction == state.getValue(FACING); + return direction == state.getValue(ItemDetectorBlock.FACING); } @Override @@ -165,7 +163,7 @@ protected int getDirectSignal(BlockState blockState, BlockGetter blockAccess, Bl protected int getSignal(BlockState blockState, BlockGetter blockAccess, BlockPos pos, Direction side) { BlockEntity blockEntity = blockAccess.getBlockEntity(pos); if (!(blockEntity instanceof ItemDetectorBlockEntity idbe)) return 0; - return blockState.getValue(FACING) == side ? idbe.getOutputSignal() : 0; + return blockState.getValue(ItemDetectorBlock.FACING) == side ? idbe.getOutputSignal() : 0; } @Override @@ -182,19 +180,19 @@ protected int getSignal(BlockState blockState, BlockGetter blockAccess, BlockPos if (level.isClientSide()) { return null; } - return createTickerHelper(type, ModBlockEntities.ITEM_DETECTOR.get(), - (level1, blockPos, blockState, blockEntity) -> + return BaseEntityBlock.createTickerHelper(type, ModBlockEntities.ITEM_DETECTOR.get(), + (level1, blockPos, blockState, blockEntity) -> blockEntity.tick()); } @Override protected BlockState rotate(BlockState state, Rotation rot) { - return state.setValue(FACING, rot.rotate(state.getValue(FACING))); + return state.setValue(ItemDetectorBlock.FACING, rot.rotate(state.getValue(ItemDetectorBlock.FACING))); } @SuppressWarnings("deprecation") @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.rotate(mirror.getRotation(state.getValue(FACING))); + return state.rotate(mirror.getRotation(state.getValue(ItemDetectorBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/PulseGeneratorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/PulseGeneratorBlock.java index 4c4a874c29..f7ec519b46 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/PulseGeneratorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/utility/redstone/PulseGeneratorBlock.java @@ -26,6 +26,7 @@ import net.minecraft.world.level.block.HorizontalDirectionalBlock; import net.minecraft.world.level.block.RedStoneWireBlock; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -49,25 +50,25 @@ public class PulseGeneratorBlock extends HorizontalDirectionalBlock implements I private static final int END_WAITING_EVENT = 1; public static final BooleanProperty POWERED = BlockStateProperties.POWERED; protected static final VoxelShape SHAPE = Block.box(0.0, 0.0, 0.0, 16.0, 4.0, 16.0); - public static final MapCodec CODEC = simpleCodec(PulseGeneratorBlock::new); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(PulseGeneratorBlock::new); public PulseGeneratorBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition.any() - .setValue(FACING, Direction.NORTH) - .setValue(POWERED, Boolean.FALSE) + .setValue(HorizontalDirectionalBlock.FACING, Direction.NORTH) + .setValue(PulseGeneratorBlock.POWERED, Boolean.FALSE) ); } @Override protected MapCodec codec() { - return CODEC; + return PulseGeneratorBlock.CODEC; } @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return PulseGeneratorBlock.SHAPE; } @Override @@ -79,7 +80,7 @@ protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, public boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction) { if (direction == null) return false; if (!(state.getBlock() instanceof PulseGeneratorBlock)) return false; - return state.getValue(FACING).getAxis().equals(direction.getAxis()); + return state.getValue(HorizontalDirectionalBlock.FACING).getAxis().equals(direction.getAxis()); } @Override @@ -89,7 +90,7 @@ protected int getDirectSignal(BlockState state, BlockGetter level, BlockPos pos, @Override protected int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { - return state.getValue(FACING) == direction && state.getValue(POWERED) ? 15 : 0; + return state.getValue(HorizontalDirectionalBlock.FACING) == direction && state.getValue(PulseGeneratorBlock.POWERED) ? 15 : 0; } @Override @@ -111,7 +112,7 @@ protected boolean isSignalSource(BlockState state) { @Override public BlockState getStateForPlacement(BlockPlaceContext context) { - return this.defaultBlockState().setValue(FACING, context.getHorizontalDirection().getOpposite()); + return this.defaultBlockState().setValue(HorizontalDirectionalBlock.FACING, context.getHorizontalDirection().getOpposite()); } @Override @@ -129,7 +130,7 @@ protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, } super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); } - Direction facing = state.getValue(FACING); + Direction facing = state.getValue(HorizontalDirectionalBlock.FACING); BlockPos front = pos.relative(facing.getOpposite()); if (EventHooks.onNeighborNotify(level, pos, level.getBlockState(pos), EnumSet.of(facing.getOpposite()), false).isCanceled()) return; level.neighborChanged(front, this, Orientation.random(level.getRandom())); @@ -213,7 +214,7 @@ public void startWaiting(Level level, BlockPos pos, Supplier stateGe if (generator.getWaitingTime() != 0) { level.scheduleTick(pos, this, generator.getWaitingTime(), TickPriority.LOW); } else { - level.blockEvent(pos, this, END_WAITING_EVENT, 0); + level.blockEvent(pos, this, PulseGeneratorBlock.END_WAITING_EVENT, 0); } } @@ -243,15 +244,13 @@ protected void updateBlockAndNeighbours( PulseGeneratorBlockEntity generator ) { BlockState state = stateGetter.get(); - boolean powered = state.getValue(POWERED); + boolean powered = state.getValue(PulseGeneratorBlock.POWERED); boolean shouldPower = generator.isOutputting(); if (powered == shouldPower) return; - Direction direction = state.getValue(FACING).getOpposite(); + Direction direction = state.getValue(HorizontalDirectionalBlock.FACING).getOpposite(); BlockPos neighbourPos = pos.relative(direction); - BlockState newState = state.setValue(POWERED, shouldPower); + BlockState newState = state.setValue(PulseGeneratorBlock.POWERED, shouldPower); level.setBlockAndUpdate(pos, newState); - // noinspection deprecation - generator.setBlockState(newState); level.neighborChanged(neighbourPos, state.getBlock(), Orientation.random(level.getRandom())); level.updateNeighborsAtExceptFromFacing( neighbourPos, @@ -261,7 +260,7 @@ protected void updateBlockAndNeighbours( ); // A block event separates zero-tick transitions from this neighbor-update stack. if (generator.getSignalDuration() == 0) { - level.blockEvent(pos, this, END_OUTPUTTING_EVENT, 0); + level.blockEvent(pos, this, PulseGeneratorBlock.END_OUTPUTTING_EVENT, 0); } } @@ -269,9 +268,9 @@ protected void updateBlockAndNeighbours( protected boolean triggerEvent(BlockState state, Level level, BlockPos pos, int id, int param) { if (!(level.getBlockEntity(pos) instanceof PulseGeneratorBlockEntity generator)) return true; Supplier currentStateGetter = () -> level.getBlockState(pos); - if (id == END_WAITING_EVENT && generator.getState() == PulseGeneratorBlockEntity.State.WAITING) { + if (id == PulseGeneratorBlock.END_WAITING_EVENT && generator.getState() == PulseGeneratorBlockEntity.State.WAITING) { this.startOutputting(level, pos, currentStateGetter, generator); - } else if (id == END_OUTPUTTING_EVENT && generator.getState() == PulseGeneratorBlockEntity.State.OUTPUTTING) { + } else if (id == PulseGeneratorBlock.END_OUTPUTTING_EVENT && generator.getState() == PulseGeneratorBlockEntity.State.OUTPUTTING) { this.checkOnSignalEnd(level, pos, currentStateGetter, generator); } return true; @@ -279,8 +278,8 @@ protected boolean triggerEvent(BlockState state, Level level, BlockPos pos, int @Override public void animateTick(BlockState state, Level level, BlockPos pos, RandomSource random) { - if (state.getValue(POWERED)) { - Direction direction = state.getValue(FACING).getOpposite(); + if (state.getValue(PulseGeneratorBlock.POWERED)) { + Direction direction = state.getValue(HorizontalDirectionalBlock.FACING).getOpposite(); double d0 = (double) pos.getX() + 0.5 + (random.nextDouble() - 0.5) * 0.2; double d1 = (double) pos.getY() + 0.5 + (random.nextDouble() - 0.5) * 0.2; double d2 = (double) pos.getZ() + 0.6 + (random.nextDouble() - 0.5) * 0.2; @@ -292,7 +291,7 @@ public void animateTick(BlockState state, Level level, BlockPos pos, RandomSourc } public static int getInputSignal(Level level, BlockPos pos, BlockState state) { - Direction direction = state.getValue(FACING); + Direction direction = state.getValue(HorizontalDirectionalBlock.FACING); BlockPos blockpos = pos.relative(direction); int i = level.getSignal(blockpos, direction); if (i >= 15) { @@ -350,23 +349,23 @@ protected InteractionResult useItemOn( @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED); + builder.add(HorizontalDirectionalBlock.FACING, PulseGeneratorBlock.POWERED); } @Override public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { - return level.setBlockAndUpdate(blockPos, level.getBlockState(blockPos).cycle(FACING)); + return level.setBlockAndUpdate(blockPos, level.getBlockState(blockPos).cycle(HorizontalDirectionalBlock.FACING)); } @Override public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return HorizontalDirectionalBlock.FACING; } @Override public void notifyMoved(Level level, BlockPos pos, BlockState state, BlockEntity be1) { if (!(be1 instanceof PulseGeneratorBlockEntity be)) { - level.setBlock(pos, state.setValue(POWERED, false), 3); + level.setBlock(pos, state.setValue(PulseGeneratorBlock.POWERED, false), 3); return; } switch (be.getState()) { @@ -382,4 +381,3 @@ public void notifyMoved(Level level, BlockPos pos, BlockState state, BlockEntity be.setChanged(); } } - diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/BurningHeaterBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/BurningHeaterBlock.java index 2f1dcc23ad..b2026cf08e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/BurningHeaterBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/BurningHeaterBlock.java @@ -18,6 +18,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; @@ -37,12 +38,12 @@ public class BurningHeaterBlock extends BaseEntityBlock implements IHammerRemova public BurningHeaterBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, 0)); + this.registerDefaultState(this.stateDefinition.any().setValue(BurningHeaterBlock.LEVEL, 0)); } @Override protected MapCodec codec() { - return simpleCodec(BurningHeaterBlock::new); + return BlockBehaviour.simpleCodec(BurningHeaterBlock::new); } @Nullable @@ -59,7 +60,7 @@ public RenderShape getRenderShape(BlockState state) { @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(LEVEL); + builder.add(BurningHeaterBlock.LEVEL); } @Nullable @@ -67,8 +68,8 @@ protected void createBlockStateDefinition(StateDefinition.Builder BlockEntityTicker getTicker( Level level, BlockState state, BlockEntityType type ) { - return createTickerHelper(type, ModBlockEntities.BURNING_HEATER.get(), - (lvl, pos, st, entity) -> entity.tick(lvl, pos, st)); + return BaseEntityBlock.createTickerHelper(type, ModBlockEntities.BURNING_HEATER.get(), + (lvl, pos, st, entity) -> entity.tick(lvl, pos, st)); } @Override @@ -112,6 +113,6 @@ public void stepOn(Level level, BlockPos pos, BlockState state, Entity entity) { @Override public boolean isActive(BlockState state) { - return state.getValue(LEVEL) > 0; + return state.getValue(BurningHeaterBlock.LEVEL) > 0; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ConfinementChamberBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ConfinementChamberBlock.java index c1c7722173..45e1d55efc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ConfinementChamberBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ConfinementChamberBlock.java @@ -18,6 +18,7 @@ import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; 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; @@ -35,7 +36,7 @@ public ConfinementChamberBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(ConfinementChamberBlock::new); + return BlockBehaviour.simpleCodec(ConfinementChamberBlock::new); } @Override @@ -91,7 +92,8 @@ public BlockState playerWillDestroy(Level level, BlockPos pos, BlockState state, protected List getDrops(BlockState state, LootParams.Builder params) { BlockEntity blockentity = params.getOptionalParameter(LootContextParams.BLOCK_ENTITY); if (blockentity instanceof ShulkerBoxBlockEntity shulkerboxblockentity) { - params = params.withDynamicDrop(CONTENTS, it -> { + params = params.withDynamicDrop( + ConfinementChamberBlock.CONTENTS, it -> { for (int i = 0; i < shulkerboxblockentity.getContainerSize(); i++) { it.accept(shulkerboxblockentity.getItem(i)); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/CorruptedBeaconBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/CorruptedBeaconBlock.java index d4a0817049..fe52ec676f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/CorruptedBeaconBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/CorruptedBeaconBlock.java @@ -36,22 +36,22 @@ public CorruptedBeaconBlock(Properties properties) { super(properties); BlockState defaultState = this.defaultBlockState(); if (defaultState.equals(this.stateDefinition.any())) { - this.registerDefaultState(this.stateDefinition.any().setValue(LIT, false)); + this.registerDefaultState(this.stateDefinition.any().setValue(CorruptedBeaconBlock.LIT, false)); } else { - this.registerDefaultState(defaultState.setValue(LIT, false)); + this.registerDefaultState(defaultState.setValue(CorruptedBeaconBlock.LIT, false)); } } @Override @Nullable public BlockState getStateForPlacement(BlockPlaceContext context) { - return Objects.requireNonNull(super.getStateForPlacement(context)).setValue(LIT, false); + return Objects.requireNonNull(super.getStateForPlacement(context)).setValue(CorruptedBeaconBlock.LIT, false); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(LIT); + builder.add(CorruptedBeaconBlock.LIT); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/CrushingTableBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/CrushingTableBlock.java index b5535b78b0..52fd6b2a8a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/CrushingTableBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/CrushingTableBlock.java @@ -28,23 +28,26 @@ public class CrushingTableBlock extends Block implements SimpleWaterloggedBlock, Block.box(2.0, 12.0, 2.0, 14.0, 16.0, 14.0), Block.box(2.0, 0.0, 2.0, 14.0, 10.0, 14.0), Block.box(4.0, 0.0, 0.0, 12.0, 10.0, 16.0), - Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0)); + Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0) + ); private static final VoxelShape REDUCE_AABB_INTERACTION = Shapes.or( Block.box(2.0, 0.0, 2.0, 14.0, 10.0, 14.0), Block.box(4.0, 0.0, 0.0, 12.0, 10.0, 16.0), - Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0)); - private static final VoxelShape AABB = Shapes.join(Shapes.block(), REDUCE_AABB, BooleanOp.ONLY_FIRST); - private static final VoxelShape INTERACTION_BOX = Shapes.join(Shapes.block(), REDUCE_AABB_INTERACTION, BooleanOp.ONLY_FIRST); + Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0) + ); + private static final VoxelShape AABB = Shapes.join(Shapes.block(), CrushingTableBlock.REDUCE_AABB, BooleanOp.ONLY_FIRST); + private static final VoxelShape INTERACTION_BOX = Shapes.join( + Shapes.block(), CrushingTableBlock.REDUCE_AABB_INTERACTION, BooleanOp.ONLY_FIRST); public CrushingTableBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, false)); + this.registerDefaultState(this.stateDefinition.any().setValue(CrushingTableBlock.WATERLOGGED, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(WATERLOGGED); + builder.add(CrushingTableBlock.WATERLOGGED); } @Override @@ -54,12 +57,12 @@ public VoxelShape getShape( BlockPos blockPos, CollisionContext collisionContext ) { - return AABB; + return CrushingTableBlock.AABB; } @Override protected VoxelShape getInteractionShape(BlockState state, BlockGetter level, BlockPos pos) { - return INTERACTION_BOX; + return CrushingTableBlock.INTERACTION_BOX; } @Override @@ -79,12 +82,12 @@ public BlockState getStateForPlacement(BlockPlaceContext blockPlaceContext) { fluidState = blockPlaceContext.getLevel().getFluidState(blockPos); BlockState state = super.getStateForPlacement(blockPlaceContext); state = null != state ? state : this.defaultBlockState(); - return state.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); + return state.setValue(CrushingTableBlock.WATERLOGGED, fluidState.getType() == Fluids.WATER); } @Override public FluidState getFluidState(BlockState blockState) { - return blockState.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(blockState); + return blockState.getValue(CrushingTableBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(blockState); } @Override @@ -98,7 +101,7 @@ protected BlockState updateShape( BlockState blockState2, RandomSource random ) { - if (blockState.getValue(WATERLOGGED)) { + if (blockState.getValue(CrushingTableBlock.WATERLOGGED)) { ticks.scheduleTick(blockPos, Fluids.WATER, Fluids.WATER.getTickDelay(levelReader)); } return super.updateShape(blockState, levelReader, ticks, blockPos, direction, blockPos2, blockState2, random); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/GiantAnvilBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/GiantAnvilBlock.java index 93f005c092..340835b997 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/GiantAnvilBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/GiantAnvilBlock.java @@ -64,6 +64,8 @@ import net.neoforged.neoforge.common.util.DeferredSoundType; import org.jspecify.annotations.Nullable; +import java.util.List; + public class GiantAnvilBlock extends SimpleMultiPartBlock implements Fallable, IHammerRemovable { public static final ThreadLocal SUPPRESS_DROPS = ThreadLocal.withInitial(() -> false); public static final SoundType SOUND_TYPE = new DeferredSoundType( @@ -82,35 +84,35 @@ public class GiantAnvilBlock extends SimpleMultiPartBlock imple new AABB(12, 13, 12, 16, 16, 16), new AABB(4, 0, 4, 16, 8, 16) ); - protected static final VoxelShape BASE_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, BASE_NW); - protected static final VoxelShape BASE_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, BASE_NW); - protected static final VoxelShape BASE_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, BASE_NW); + protected static final VoxelShape BASE_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, GiantAnvilBlock.BASE_NW); + protected static final VoxelShape BASE_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, GiantAnvilBlock.BASE_NW); + protected static final VoxelShape BASE_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, GiantAnvilBlock.BASE_NW); protected static final VoxelShape BASE_N = ShapeUtil.merge( Block.box(0, 13, 12, 16, 16, 16), Block.box(0, 8, 9, 16, 13, 16), Block.box(0, 0, 4, 16, 8, 16) ); - protected static final VoxelShape BASE_W = ShapeUtil.rotate(Direction.Axis.Y, 90, BASE_N); - protected static final VoxelShape BASE_S = ShapeUtil.rotate(Direction.Axis.Y, 180, BASE_N); - protected static final VoxelShape BASE_E = ShapeUtil.rotate(Direction.Axis.Y, 270, BASE_N); + protected static final VoxelShape BASE_W = ShapeUtil.rotate(Direction.Axis.Y, 90, GiantAnvilBlock.BASE_N); + protected static final VoxelShape BASE_S = ShapeUtil.rotate(Direction.Axis.Y, 180, GiantAnvilBlock.BASE_N); + protected static final VoxelShape BASE_E = ShapeUtil.rotate(Direction.Axis.Y, 270, GiantAnvilBlock.BASE_N); protected static final VoxelShape MID_NW = ShapeUtil.merge( new AABB(12, 0, 12, 16, 10, 16), new AABB(8, 10, 8, 16, 16, 16) ); - protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_NW); - protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_NW); - protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_NW); + protected static final VoxelShape MID_SW = ShapeUtil.rotate(Direction.Axis.Y, 90, GiantAnvilBlock.MID_NW); + protected static final VoxelShape MID_SE = ShapeUtil.rotate(Direction.Axis.Y, 180, GiantAnvilBlock.MID_NW); + protected static final VoxelShape MID_NE = ShapeUtil.rotate(Direction.Axis.Y, 270, GiantAnvilBlock.MID_NW); protected static final VoxelShape MID_N = ShapeUtil.merge( Block.box(0, 0, 12, 16, 9, 16), Block.box(0, 9, 6, 16, 16, 16), Block.box(0, 12, 0, 16, 16, 6) ); - protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, MID_N); - protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, MID_N); - protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, MID_N); + protected static final VoxelShape MID_W = ShapeUtil.rotate(Direction.Axis.Y, 90, GiantAnvilBlock.MID_N); + protected static final VoxelShape MID_S = ShapeUtil.rotate(Direction.Axis.Y, 180, GiantAnvilBlock.MID_N); + protected static final VoxelShape MID_E = ShapeUtil.rotate(Direction.Axis.Y, 270, GiantAnvilBlock.MID_N); private static final ImmutableMap> UPDATE_OFFSET = ImmutableMap.of( Direction.DOWN, @@ -191,8 +193,8 @@ public GiantAnvilBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition .any() - .setValue(HALF, Cube3x3PartHalf.BOTTOM_CENTER) - .setValue(CUBE, GiantAnvilCube.CORNER)); + .setValue(GiantAnvilBlock.HALF, Cube3x3PartHalf.BOTTOM_CENTER) + .setValue(GiantAnvilBlock.CUBE, GiantAnvilCube.CORNER)); } @Override @@ -202,23 +204,23 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - return switch (state.getValue(HALF)) { - case MID_E -> MID_E; - case MID_W -> MID_W; - case MID_N -> MID_N; - case MID_S -> MID_S; - case MID_EN -> MID_NE; - case MID_ES -> MID_SE; - case MID_WN -> MID_NW; - case MID_WS -> MID_SW; - case BOTTOM_E -> BASE_E; - case BOTTOM_W -> BASE_W; - case BOTTOM_N -> BASE_N; - case BOTTOM_S -> BASE_S; - case BOTTOM_EN -> BASE_NE; - case BOTTOM_ES -> BASE_SE; - case BOTTOM_WN -> BASE_NW; - case BOTTOM_WS -> BASE_SW; + return switch (state.getValue(GiantAnvilBlock.HALF)) { + case MID_E -> GiantAnvilBlock.MID_E; + case MID_W -> GiantAnvilBlock.MID_W; + case MID_N -> GiantAnvilBlock.MID_N; + case MID_S -> GiantAnvilBlock.MID_S; + case MID_EN -> GiantAnvilBlock.MID_NE; + case MID_ES -> GiantAnvilBlock.MID_SE; + case MID_WN -> GiantAnvilBlock.MID_NW; + case MID_WS -> GiantAnvilBlock.MID_SW; + case BOTTOM_E -> GiantAnvilBlock.BASE_E; + case BOTTOM_W -> GiantAnvilBlock.BASE_W; + case BOTTOM_N -> GiantAnvilBlock.BASE_N; + case BOTTOM_S -> GiantAnvilBlock.BASE_S; + case BOTTOM_EN -> GiantAnvilBlock.BASE_NE; + case BOTTOM_ES -> GiantAnvilBlock.BASE_SE; + case BOTTOM_WN -> GiantAnvilBlock.BASE_NW; + case BOTTOM_WS -> GiantAnvilBlock.BASE_SW; default -> Shapes.block(); }; } @@ -226,12 +228,12 @@ public VoxelShape getShape( @Override public BlockState placedState(Cube3x3PartHalf part, BlockState state) { return super.placedState(part, state) - .setValue(CUBE, part == Cube3x3PartHalf.MID_CENTER ? GiantAnvilCube.CENTER : GiantAnvilCube.CORNER); + .setValue(GiantAnvilBlock.CUBE, part == Cube3x3PartHalf.MID_CENTER ? GiantAnvilCube.CENTER : GiantAnvilCube.CORNER); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(HALF, CUBE); + builder.add(GiantAnvilBlock.HALF, GiantAnvilBlock.CUBE); } public static BlockState damage(BlockState state) { @@ -269,7 +271,7 @@ public void onLand( ) { level.setBlockAndUpdate(pos, Blocks.AIR.defaultBlockState()); BlockPos belowPos = pos.below(); - if (!canSurvive(state, level, belowPos)) { + if (!this.canSurvive(state, level, belowPos)) { ItemEntity itemEntity = new ItemEntity( level, belowPos.getX(), belowPos.getY(), belowPos.getZ(), ModBlocks.GIANT_ANVIL.asStack()); itemEntity.setDefaultPickUpDelay(); @@ -277,8 +279,8 @@ public void onLand( return; } for (Cube3x3PartHalf part : this.getParts()) { - BlockState newState = state.setValue(HALF, part) - .setValue(CUBE, part == Cube3x3PartHalf.MID_CENTER ? GiantAnvilCube.CENTER : GiantAnvilCube.CORNER); + BlockState newState = state.setValue(GiantAnvilBlock.HALF, part) + .setValue(GiantAnvilBlock.CUBE, part == Cube3x3PartHalf.MID_CENTER ? GiantAnvilCube.CENTER : GiantAnvilCube.CORNER); level.setBlockAndUpdate(belowPos.offset(part.getOffset()), newState); } if (level instanceof ServerLevel serverLevel) { @@ -312,7 +314,7 @@ public void tick( BlockPos pos, RandomSource random ) { - BlockState ringState = level.getBlockState(pos.subtract(state.getValue(HALF).getOffset()).above(3)); + BlockState ringState = level.getBlockState(pos.subtract(state.getValue(GiantAnvilBlock.HALF).getOffset()).above(3)); boolean isHeldByAcceleration = ringState.getBlock() instanceof AccelerationRingBlock && ringState.getValue(AccelerationRingBlock.HALF) == DirectionCube3x3PartHalf.BOTTOM_CENTER @@ -327,14 +329,15 @@ public void tick( if (isHeldByAcceleration || isHeldByDeflection) { return; } - if (state.getValue(HALF) != Cube3x3PartHalf.BOTTOM_CENTER) return; + if (state.getValue(GiantAnvilBlock.HALF) != Cube3x3PartHalf.BOTTOM_CENTER) return; for (Cube3x3PartHalf part : this.getParts()) { if (part.getOffsetY() != 0) continue; if (!FallingBlock.isFree(level.getBlockState(pos.offset(part.getOffset()).below()))) return; } BlockPos above = pos.above(); BlockState state1 = level.getBlockState(above); - if (!state1.is(this) || !state1.hasProperty(HALF) || state1.getValue(HALF) != Cube3x3PartHalf.MID_CENTER) { + if (!state1.is(this) || !state1.hasProperty(GiantAnvilBlock.HALF) || state1.getValue(GiantAnvilBlock.HALF) + != Cube3x3PartHalf.MID_CENTER) { return; } this.removePartsAndUpdate(level, pos); @@ -351,7 +354,7 @@ public void removePartsAndUpdate(Level level, BlockPos pos) { BlockPos bp = bottomCenterPos.offset(part.getOffset()); level.setBlock(bp, level.getBlockState(bp).getFluidState().createLegacyBlock(), 3, 0); } - UPDATE_OFFSET.forEach((direction, offsetList) -> offsetList.forEach(offset -> { + GiantAnvilBlock.UPDATE_OFFSET.forEach((direction, offsetList) -> offsetList.forEach(offset -> { BlockPos updatedPos = bottomCenterPos.offset(offset); BlockPos fromPos = updatedPos.relative(direction); level.neighborShapeChanged( @@ -377,8 +380,8 @@ public void onPlace( BlockState oldState, boolean movedByPiston ) { - if (state.hasProperty(HALF)) { - level.scheduleTick(pos.subtract(state.getValue(HALF).getOffset()), this, this.getDelayAfterPlace()); + if (state.hasProperty(GiantAnvilBlock.HALF)) { + level.scheduleTick(pos.subtract(state.getValue(GiantAnvilBlock.HALF).getOffset()), this, this.getDelayAfterPlace()); } } @@ -393,8 +396,8 @@ protected BlockState updateShape( BlockState neighborState, RandomSource random ) { - if (state.hasProperty(HALF) && level instanceof Level actualLevel) { - actualLevel.scheduleTick(pos.subtract(state.getValue(HALF).getOffset()), this, this.getDelayAfterPlace()); + if (state.hasProperty(GiantAnvilBlock.HALF) && level instanceof Level actualLevel) { + actualLevel.scheduleTick(pos.subtract(state.getValue(GiantAnvilBlock.HALF).getOffset()), this, this.getDelayAfterPlace()); } return super.updateShape(state, level, ticks, pos, direction, neighborPos, neighborState, random); } @@ -427,12 +430,13 @@ public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) return new SimpleMenuProvider( (syncId, inventory, player) -> new AnvilMenu(syncId, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE); + GiantAnvilBlock.CONTAINER_TITLE + ); } @Override - public java.util.List getDrops(BlockState state, LootParams.Builder params) { - if (SUPPRESS_DROPS.get()) return java.util.List.of(); + public List getDrops(BlockState state, LootParams.Builder params) { + if (GiantAnvilBlock.SUPPRESS_DROPS.get()) return List.of(); return super.getDrops(state, params); } @@ -443,11 +447,11 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(HALF, state.getValue(HALF).rotate(rotation)); + return state.setValue(GiantAnvilBlock.HALF, state.getValue(GiantAnvilBlock.HALF).rotate(rotation)); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(HALF, state.getValue(HALF).mirror(mirror)); + return state.setValue(GiantAnvilBlock.HALF, state.getValue(GiantAnvilBlock.HALF).mirror(mirror)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/JewelCraftingTable.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/JewelCraftingTable.java index 81b21c0573..56df151d55 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/JewelCraftingTable.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/JewelCraftingTable.java @@ -42,29 +42,29 @@ public class JewelCraftingTable extends Block implements IHammerRemovable { public JewelCraftingTable(Properties properties) { super(properties); - registerDefaultState(getStateDefinition().any().setValue(FACING, Direction.NORTH)); + this.registerDefaultState(this.getStateDefinition().any().setValue(JewelCraftingTable.FACING, Direction.NORTH)); } @Override public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(JewelCraftingTable.FACING, rotation.rotate(state.getValue(JewelCraftingTable.FACING))); } @Override public BlockState mirror(BlockState state, Mirror mirror) { - return this.rotate(state, mirror.getRotation(state.getValue(FACING))); + return this.rotate(state, mirror.getRotation(state.getValue(JewelCraftingTable.FACING))); } @Nullable @Override public BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(FACING, context.getHorizontalDirection().getOpposite()); + .setValue(JewelCraftingTable.FACING, context.getHorizontalDirection().getOpposite()); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING); + builder.add(JewelCraftingTable.FACING); } @Override @@ -73,7 +73,7 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - return SHAPE; + return JewelCraftingTable.SHAPE; } @Override @@ -97,7 +97,7 @@ protected InteractionResult useWithoutItem(BlockState state, Level level, BlockP inventory, ContainerLevelAccess.create(level, pos) ), - getName() + this.getName() ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeoforgeBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeoforgeBlock.java index 4cce67d71d..2be59659ed 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeoforgeBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeoforgeBlock.java @@ -27,6 +27,7 @@ import net.minecraft.world.level.block.AnvilBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.BlockHitResult; @@ -41,13 +42,13 @@ public class NeoforgeBlock extends BetterAnvilBlock { private static final VoxelShape X_TOP = Block.box(0.0, 10.0, 3.0, 16.0, 16.0, 13.0); private static final VoxelShape Z_LEG1 = Block.box(5.0, 4.0, 4.0, 11.0, 10.0, 12.0); private static final VoxelShape Z_TOP = Block.box(3.0, 10.0, 0.0, 13.0, 16.0, 16.0); - private static final VoxelShape X_AXIS_AABB = Shapes.or(BASE, X_LEG1, X_TOP); - private static final VoxelShape Z_AXIS_AABB = Shapes.or(BASE, Z_LEG1, Z_TOP); + private static final VoxelShape X_AXIS_AABB = Shapes.or(NeoforgeBlock.BASE, NeoforgeBlock.X_LEG1, NeoforgeBlock.X_TOP); + private static final VoxelShape Z_AXIS_AABB = Shapes.or(NeoforgeBlock.BASE, NeoforgeBlock.Z_LEG1, NeoforgeBlock.Z_TOP); public static final Component CONTAINER_TITLE = Component.translatable("container.repair"); @Override public MapCodec codec() { - return simpleCodec(NeoforgeBlock::new); + return BlockBehaviour.simpleCodec(NeoforgeBlock::new); } public NeoforgeBlock(Properties properties) { @@ -66,7 +67,9 @@ public InteractionResult use( BlockHitResult hit ) { if (level.isClientSide()) return InteractionResult.SUCCESS; - ModMenuTypes.open((ServerPlayer) player, state.getMenuProvider(level, pos)); + MenuProvider menuProvider = state.getMenuProvider(level, pos); + if (menuProvider == null) return InteractionResult.PASS; + ModMenuTypes.open((ServerPlayer) player, menuProvider); player.awardStat(Stats.INTERACT_WITH_ANVIL); return InteractionResult.CONSUME; } @@ -76,14 +79,14 @@ public InteractionResult use( return new SimpleMenuProvider( (syncId, inventory, player) -> new NeoforgeMenu(syncId, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE + NeoforgeBlock.CONTAINER_TITLE ); } @Override protected VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - Direction direction = state.getValue(FACING); - return direction.getAxis() == Direction.Axis.X ? X_AXIS_AABB : Z_AXIS_AABB; + Direction direction = state.getValue(AnvilBlock.FACING); + return direction.getAxis() == Direction.Axis.X ? NeoforgeBlock.X_AXIS_AABB : NeoforgeBlock.Z_AXIS_AABB; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeutronIrradiatorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeutronIrradiatorBlock.java index ba4dafebd1..7782323486 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeutronIrradiatorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/NeutronIrradiatorBlock.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.EnumProperty; @@ -41,7 +42,7 @@ public class NeutronIrradiatorBlock extends BaseEntityBlock implements IHammerRe @Override public VoxelShape getShape(BlockState blockState, BlockGetter blockGetter, BlockPos blockPos, CollisionContext collisionContext) { - return MODEL; + return NeutronIrradiatorBlock.MODEL; } @Override @@ -51,7 +52,7 @@ public void onPlace(BlockState state, Level level, BlockPos pos, BlockState oldS @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(TYPE); + builder.add(NeutronIrradiatorBlock.TYPE); } @Override @@ -67,12 +68,12 @@ protected void neighborChanged( public NeutronIrradiatorBlock(Properties properties) { super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(TYPE, IrradiatorType.NEUTRON)); + this.registerDefaultState(this.stateDefinition.any().setValue(NeutronIrradiatorBlock.TYPE, IrradiatorType.NEUTRON)); } @Override protected MapCodec codec() { - return simpleCodec(NeutronIrradiatorBlock::new); + return BlockBehaviour.simpleCodec(NeutronIrradiatorBlock::new); } @Nullable @@ -84,13 +85,13 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Nullable @Override public BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { - return createTickerHelper(type, ModBlockEntities.NEUTRON_IRRADIATOR.get(), - (level1, pos, state1, entity) -> entity.tick(level1, pos, state1)); + return BaseEntityBlock.createTickerHelper(type, ModBlockEntities.NEUTRON_IRRADIATOR.get(), + (level1, pos, state1, entity) -> entity.tick(level1, pos, state1)); } @Override public void animateTick(BlockState state, Level level, BlockPos pos, RandomSource random) { - IrradiatorType type = state.getValue(TYPE); + IrradiatorType type = state.getValue(NeutronIrradiatorBlock.TYPE); if (type == IrradiatorType.NEUTRON) return; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpaceOvercompressorBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpaceOvercompressorBlock.java index 6e00036264..1ae73f5cf5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpaceOvercompressorBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpaceOvercompressorBlock.java @@ -8,6 +8,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import org.jspecify.annotations.Nullable; @@ -18,7 +19,7 @@ public SpaceOvercompressorBlock(Properties properties) { @Override protected MapCodec codec() { - return simpleCodec(SpaceOvercompressorBlock::new); + return BlockBehaviour.simpleCodec(SpaceOvercompressorBlock::new); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpectralAnvilBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpectralAnvilBlock.java index 66829f7cc2..5e84ed0171 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpectralAnvilBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/SpectralAnvilBlock.java @@ -46,21 +46,21 @@ public class SpectralAnvilBlock extends Block implements IHammerRemovable { private static final VoxelShape X_TOP = Block.box(0.0, 10.0, 3.0, 16.0, 16.0, 13.0); private static final VoxelShape Z_LEG1 = Block.box(5.0, 4.0, 4.0, 11.0, 10.0, 12.0); private static final VoxelShape Z_TOP = Block.box(3.0, 10.0, 0.0, 13.0, 16.0, 16.0); - private static final VoxelShape X_AXIS_AABB = Shapes.or(BASE, X_LEG1, X_TOP); - private static final VoxelShape Z_AXIS_AABB = Shapes.or(BASE, Z_LEG1, Z_TOP); + private static final VoxelShape X_AXIS_AABB = Shapes.or(SpectralAnvilBlock.BASE, SpectralAnvilBlock.X_LEG1, SpectralAnvilBlock.X_TOP); + private static final VoxelShape Z_AXIS_AABB = Shapes.or(SpectralAnvilBlock.BASE, SpectralAnvilBlock.Z_LEG1, SpectralAnvilBlock.Z_TOP); /// 幻灵铁砧 public SpectralAnvilBlock(Properties properties) { super(properties); this.registerDefaultState( - this.stateDefinition.any().setValue(FACING, Direction.NORTH).setValue(POWERED, false) + this.stateDefinition.any().setValue(SpectralAnvilBlock.FACING, Direction.NORTH).setValue(SpectralAnvilBlock.POWERED, false) ); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - Direction direction = state.getValue(FACING); - return direction.getAxis() == Direction.Axis.X ? X_AXIS_AABB : Z_AXIS_AABB; + Direction direction = state.getValue(SpectralAnvilBlock.FACING); + return direction.getAxis() == Direction.Axis.X ? SpectralAnvilBlock.X_AXIS_AABB : SpectralAnvilBlock.Z_AXIS_AABB; } @Override @@ -76,13 +76,14 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public @Nullable BlockState getStateForPlacement(BlockPlaceContext context) { return this.defaultBlockState() - .setValue(FACING, context.getHorizontalDirection().getClockWise()) - .setValue(POWERED, context.getLevel().getBlockState(context.getClickedPos().above()).is(ModBlockTags.MAGNET)); + .setValue(SpectralAnvilBlock.FACING, context.getHorizontalDirection().getClockWise()) + .setValue( + SpectralAnvilBlock.POWERED, context.getLevel().getBlockState(context.getClickedPos().above()).is(ModBlockTags.MAGNET)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED); + builder.add(SpectralAnvilBlock.FACING, SpectralAnvilBlock.POWERED); } @Override @@ -108,7 +109,8 @@ public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) return new SimpleMenuProvider( (syncId, inventory, player) -> new AnvilMenu(syncId, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE); + SpectralAnvilBlock.CONTAINER_TITLE + ); } @Override @@ -128,7 +130,7 @@ protected void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSou FallingSpectralBlockEntity.fall( level, pos, - level.getBlockState(pos).setValue(POWERED, false), + level.getBlockState(pos).setValue(SpectralAnvilBlock.POWERED, false), false, true ); @@ -145,12 +147,12 @@ protected void neighborChanged( boolean movedByPiston ) { boolean hasNeighborSignal = MagnetUtil.hasMagnetism(level, pos); - boolean currentPowered = state.getValue(POWERED); + boolean currentPowered = state.getValue(SpectralAnvilBlock.POWERED); if (hasNeighborSignal && !currentPowered) { - level.setBlockAndUpdate(pos, state.setValue(POWERED, true)); + level.setBlockAndUpdate(pos, state.setValue(SpectralAnvilBlock.POWERED, true)); } else if (!hasNeighborSignal && currentPowered) { level.scheduleTick(pos, this, 4); - level.setBlockAndUpdate(pos, state.setValue(POWERED, false)); + level.setBlockAndUpdate(pos, state.setValue(SpectralAnvilBlock.POWERED, false)); } @@ -158,11 +160,11 @@ protected void neighborChanged( @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(SpectralAnvilBlock.FACING, rotation.rotate(state.getValue(SpectralAnvilBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(SpectralAnvilBlock.FACING, mirror.mirror(state.getValue(SpectralAnvilBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/StampingPlatformBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/StampingPlatformBlock.java index 9f1ba40348..d6030328b4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/StampingPlatformBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/StampingPlatformBlock.java @@ -36,28 +36,31 @@ public class StampingPlatformBlock extends Block implements SimpleWaterloggedBlo Block.box(2.0, 12.0, 2.0, 14.0, 16.0, 14.0), Block.box(2.0, 0.0, 2.0, 14.0, 10.0, 14.0), Block.box(4.0, 0.0, 0.0, 12.0, 10.0, 16.0), - Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0)); + Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0) + ); private static final VoxelShape REDUCE_AABB_INTERACTION = Shapes.or( Block.box(2.0, 0.0, 2.0, 14.0, 10.0, 14.0), Block.box(4.0, 0.0, 0.0, 12.0, 10.0, 16.0), - Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0)); - private static final VoxelShape AABB = Shapes.join(Shapes.block(), REDUCE_AABB, BooleanOp.ONLY_FIRST); - private static final VoxelShape INTERACTION_BOX = Shapes.join(Shapes.block(), REDUCE_AABB_INTERACTION, BooleanOp.ONLY_FIRST); + Block.box(0.0, 0.0, 4.0, 16.0, 10.0, 12.0) + ); + private static final VoxelShape AABB = Shapes.join(Shapes.block(), StampingPlatformBlock.REDUCE_AABB, BooleanOp.ONLY_FIRST); + private static final VoxelShape INTERACTION_BOX = Shapes.join( + Shapes.block(), StampingPlatformBlock.REDUCE_AABB_INTERACTION, BooleanOp.ONLY_FIRST); public StampingPlatformBlock(Properties properties) { super(properties); this.registerDefaultState( this.stateDefinition.any() - .setValue(WATERLOGGED, false) - .setValue(FACING, Direction.NORTH) + .setValue(StampingPlatformBlock.WATERLOGGED, false) + .setValue(StampingPlatformBlock.FACING, Direction.NORTH) ); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { super.createBlockStateDefinition(builder); - builder.add(WATERLOGGED); - builder.add(FACING); + builder.add(StampingPlatformBlock.WATERLOGGED); + builder.add(StampingPlatformBlock.FACING); } @Override @@ -67,12 +70,12 @@ public VoxelShape getShape( BlockPos blockPos, CollisionContext collisionContext ) { - return AABB; + return StampingPlatformBlock.AABB; } @Override protected VoxelShape getInteractionShape(BlockState state, BlockGetter level, BlockPos pos) { - return INTERACTION_BOX; + return StampingPlatformBlock.INTERACTION_BOX; } @Override @@ -88,13 +91,14 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { BlockState state = super.getStateForPlacement(context); state = null != state ? state : this.defaultBlockState(); Direction facing = context.getHorizontalDirection().getOpposite(); - return state.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER).setValue(FACING, facing); + return state.setValue(StampingPlatformBlock.WATERLOGGED, fluidState.getType() == Fluids.WATER).setValue( + StampingPlatformBlock.FACING, facing); } @Override public FluidState getFluidState(BlockState blockState) { - return blockState.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(blockState); + return blockState.getValue(StampingPlatformBlock.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(blockState); } @Override @@ -109,7 +113,7 @@ protected BlockState updateShape( BlockState blockState2, RandomSource random ) { - if (blockState.getValue(WATERLOGGED)) { + if (blockState.getValue(StampingPlatformBlock.WATERLOGGED)) { ticks.scheduleTick(blockPos, Fluids.WATER, Fluids.WATER.getTickDelay(levelReader)); } return super.updateShape(blockState, levelReader, ticks, blockPos, direction, blockPos2, blockState2, random); @@ -123,17 +127,17 @@ protected boolean isPathfindable(BlockState state, PathComputationType pathCompu @Override public Vec3 getOffset(Level level, BlockPos pos, BlockState state) { if (!(state.getBlock() instanceof StampingPlatformBlock)) return Vec3.ZERO; - Vec3i normal = state.getValue(FACING).getUnitVec3i(); + Vec3i normal = state.getValue(StampingPlatformBlock.FACING).getUnitVec3i(); return new Vec3(normal.getX(), normal.getY(), normal.getZ()).scale(0.7); } @Override protected BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); + return state.setValue(StampingPlatformBlock.FACING, rotation.rotate(state.getValue(StampingPlatformBlock.FACING))); } @Override protected BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(FACING, mirror.mirror(state.getValue(FACING))); + return state.setValue(StampingPlatformBlock.FACING, mirror.mirror(state.getValue(StampingPlatformBlock.FACING))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/StructureScannerBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/StructureScannerBlock.java index e726902ffe..aa6fb2c5b9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/StructureScannerBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/StructureScannerBlock.java @@ -10,6 +10,7 @@ import net.minecraft.core.Direction; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; @@ -21,6 +22,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; @@ -33,8 +35,11 @@ import net.minecraft.world.phys.shapes.VoxelShape; import org.jspecify.annotations.Nullable; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + public class StructureScannerBlock extends BaseEntityBlock implements IHammerRemovable { - public static final MapCodec CODEC = simpleCodec(StructureScannerBlock::new); + public static final MapCodec CODEC = BlockBehaviour.simpleCodec(StructureScannerBlock::new); public static final EnumProperty FACING = HorizontalDirectionalBlock.FACING; public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public static final BooleanProperty UPSIDE_DOWN = BooleanProperty.create("upside_down"); @@ -49,31 +54,33 @@ public class StructureScannerBlock extends BaseEntityBlock implements IHammerRem ); // 使用 ShapeUtil.rotate 自动生成其他水平朝向 - private static final VoxelShape SHAPE_WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, SHAPE_NORTH); - private static final VoxelShape SHAPE_SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, SHAPE_NORTH); - private static final VoxelShape SHAPE_EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, SHAPE_NORTH); + private static final VoxelShape SHAPE_WEST = ShapeUtil.rotate(Direction.Axis.Y, 90, StructureScannerBlock.SHAPE_NORTH); + private static final VoxelShape SHAPE_SOUTH = ShapeUtil.rotate(Direction.Axis.Y, 180, StructureScannerBlock.SHAPE_NORTH); + private static final VoxelShape SHAPE_EAST = ShapeUtil.rotate(Direction.Axis.Y, 270, StructureScannerBlock.SHAPE_NORTH); // 倒挂状态:使用 Axis.X 旋转 180 度实现 Y 轴翻转 - private static final VoxelShape SHAPE_NORTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_SOUTH); - private static final VoxelShape SHAPE_WEST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_WEST); - private static final VoxelShape SHAPE_SOUTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_NORTH); - private static final VoxelShape SHAPE_EAST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, SHAPE_EAST); + private static final VoxelShape SHAPE_NORTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, StructureScannerBlock.SHAPE_SOUTH); + private static final VoxelShape SHAPE_WEST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, StructureScannerBlock.SHAPE_WEST); + private static final VoxelShape SHAPE_SOUTH_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, StructureScannerBlock.SHAPE_NORTH); + private static final VoxelShape SHAPE_EAST_UPSIDE = ShapeUtil.rotate(Direction.Axis.X, 180, StructureScannerBlock.SHAPE_EAST); public StructureScannerBlock(Properties properties) { super(properties); this.registerDefaultState( - this.stateDefinition.any().setValue(FACING, Direction.NORTH).setValue(POWERED, false).setValue(UPSIDE_DOWN, false) + this.stateDefinition.any().setValue(StructureScannerBlock.FACING, Direction.NORTH) + .setValue(StructureScannerBlock.POWERED, false).setValue( + StructureScannerBlock.UPSIDE_DOWN, false) ); } @Override protected MapCodec codec() { - return CODEC; + return StructureScannerBlock.CODEC; } @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(FACING, POWERED, UPSIDE_DOWN); + protected void createBlockStateDefinition(StateDefinition.Builder builder) { + builder.add(StructureScannerBlock.FACING, StructureScannerBlock.POWERED, StructureScannerBlock.UPSIDE_DOWN); } @Override @@ -84,9 +91,9 @@ public BlockState getStateForPlacement(BlockPlaceContext context) { Direction horizontalFacing = context.getHorizontalDirection().getOpposite(); return this.defaultBlockState() - .setValue(FACING, horizontalFacing) - .setValue(UPSIDE_DOWN, upsideDown) - .setValue(POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); + .setValue(StructureScannerBlock.FACING, horizontalFacing) + .setValue(StructureScannerBlock.UPSIDE_DOWN, upsideDown) + .setValue(StructureScannerBlock.POWERED, context.getLevel().hasNeighborSignal(context.getClickedPos())); } @Override @@ -96,14 +103,14 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - Direction facing = state.getValue(FACING); - boolean upsideDown = state.getValue(UPSIDE_DOWN); + Direction facing = state.getValue(StructureScannerBlock.FACING); + boolean upsideDown = state.getValue(StructureScannerBlock.UPSIDE_DOWN); return switch (facing) { - case SOUTH -> upsideDown ? SHAPE_SOUTH_UPSIDE : SHAPE_SOUTH; - case WEST -> upsideDown ? SHAPE_WEST_UPSIDE : SHAPE_WEST; - case EAST -> upsideDown ? SHAPE_EAST_UPSIDE : SHAPE_EAST; - default -> upsideDown ? SHAPE_NORTH_UPSIDE : SHAPE_NORTH; + case SOUTH -> upsideDown ? StructureScannerBlock.SHAPE_SOUTH_UPSIDE : StructureScannerBlock.SHAPE_SOUTH; + case WEST -> upsideDown ? StructureScannerBlock.SHAPE_WEST_UPSIDE : StructureScannerBlock.SHAPE_WEST; + case EAST -> upsideDown ? StructureScannerBlock.SHAPE_EAST_UPSIDE : StructureScannerBlock.SHAPE_EAST; + default -> upsideDown ? StructureScannerBlock.SHAPE_NORTH_UPSIDE : StructureScannerBlock.SHAPE_NORTH; }; } @@ -155,11 +162,11 @@ protected void neighborChanged( } boolean powered = level.hasNeighborSignal(pos); - boolean wasPowered = state.getValue(POWERED); + boolean wasPowered = state.getValue(StructureScannerBlock.POWERED); // 更新红石状态 if (powered != wasPowered) { - level.setBlock(pos, state.setValue(POWERED, powered), 2); + level.setBlock(pos, state.setValue(StructureScannerBlock.POWERED, powered), 2); } // 收到红石信号时,自动执行扫描并保存 @@ -193,8 +200,8 @@ private void autoScanAndSave(Level level, StructureScannerBlockEntity scannerEnt } // 生成结构名称(使用年月日时分格式:auto-202605221430) - java.time.LocalDateTime now = java.time.LocalDateTime.now(); - java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmm"); + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm"); String structureName = "auto-" + now.format(formatter); // 开始扫描 @@ -215,7 +222,7 @@ public BlockState playerWillDestroy( ItemStack diskStack = scannerEntity.getDiskStack(); if (!diskStack.isEmpty()) { Vec3 vec3 = pos.getCenter(); - net.minecraft.world.entity.item.ItemEntity itemEntity = new net.minecraft.world.entity.item.ItemEntity( + ItemEntity itemEntity = new ItemEntity( level, vec3.x, vec3.y, vec3.z, diskStack ); itemEntity.setDefaultPickUpDelay(); @@ -226,7 +233,7 @@ public BlockState playerWillDestroy( ItemStack outputStack = scannerEntity.getOutputStack(); if (!outputStack.isEmpty()) { Vec3 vec3 = pos.getCenter(); - net.minecraft.world.entity.item.ItemEntity itemEntity = new net.minecraft.world.entity.item.ItemEntity( + ItemEntity itemEntity = new ItemEntity( level, vec3.x, vec3.y, vec3.z, outputStack ); itemEntity.setDefaultPickUpDelay(); diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/TranscendenceAnvilBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/TranscendenceAnvilBlock.java index 816941da0b..d289237eb9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/TranscendenceAnvilBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/TranscendenceAnvilBlock.java @@ -21,6 +21,7 @@ import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.AnvilBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; @@ -37,8 +38,8 @@ public class TranscendenceAnvilBlock extends BetterAnvilBlock implements IHammer Block.box(5.0, 4.0, 5.0, 11.0, 10.0, 11.0)); private static final VoxelShape X_TOP = Block.box(0.0, 10.0, 3.0, 16.0, 16.0, 13.0); private static final VoxelShape Z_TOP = Block.box(3.0, 10.0, 0.0, 13.0, 16.0, 16.0); - private static final VoxelShape X_AXIS_AABB = Shapes.or(BASE, X_TOP); - private static final VoxelShape Z_AXIS_AABB = Shapes.or(BASE, Z_TOP); + private static final VoxelShape X_AXIS_AABB = Shapes.or(TranscendenceAnvilBlock.BASE, TranscendenceAnvilBlock.X_TOP); + private static final VoxelShape Z_AXIS_AABB = Shapes.or(TranscendenceAnvilBlock.BASE, TranscendenceAnvilBlock.Z_TOP); private static final Component CONTAINER_TITLE = Component.translatable("container.repair"); private BlockState checkBlockState; @@ -49,9 +50,9 @@ public TranscendenceAnvilBlock(Properties properties) { @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { - Direction direction = state.getValue(FACING); - if (direction.getAxis() == Direction.Axis.X) return X_AXIS_AABB; - return Z_AXIS_AABB; + Direction direction = state.getValue(AnvilBlock.FACING); + if (direction.getAxis() == Direction.Axis.X) return TranscendenceAnvilBlock.X_AXIS_AABB; + return TranscendenceAnvilBlock.Z_AXIS_AABB; } @Override @@ -67,7 +68,8 @@ public InteractionResult use(BlockState state, Level level, BlockPos pos, Player public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) { return new SimpleMenuProvider( (i, inventory, player) -> new TranscendenceAnvilMenu(i, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE); + TranscendenceAnvilBlock.CONTAINER_TITLE + ); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/TransparentCraftingTableBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/TransparentCraftingTableBlock.java index 89b7e05d06..b3c68632c2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/TransparentCraftingTableBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/TransparentCraftingTableBlock.java @@ -37,12 +37,12 @@ public class TransparentCraftingTableBlock extends TransparentBlock implements I public TransparentCraftingTableBlock(Properties properties) { super(properties); - registerDefaultState(stateDefinition.any().setValue(TYPE, Type.SINGLE)); + this.registerDefaultState(this.stateDefinition.any().setValue(TransparentCraftingTableBlock.TYPE, Type.SINGLE)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(TYPE); + builder.add(TransparentCraftingTableBlock.TYPE); } @Override @@ -83,12 +83,16 @@ protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState o if (this.tryFormMatrix(level, pos)) { return; } - if (state.getValue(TYPE) != Type.SINGLE) level.setBlockAndUpdate(pos, state.setValue(TYPE, Type.SINGLE)); + if (state.getValue(TransparentCraftingTableBlock.TYPE) != Type.SINGLE) { + level.setBlockAndUpdate(pos, state.setValue( + TransparentCraftingTableBlock.TYPE, Type.SINGLE) + ); + } Direction.Plane.HORIZONTAL.stream() .map(pos::relative) .filter(poz -> { BlockState adjacentState = level.getBlockState(poz); - return adjacentState.is(this) && adjacentState.getValue(TYPE) != Type.SINGLE; + return adjacentState.is(this) && adjacentState.getValue(TransparentCraftingTableBlock.TYPE) != Type.SINGLE; }) .forEach(poz -> this.deformMatrix(level, poz)); } @@ -96,7 +100,7 @@ protected void onPlace(BlockState state, Level level, BlockPos pos, BlockState o @Override protected void affectNeighborsAfterRemoval(BlockState state, ServerLevel level, BlockPos pos, boolean movedByPiston) { super.affectNeighborsAfterRemoval(state, level, pos, movedByPiston); - if (state.getValue(TYPE) != Type.SINGLE) { + if (state.getValue(TransparentCraftingTableBlock.TYPE) != Type.SINGLE) { this.deformMatrix(level, pos); return; } @@ -123,7 +127,7 @@ protected BlockState updateShape( if (this.tryFormMatrix(actualLevel, pos)) { return state; } - if (state.getValue(TYPE) != Type.SINGLE && !this.isValidMatrixBlock(neighborState, false)) { + if (state.getValue(TransparentCraftingTableBlock.TYPE) != Type.SINGLE && !this.isValidMatrixBlock(neighborState, false)) { this.deformMatrix(actualLevel, pos); return state; } @@ -188,7 +192,7 @@ private boolean tryFormMatrix(Level level, BlockPos pos) { int indexZ = z == maxZ ? 2 : (z > minZ ? 1 : 0); BlockState state = level.getBlockState(mpos.set(x, y0, z)); if (!state.is(this)) continue; - level.setBlockAndUpdate(mpos, state.setValue(TYPE, Type.LOOKUP[indexX][indexZ])); + level.setBlockAndUpdate(mpos, state.setValue(TransparentCraftingTableBlock.TYPE, Type.LOOKUP[indexX][indexZ])); } } return true; @@ -225,7 +229,7 @@ private void deformMatrix(Level level, BlockPos pos) { for (int z = minZ; z <= maxZ; z++) { BlockState state = level.getBlockState(mpos.set(x, y0, z)); if (!state.is(this)) continue; - level.setBlockAndUpdate(mpos, state.setValue(TYPE, Type.SINGLE)); + level.setBlockAndUpdate(mpos, state.setValue(TransparentCraftingTableBlock.TYPE, Type.SINGLE)); } } } @@ -253,19 +257,19 @@ public enum Type implements StringRepresentable { public static final Type[][] LOOKUP = { { - CORNER_NORTH_WEST, - SIDE_WEST, - CORNER_SOUTH_WEST + Type.CORNER_NORTH_WEST, + Type.SIDE_WEST, + Type.CORNER_SOUTH_WEST }, { - SIDE_NORTH, - CENTER, - SIDE_SOUTH + Type.SIDE_NORTH, + Type.CENTER, + Type.SIDE_SOUTH }, { - CORNER_NORTH_EAST, - SIDE_EAST, - CORNER_SOUTH_EAST + Type.CORNER_NORTH_EAST, + Type.SIDE_EAST, + Type.CORNER_SOUTH_EAST } }; diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberAnvilBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberAnvilBlock.java index e259c591bf..257116f01e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberAnvilBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberAnvilBlock.java @@ -23,6 +23,7 @@ import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.AnvilBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; @@ -39,8 +40,8 @@ public class EmberAnvilBlock extends BetterAnvilBlock implements IHammerRemovabl private static final VoxelShape X_TOP = Block.box(0.0, 10.0, 3.0, 16.0, 16.0, 13.0); private static final VoxelShape Z_LEG1 = Block.box(5.0, 4.0, 4.0, 11.0, 10.0, 12.0); private static final VoxelShape Z_TOP = Block.box(3.0, 10.0, 0.0, 13.0, 16.0, 16.0); - private static final VoxelShape X_AXIS_AABB = Shapes.or(BASE, X_LEG1, X_TOP); - private static final VoxelShape Z_AXIS_AABB = Shapes.or(BASE, Z_LEG1, Z_TOP); + private static final VoxelShape X_AXIS_AABB = Shapes.or(EmberAnvilBlock.BASE, EmberAnvilBlock.X_LEG1, EmberAnvilBlock.X_TOP); + private static final VoxelShape Z_AXIS_AABB = Shapes.or(EmberAnvilBlock.BASE, EmberAnvilBlock.Z_LEG1, EmberAnvilBlock.Z_TOP); private static final Component CONTAINER_TITLE = Component.translatable("container.repair"); private BlockState checkBlockState; @@ -55,11 +56,11 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - Direction direction = state.getValue(FACING); + Direction direction = state.getValue(AnvilBlock.FACING); if (direction.getAxis() == Direction.Axis.X) { - return X_AXIS_AABB; + return EmberAnvilBlock.X_AXIS_AABB; } - return Z_AXIS_AABB; + return EmberAnvilBlock.Z_AXIS_AABB; } @Override @@ -82,7 +83,8 @@ public InteractionResult use( public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) { return new SimpleMenuProvider( (i, inventory, player) -> new EmberAnvilMenu(i, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE); + EmberAnvilBlock.CONTAINER_TITLE + ); } @Override @@ -102,7 +104,7 @@ public void randomTick( BlockPos pos, RandomSource random) { if (random.nextDouble() <= 0.5) { - tryAbsorbWater(level, pos); + this.tryAbsorbWater(level, pos); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberGrindstoneBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberGrindstoneBlock.java index c32be39966..9a23f6428b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberGrindstoneBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberGrindstoneBlock.java @@ -42,7 +42,7 @@ public InteractionResult use( BlockHitResult hit ) { if (level.isClientSide()) return InteractionResult.SUCCESS; - ModMenuTypes.open((ServerPlayer) player, state.getMenuProvider(level, pos)); + ModMenuTypes.open((ServerPlayer) player, this.getMenuProvider(state, level, pos)); player.awardStat(Stats.INTERACT_WITH_GRINDSTONE); return InteractionResult.CONSUME; } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberSmithingTableBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberSmithingTableBlock.java index 4dafe6b5de..23d0f6dd32 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberSmithingTableBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/ember/EmberSmithingTableBlock.java @@ -79,7 +79,8 @@ public InteractionResult use( public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) { return new SimpleMenuProvider( (i, inventory, player) -> new EmberSmithingMenu(i, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE); + EmberSmithingTableBlock.CONTAINER_TITLE + ); } @Override @@ -94,7 +95,7 @@ public void randomTick( BlockPos pos, RandomSource random) { if (random.nextDouble() <= 0.5) { - tryAbsorbWater(level, pos); + this.tryAbsorbWater(level, pos); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostAnvilBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostAnvilBlock.java index 5216a44891..e9931f7862 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostAnvilBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostAnvilBlock.java @@ -19,6 +19,7 @@ import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.AnvilBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; @@ -33,8 +34,8 @@ public class FrostAnvilBlock extends BetterAnvilBlock implements IHammerRemovabl private static final VoxelShape X_TOP = Block.box(0.0, 10.0, 3.0, 16.0, 16.0, 13.0); private static final VoxelShape Z_LEG1 = Block.box(5.0, 4.0, 4.0, 11.0, 10.0, 12.0); private static final VoxelShape Z_TOP = Block.box(3.0, 10.0, 0.0, 13.0, 16.0, 16.0); - private static final VoxelShape X_AXIS_AABB = Shapes.or(BASE, X_LEG1, X_TOP); - private static final VoxelShape Z_AXIS_AABB = Shapes.or(BASE, Z_LEG1, Z_TOP); + private static final VoxelShape X_AXIS_AABB = Shapes.or(FrostAnvilBlock.BASE, FrostAnvilBlock.X_LEG1, FrostAnvilBlock.X_TOP); + private static final VoxelShape Z_AXIS_AABB = Shapes.or(FrostAnvilBlock.BASE, FrostAnvilBlock.Z_LEG1, FrostAnvilBlock.Z_TOP); private static final Component CONTAINER_TITLE = Component.translatable("container.repair"); public FrostAnvilBlock(Properties properties) { @@ -48,9 +49,9 @@ public VoxelShape getShape( BlockPos pos, CollisionContext context ) { - Direction direction = state.getValue(FACING); - if (direction.getAxis() == Direction.Axis.X) return X_AXIS_AABB; - return Z_AXIS_AABB; + Direction direction = state.getValue(AnvilBlock.FACING); + if (direction.getAxis() == Direction.Axis.X) return FrostAnvilBlock.X_AXIS_AABB; + return FrostAnvilBlock.Z_AXIS_AABB; } @Override @@ -72,7 +73,7 @@ public InteractionResult use( public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) { return new SimpleMenuProvider( (i, inventory, player) -> new FrostAnvilMenu(i, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE + FrostAnvilBlock.CONTAINER_TITLE ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostSmithingTableBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostSmithingTableBlock.java index c6263640d2..d86893ee3c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostSmithingTableBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/frost/FrostSmithingTableBlock.java @@ -23,7 +23,7 @@ public FrostSmithingTableBlock(Properties properties) { public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) { return new SimpleMenuProvider( (i, inventory, player) -> new FrostSmithingMenu(i, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE + FrostSmithingTableBlock.CONTAINER_TITLE ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalAnvilBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalAnvilBlock.java index 3a590c54e2..c885aae5fc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalAnvilBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalAnvilBlock.java @@ -18,6 +18,7 @@ import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.AnvilBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; @@ -32,8 +33,8 @@ public class RoyalAnvilBlock extends BetterAnvilBlock implements IHammerRemovabl private static final VoxelShape X_TOP = Block.box(0.0, 10.0, 3.0, 16.0, 16.0, 13.0); private static final VoxelShape Z_LEG1 = Block.box(5.0, 4.0, 4.0, 11.0, 10.0, 12.0); private static final VoxelShape Z_TOP = Block.box(3.0, 10.0, 0.0, 13.0, 16.0, 16.0); - private static final VoxelShape X_AXIS_AABB = Shapes.or(BASE, X_LEG1, X_TOP); - private static final VoxelShape Z_AXIS_AABB = Shapes.or(BASE, Z_LEG1, Z_TOP); + private static final VoxelShape X_AXIS_AABB = Shapes.or(RoyalAnvilBlock.BASE, RoyalAnvilBlock.X_LEG1, RoyalAnvilBlock.X_TOP); + private static final VoxelShape Z_AXIS_AABB = Shapes.or(RoyalAnvilBlock.BASE, RoyalAnvilBlock.Z_LEG1, RoyalAnvilBlock.Z_TOP); private static final Component CONTAINER_TITLE = Component.translatable("container.repair"); public RoyalAnvilBlock(Properties properties) { @@ -46,11 +47,11 @@ public VoxelShape getShape( BlockGetter level, BlockPos pos, CollisionContext context) { - Direction direction = state.getValue(FACING); + Direction direction = state.getValue(AnvilBlock.FACING); if (direction.getAxis() == Direction.Axis.X) { - return X_AXIS_AABB; + return RoyalAnvilBlock.X_AXIS_AABB; } - return Z_AXIS_AABB; + return RoyalAnvilBlock.Z_AXIS_AABB; } @Override @@ -72,7 +73,8 @@ public InteractionResult use( public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) { return new SimpleMenuProvider( (i, inventory, player) -> new RoyalAnvilMenu(i, inventory, ContainerLevelAccess.create(level, pos)), - CONTAINER_TITLE); + RoyalAnvilBlock.CONTAINER_TITLE + ); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalGrindstoneBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalGrindstoneBlock.java index 892bb6b182..190fb379cc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalGrindstoneBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalGrindstoneBlock.java @@ -45,7 +45,8 @@ public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) inventory, ContainerLevelAccess.create(level, pos) ), - CONTAINER_TITLE); + RoyalGrindstoneBlock.CONTAINER_TITLE + ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalSmithingTableBlock.java b/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalSmithingTableBlock.java index 1fb80bd2c1..b40acf83f7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalSmithingTableBlock.java +++ b/src/main/java/dev/dubhe/anvilcraft/block/workstation/royal/RoyalSmithingTableBlock.java @@ -26,7 +26,7 @@ public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) inventory, ContainerLevelAccess.create(level, pos) ), - CONTAINER_TITLE + RoyalSmithingTableBlock.CONTAINER_TITLE ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/AnvilCraftClient.java b/src/main/java/dev/dubhe/anvilcraft/client/AnvilCraftClient.java index 25c27f9983..08345e6ee8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/AnvilCraftClient.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/AnvilCraftClient.java @@ -64,15 +64,15 @@ public class AnvilCraftClient { public static PillSelectorSupport pillSelectorSupport = PillSelectorSupport.INSTANCE; public AnvilCraftClient(IEventBus modBus, ModContainer container) { - modEventBus = modBus; - modContainer = container; + AnvilCraftClient.modEventBus = modBus; + AnvilCraftClient.modContainer = container; InspectionSupport.initializeClient(); } @SubscribeEvent public static void clientSetup(FMLClientSetupEvent event) { - IntegrationHook.setModEventBus(modEventBus); - IntegrationHook.setModContainer(modContainer); + IntegrationHook.setModEventBus(AnvilCraftClient.modEventBus); + IntegrationHook.setModContainer(AnvilCraftClient.modContainer); AnvilCraft.getINTEGRATION_MANAGER().loadAllClientIntegrations(); event.enqueueWork(() -> { CachedBlockEntityRenderDispatcher.INSTANCE.registerRenderer( diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/ClientBlockEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/ClientBlockEventListener.java index 0e58c009d0..6a390e653c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/ClientBlockEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/ClientBlockEventListener.java @@ -38,21 +38,21 @@ public class ClientBlockEventListener { public static void onCreativeCrateAttack(PlayerInteractEvent.LeftClickBlock event) { if (event.getAction() != PlayerInteractEvent.LeftClickBlock.Action.START) return; if (!event.getLevel().getBlockState(event.getPos()).is(ModBlocks.CREATIVE_CRATE.get())) return; - creativeCrateAttackPos = event.getPos().immutable(); - attackWasDown = true; + ClientBlockEventListener.creativeCrateAttackPos = event.getPos().immutable(); + ClientBlockEventListener.attackWasDown = true; } @SubscribeEvent public static void onClientTick(ClientTickEvent.Post event) { Minecraft client = Minecraft.getInstance(); boolean attackDown = client.options.keyAttack.isDown(); - if (attackWasDown && !attackDown && creativeCrateAttackPos != null) { - ClientPacketDistributor.sendToServer(new CreativeCrateAttackPacket(creativeCrateAttackPos)); - creativeCrateAttackPos = null; + if (ClientBlockEventListener.attackWasDown && !attackDown && ClientBlockEventListener.creativeCrateAttackPos != null) { + ClientPacketDistributor.sendToServer(new CreativeCrateAttackPacket(ClientBlockEventListener.creativeCrateAttackPos)); + ClientBlockEventListener.creativeCrateAttackPos = null; } - attackWasDown = attackDown; + ClientBlockEventListener.attackWasDown = attackDown; if (client.level == null) { - creativeCrateAttackPos = null; + ClientBlockEventListener.creativeCrateAttackPos = null; } } @@ -84,7 +84,7 @@ public static void anvilHammerUse(PlayerInteractEvent.RightClickBlock event) { if (entity.isShiftKeyDown() && !state.is(ModBlockTags.HAMMER_REMOVABLE) && !(state.getBlock() instanceof IHammerRemovable)) { return; } - if (event.getLevel().isClientSide() && clientHandle(event, state, hand, event.getHitVec())) { + if (event.getLevel().isClientSide() && ClientBlockEventListener.clientHandle(event, state, hand, event.getHitVec())) { event.setCancellationResult(InteractionResult.SUCCESS); event.setCanceled(true); } else if (!state.is(BlockTags.CAULDRONS) && !state.is(ModBlockTags.ANVIL_HAMMER_BLACKLIST)) { diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/ClientEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/ClientEventListener.java index b6aacb7f22..fecd81c9b6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/ClientEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/ClientEventListener.java @@ -13,6 +13,7 @@ import dev.dubhe.anvilcraft.client.init.ModTextureAtlases; import dev.dubhe.anvilcraft.client.support.AmuletSelectorSupport; import dev.dubhe.anvilcraft.client.support.FilterSelectorSupport; +import dev.dubhe.anvilcraft.client.support.ScreenShakeManager; import dev.dubhe.anvilcraft.client.support.SeismicBounceManager; import dev.dubhe.anvilcraft.client.support.StructureDiskPreviewSupport; import dev.dubhe.anvilcraft.init.block.ModBlocks; @@ -137,9 +138,9 @@ public static void onScreenKeyReleased(ScreenEvent.KeyReleased.Post event) { @SubscribeEvent public static void onClientTick(ClientTickEvent.Post event) { - handleAttackKeyRelease(); + ClientEventListener.handleAttackKeyRelease(); SeismicBounceManager.getInstance().tick(); - dev.dubhe.anvilcraft.client.support.ScreenShakeManager.getInstance().tick(); + ScreenShakeManager.getInstance().tick(); long lastThoughtTime = ThoughtManager.getLastThoughtTime(); if (lastThoughtTime < 0) { return; @@ -173,17 +174,17 @@ public static void onMouseButton(InputEvent.MouseButton.Post event) { || minecraft.options.keyAttack.getKey().getValue() != event.getButton()) { return; } - sendDragonRodStopDevourPacket(minecraft); - wasAttackDown = false; + ClientEventListener.sendDragonRodStopDevourPacket(minecraft); + ClientEventListener.wasAttackDown = false; } private static void handleAttackKeyRelease() { Minecraft minecraft = Minecraft.getInstance(); boolean attackDown = minecraft.options.keyAttack.isDown(); - if (wasAttackDown && !attackDown) { - sendDragonRodStopDevourPacket(minecraft); + if (ClientEventListener.wasAttackDown && !attackDown) { + ClientEventListener.sendDragonRodStopDevourPacket(minecraft); } - wasAttackDown = attackDown; + ClientEventListener.wasAttackDown = attackDown; } private static void sendDragonRodStopDevourPacket(Minecraft minecraft) { diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/EnergyWeaponSoundHandler.java b/src/main/java/dev/dubhe/anvilcraft/client/event/EnergyWeaponSoundHandler.java index b310fda462..e74d2891d5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/EnergyWeaponSoundHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/EnergyWeaponSoundHandler.java @@ -34,27 +34,27 @@ public static void onClientTick(ClientTickEvent.Post event) { Minecraft minecraft = Minecraft.getInstance(); if (minecraft.level == null || minecraft.isPaused()) return; - ACTIVE_SOUNDS.entrySet().removeIf(entry -> entry.getValue().isStopped()); + EnergyWeaponSoundHandler.ACTIVE_SOUNDS.entrySet().removeIf(entry -> entry.getValue().isStopped()); for (Player player : minecraft.level.players()) { - WeaponSound required = getRequiredSound(player); - FollowingWeaponSound active = ACTIVE_SOUNDS.get(player.getUUID()); + WeaponSound required = EnergyWeaponSoundHandler.getRequiredSound(player); + FollowingWeaponSound active = EnergyWeaponSoundHandler.ACTIVE_SOUNDS.get(player.getUUID()); if (active != null && active.type != required) { active.finish(); - ACTIVE_SOUNDS.remove(player.getUUID()); + EnergyWeaponSoundHandler.ACTIVE_SOUNDS.remove(player.getUUID()); active = null; } if (required == null || active != null) continue; FollowingWeaponSound sound = new FollowingWeaponSound(player, required); - ACTIVE_SOUNDS.put(player.getUUID(), sound); + EnergyWeaponSoundHandler.ACTIVE_SOUNDS.put(player.getUUID(), sound); minecraft.getSoundManager().play(sound); } } @SubscribeEvent public static void onLogout(ClientPlayerNetworkEvent.LoggingOut event) { - ACTIVE_SOUNDS.values().forEach(FollowingWeaponSound::finish); - ACTIVE_SOUNDS.clear(); + EnergyWeaponSoundHandler.ACTIVE_SOUNDS.values().forEach(FollowingWeaponSound::finish); + EnergyWeaponSoundHandler.ACTIVE_SOUNDS.clear(); } private static @Nullable WeaponSound getRequiredSound(Player player) { @@ -105,7 +105,7 @@ public boolean canPlaySound() { @Override public void tick() { - if (this.player.isRemoved() || getRequiredSound(this.player) != this.type) { + if (this.player.isRemoved() || EnergyWeaponSoundHandler.getRequiredSound(this.player) != this.type) { this.stop(); return; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/HammerEffectRenderEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/HammerEffectRenderEventListener.java index e076767c00..69ddc852ed 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/HammerEffectRenderEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/HammerEffectRenderEventListener.java @@ -5,7 +5,6 @@ import dev.anvilcraft.lib.v2.util.Util; import dev.dubhe.anvilcraft.AnvilCraft; import dev.dubhe.anvilcraft.api.hammer.IHasHammerEffect; -import dev.dubhe.anvilcraft.mixin.accessor.LevelRendererAccessor; import lombok.extern.slf4j.Slf4j; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.BlockModelRenderState; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/IonoCraftBackpackClientHandler.java b/src/main/java/dev/dubhe/anvilcraft/client/event/IonoCraftBackpackClientHandler.java index 4e00ee0a8d..c27a0ed006 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/IonoCraftBackpackClientHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/IonoCraftBackpackClientHandler.java @@ -15,6 +15,7 @@ import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.neoforge.client.event.ClientTickEvent; +import org.jspecify.annotations.Nullable; import java.util.Collections; import java.util.Set; @@ -33,16 +34,16 @@ public class IonoCraftBackpackClientHandler { /** 服务器同步的正在用背包飞行的玩家 entityId 集合 */ private static final Set SYNCED_FLYING_PLAYERS = Collections.newSetFromMap(new ConcurrentHashMap<>()); /** 上一个 level 引用,用于检测世界切换/断连并清理飞行集合 */ - private static ClientLevel lastLevel = null; + private static @Nullable ClientLevel lastLevel; /** * 由 {@code IonoCraftBackpackFlyingPacket} 在客户端调用,记录服务器同步的飞行状态。 */ public static void onFlyingSync(int playerId, boolean flying) { if (flying) { - SYNCED_FLYING_PLAYERS.add(playerId); + IonoCraftBackpackClientHandler.SYNCED_FLYING_PLAYERS.add(playerId); } else { - SYNCED_FLYING_PLAYERS.remove(playerId); + IonoCraftBackpackClientHandler.SYNCED_FLYING_PLAYERS.remove(playerId); } } @@ -55,9 +56,9 @@ public static void onClientTick(ClientTickEvent.Post event) { ClientLevel level = minecraft.level; // 世界切换或重连时清空旧的飞行状态集合,防止内存泄漏 - if (lastLevel != level) { - lastLevel = level; - SYNCED_FLYING_PLAYERS.clear(); + if (IonoCraftBackpackClientHandler.lastLevel != level) { + IonoCraftBackpackClientHandler.lastLevel = level; + IonoCraftBackpackClientHandler.SYNCED_FLYING_PLAYERS.clear(); } LocalPlayer localPlayer = minecraft.player; boolean firstPerson = minecraft.options.getCameraType() == CameraType.FIRST_PERSON; @@ -74,10 +75,10 @@ public static void onClientTick(ClientTickEvent.Post event) { // 本地玩家用精确 abilities;远程玩家用服务器同步的精确状态 boolean flying = player == localPlayer ? player.getAbilities().flying - : SYNCED_FLYING_PLAYERS.contains(player.getId()); + : IonoCraftBackpackClientHandler.SYNCED_FLYING_PLAYERS.contains(player.getId()); if (!flying) continue; - spawnExhaustParticles(level, player, player.getRandom()); + IonoCraftBackpackClientHandler.spawnExhaustParticles(level, player, player.getRandom()); } } @@ -86,18 +87,20 @@ private static void spawnExhaustParticles(ClientLevel level, Player player, Rand double cosYaw = Math.cos(yawRad); double sinYaw = Math.sin(yawRad); - double backX = sinYaw; double backZ = -cosYaw; - double[][] exhausts = {{SIDE_OFFSET, BACK_OFFSET}, {-SIDE_OFFSET, BACK_OFFSET}}; + double[][] exhausts = { + {IonoCraftBackpackClientHandler.SIDE_OFFSET, IonoCraftBackpackClientHandler.BACK_OFFSET}, + {-IonoCraftBackpackClientHandler.SIDE_OFFSET, IonoCraftBackpackClientHandler.BACK_OFFSET} + }; for (double[] exhaust : exhausts) { double sideComp = exhaust[0]; double backComp = exhaust[1]; - double worldX = player.getX() + sideComp * (-cosYaw) + backComp * backX; + double worldX = player.getX() + sideComp * (-cosYaw) + backComp * sinYaw; double worldZ = player.getZ() + sideComp * (-sinYaw) + backComp * backZ; - double worldY = player.getY() + Y_OFFSET; + double worldY = player.getY() + IonoCraftBackpackClientHandler.Y_OFFSET; double velX = random.nextGaussian() * 0.02; double velY = -0.3 - random.nextFloat() * 0.3; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/LargeBlockPlacePreviewEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/LargeBlockPlacePreviewEventListener.java index 087f986bfa..b0c6229410 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/LargeBlockPlacePreviewEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/LargeBlockPlacePreviewEventListener.java @@ -35,6 +35,7 @@ import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.neoforge.client.event.ClientTickEvent; import net.neoforged.neoforge.client.event.ExtractBlockOutlineRenderStateEvent; +import org.jspecify.annotations.Nullable; import java.util.List; @@ -45,30 +46,30 @@ public class LargeBlockPlacePreviewEventListener { private static int boundColor = 0xffffffff; - private static final Runnable changeBoundColorRed = () -> boundColor = 0xffff0000; - private static final Runnable changeBoundColorWhite = () -> boundColor = 0xffffffff; + private static final Runnable changeBoundColorRed = () -> LargeBlockPlacePreviewEventListener.boundColor = 0xffff0000; + private static final Runnable changeBoundColorWhite = () -> LargeBlockPlacePreviewEventListener.boundColor = 0xffffffff; private static ItemStack currentItem = ItemStack.EMPTY; - private static BlockPos currentPos = null; + private static @Nullable BlockPos currentPos; private static List cachedErrorPosList = new ObjectArrayList<>(); private static final SegmentedActuator animationActuator = new SegmentedActuator( - new SegmentedActuator.Task(2, changeBoundColorRed), - new SegmentedActuator.Task(2, changeBoundColorWhite), - new SegmentedActuator.Task(2, changeBoundColorRed), - new SegmentedActuator.Task(2, changeBoundColorWhite) + new SegmentedActuator.Task(2, LargeBlockPlacePreviewEventListener.changeBoundColorRed), + new SegmentedActuator.Task(2, LargeBlockPlacePreviewEventListener.changeBoundColorWhite), + new SegmentedActuator.Task(2, LargeBlockPlacePreviewEventListener.changeBoundColorRed), + new SegmentedActuator.Task(2, LargeBlockPlacePreviewEventListener.changeBoundColorWhite) ); @SubscribeEvent public static void on(ClientTickEvent.Pre event) { - boundColor = 0xffffffff; - if (failBoundCooldown > 0) { - failBoundCooldown--; - animationActuator.execute(); + LargeBlockPlacePreviewEventListener.boundColor = 0xffffffff; + if (LargeBlockPlacePreviewEventListener.failBoundCooldown > 0) { + LargeBlockPlacePreviewEventListener.failBoundCooldown--; + LargeBlockPlacePreviewEventListener.animationActuator.execute(); } - if (failBoundErrorCooldown > 0) { - failBoundErrorCooldown--; + if (LargeBlockPlacePreviewEventListener.failBoundErrorCooldown > 0) { + LargeBlockPlacePreviewEventListener.failBoundErrorCooldown--; } } @@ -93,16 +94,19 @@ public static void renderHighlight(ExtractBlockOutlineRenderStateEvent event) { } if (item.getItem() instanceof BlockItem blockItem) { if (blockItem.getBlock() instanceof AbstractMultiPartBlock block) { - validateCanRender(item, blockItem, pos); + LargeBlockPlacePreviewEventListener.validateCanRender(item, blockItem, pos); // Build the actual placement state from the hit result - BlockPlaceContext context = new BlockPlaceContext(player, player.getUsedItemHand(), item, new BlockHitResult( + BlockPlaceContext context = new BlockPlaceContext( + player, player.getUsedItemHand(), item, new BlockHitResult( target.getLocation(), direction, target.getBlockPos(), target.isInside() - )); - BlockState placementState = getPlacementState(block, blockItem, context); - Pair> pair = getShapeAndErrorPosList(level, block, pos, placementState); + ) + ); + BlockState placementState = LargeBlockPlacePreviewEventListener.getPlacementState(block, blockItem, context); + Pair> pair = LargeBlockPlacePreviewEventListener.getShapeAndErrorPosList( + level, block, pos, placementState); if (!pair.second().isEmpty()) { if (blockItem instanceof SimpleMultiPartBlockItem simpleMultiPartBlockItem) { int distance = simpleMultiPartBlockItem.getMaxOffsetDistance(direction); @@ -112,7 +116,7 @@ public static void renderHighlight(ExtractBlockOutlineRenderStateEvent event) { int distance = flexibleMultiPartBlockItem.getMaxOffsetDistance(placementState, direction); pos = pos.relative(direction, distance - 1); } - pair = getShapeAndErrorPosList(level, block, pos, placementState); + pair = LargeBlockPlacePreviewEventListener.getShapeAndErrorPosList(level, block, pos, placementState); } TooltipRenderHelper.renderOutline( pose, @@ -122,9 +126,9 @@ public static void renderHighlight(ExtractBlockOutlineRenderStateEvent event) { position.z, pos, pair.first(), - boundColor + LargeBlockPlacePreviewEventListener.boundColor ); - renderErrorBound(pose, consumer, event.getCamera()); + LargeBlockPlacePreviewEventListener.renderErrorBound(pose, consumer, event.getCamera()); } } return false; @@ -159,26 +163,26 @@ private static void validateCanRender( ItemStack item, BlockItem blockItem, BlockPos pos) { - if (currentItem.isEmpty()) { - currentItem = item.copy(); - } else if (!currentItem.is(blockItem)) { - currentItem = ItemStack.EMPTY; - failBoundCooldown = 0; + if (LargeBlockPlacePreviewEventListener.currentItem.isEmpty()) { + LargeBlockPlacePreviewEventListener.currentItem = item.copy(); + } else if (!LargeBlockPlacePreviewEventListener.currentItem.is(blockItem)) { + LargeBlockPlacePreviewEventListener.currentItem = ItemStack.EMPTY; + LargeBlockPlacePreviewEventListener.failBoundCooldown = 0; } - if (currentPos == null) { - currentPos = pos; - } else if (!currentPos.equals(pos)) { - currentPos = null; - failBoundCooldown = 0; + if (LargeBlockPlacePreviewEventListener.currentPos == null) { + LargeBlockPlacePreviewEventListener.currentPos = pos; + } else if (!LargeBlockPlacePreviewEventListener.currentPos.equals(pos)) { + LargeBlockPlacePreviewEventListener.currentPos = null; + LargeBlockPlacePreviewEventListener.failBoundCooldown = 0; } } private static void renderErrorBound(PoseStack poseStack, VertexConsumer vertexConsumer, Camera camera) { Vec3 position = camera.position(); - if (failBoundErrorCooldown <= 0) { + if (LargeBlockPlacePreviewEventListener.failBoundErrorCooldown <= 0) { return; } - for (BlockPos blockPos : cachedErrorPosList) { + for (BlockPos blockPos : LargeBlockPlacePreviewEventListener.cachedErrorPosList) { TooltipRenderHelper.renderOutline( poseStack, vertexConsumer, @@ -204,12 +208,12 @@ private static BlockState getPlacementState(AbstractMultiPartBlock block, Blo } public static void startFailBoundCooldown() { - failBoundCooldown = 8; - animationActuator.reset(); + LargeBlockPlacePreviewEventListener.failBoundCooldown = 8; + LargeBlockPlacePreviewEventListener.animationActuator.reset(); } public static void startFailBoundErrorCooldown(List errorPosList) { - failBoundErrorCooldown = 6; - cachedErrorPosList = new ObjectArrayList<>(errorPosList); + LargeBlockPlacePreviewEventListener.failBoundErrorCooldown = 6; + LargeBlockPlacePreviewEventListener.cachedErrorPosList = new ObjectArrayList<>(errorPosList); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/RegisterAdditionalEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/RegisterAdditionalEventListener.java index 92e457b5b8..5bb2b3c2a1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/RegisterAdditionalEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/RegisterAdditionalEventListener.java @@ -267,7 +267,7 @@ public static void registerModels(ModelEvent.RegisterStandalone event) { SimpleUnbakedStandaloneModel.blockStateModel(AnvilCraft.of("block/celestial_body/planet_hollow"))); event.register(CFARenderer.BODY_PLANET_ERROR, SimpleUnbakedStandaloneModel.blockStateModel(AnvilCraft.of("block/celestial_body/planet_error"))); - registerCelestialBodyModels(event); + RegisterAdditionalEventListener.registerCelestialBodyModels(event); event.register( FishTankRenderer.FIRE, SimpleUnbakedStandaloneModel.blockStateModel(AnvilCraft.of("block/oil_cauldron_fire4")) diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/SeismicBounceRenderEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/SeismicBounceRenderEventListener.java index f14544f99a..1286dc95dd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/SeismicBounceRenderEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/SeismicBounceRenderEventListener.java @@ -15,6 +15,8 @@ import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.neoforge.client.event.SubmitCustomGeometryEvent; +import java.util.Map; + /** * 震波弹跳渲染 —— 直接获取原版光照管线。 * @@ -38,7 +40,7 @@ public static void onRender(SubmitCustomGeometryEvent event) { var poseStack = event.getPoseStack(); var nodeCollector = event.getSubmitNodeCollector(); - submitEntries( + SeismicBounceRenderEventListener.submitEntries( event, SeismicBounceManager.getInstance().getActiveBounces(), camX, @@ -46,7 +48,7 @@ public static void onRender(SubmitCustomGeometryEvent event) { camZ, partialTick ); - submitEntries( + SeismicBounceRenderEventListener.submitEntries( event, SeismicBounceManager.getInstance().getActiveResonances(), camX, @@ -58,7 +60,7 @@ public static void onRender(SubmitCustomGeometryEvent event) { private static void submitEntries( SubmitCustomGeometryEvent event, - java.util.Map entries, + Map entries, double camX, double camY, double camZ, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/SubmitGeometryEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/SubmitGeometryEventListener.java index 22f3081b41..c4bcb91aa0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/SubmitGeometryEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/SubmitGeometryEventListener.java @@ -74,16 +74,16 @@ public static void on(SubmitCustomGeometryEvent event) { nodeCollector.submitCustomGeometry( poseStack, RenderTypes.lines(), ((pose, buffer) -> { if (AnvilHammerItem.shouldRenderEffect(player)) { - renderAffectRange(poseStack, blockHitResult, buffer, camX, camY, camZ); + SubmitGeometryEventListener.renderAffectRange(poseStack, blockHitResult, buffer, camX, camY, camZ); } - renderDragonRodOutline(pose, blockHitResult, buffer, camX, camY, camZ, handItem); + SubmitGeometryEventListener.renderDragonRodOutline(pose, blockHitResult, buffer, camX, camY, camZ, handItem); }) ); } - submitPowerGridLines(poseStack, nodeCollector, camera); + SubmitGeometryEventListener.submitPowerGridLines(poseStack, nodeCollector, camera); } private static void submitPowerGridLines(PoseStack poseStack, SubmitNodeCollector nodeCollector, Vec3 camera) { diff --git a/src/main/java/dev/dubhe/anvilcraft/client/event/WheelLifecycleEventListener.java b/src/main/java/dev/dubhe/anvilcraft/client/event/WheelLifecycleEventListener.java index bd164c146b..8e91037028 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/event/WheelLifecycleEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/event/WheelLifecycleEventListener.java @@ -85,11 +85,13 @@ public class WheelLifecycleEventListener { /** 判断当前是否正在通过长按铁砧锤打开方块状态选择轮。 */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean isHammerWheelOpen() { - return hammerKeyWasDown && hammerWheelCache != null && hammerWheelCache.isPresent(); + return WheelLifecycleEventListener.hammerKeyWasDown && WheelLifecycleEventListener.hammerWheelCache != null + && WheelLifecycleEventListener.hammerWheelCache.isPresent(); } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean isHammerWheelModel(WheelMenuModel model) { - return hammerWheelCache != null && hammerWheelCache.orElse(null) == model; + return WheelLifecycleEventListener.hammerWheelCache != null && WheelLifecycleEventListener.hammerWheelCache.orElse(null) == model; } @SubscribeEvent @@ -152,7 +154,7 @@ public static boolean openHammerWheel( )); } if (WheelLifecycleEventListener.hammerWheelCache.isEmpty()) return false; - CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.hammerWheelCache.get()); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.hammerWheelCache.get()); WheelLifecycleEventListener.hammerKeyWasDown = true; return true; } @@ -180,7 +182,7 @@ private static void openMultiphaseWheel(long gameTime) { ); } if (WheelLifecycleEventListener.multiphaseWheelCache.isEmpty()) return; - CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.multiphaseWheelCache.get()); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.multiphaseWheelCache.get()); WheelLifecycleEventListener.multiphaseKeyWasDown = true; } } @@ -203,11 +205,11 @@ private static void openResonatorWheel(long gameTime) { } if (gameTime - WheelLifecycleEventListener.resonatorKeyTime > 4) { if (WheelLifecycleEventListener.resonatorWheelCache.isEmpty()) return; - CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.resonatorWheelCache.get()); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.resonatorWheelCache.get()); WheelLifecycleEventListener.resonatorKeyWasDown = true; } else { if (WheelLifecycleEventListener.resonatorWheelCache.isEmpty()) return; - CONTROLLER.openTap(WheelLifecycleEventListener.resonatorWheelCache.get()); + WheelLifecycleEventListener.CONTROLLER.openTap(WheelLifecycleEventListener.resonatorWheelCache.get()); } } @@ -229,11 +231,11 @@ private static void openMultitoolWheel(long gameTime) { } if (gameTime - WheelLifecycleEventListener.multitoolKeyTime > 4) { if (WheelLifecycleEventListener.multitoolWheelCache.isEmpty()) return; - CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.multitoolWheelCache.get()); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.multitoolWheelCache.get()); WheelLifecycleEventListener.multitoolKeyWasDown = true; } else { if (WheelLifecycleEventListener.multitoolWheelCache.isEmpty()) return; - CONTROLLER.openTap(WheelLifecycleEventListener.multitoolWheelCache.get()); + WheelLifecycleEventListener.CONTROLLER.openTap(WheelLifecycleEventListener.multitoolWheelCache.get()); } } @@ -307,12 +309,12 @@ private static void openHeavyHalberdWheel(long gameTime) { stack = player.getOffhandItem(); } if (!(stack.getItem() instanceof HeavyHalberdItem)) return; - WheelLifecycleEventListener.heavyHalberdWheelCache = Optional.ofNullable( + WheelLifecycleEventListener.heavyHalberdWheelCache = Optional.of( WheelLifecycleEventListener.getHeavyHalberdWheel(hand, stack) ); } if (WheelLifecycleEventListener.heavyHalberdWheelCache.isEmpty()) return; - CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.heavyHalberdWheelCache.get()); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyPressed(WheelLifecycleEventListener.heavyHalberdWheelCache.get()); WheelLifecycleEventListener.heavyHalberdKeyWasDown = true; } } @@ -321,7 +323,7 @@ private static WheelMenuModel getMultiphaseWheel(InteractionHand hand, ItemStack int phaseCount = multiphase.phases().size(); WheelMenuBuilder builder = WheelMenuBuilder.create().slotsPerPage(phaseCount); for (int i = 0; i < phaseCount; i++) { - addMultiphaseWheelEntry(builder, hand, holding, multiphase, i); + WheelLifecycleEventListener.addMultiphaseWheelEntry(builder, hand, holding, multiphase, i); } return builder.build(); } @@ -616,7 +618,7 @@ private static void processHammerPress(Minecraft client, int action) { if (client.level == null) return; if (action == GLFW.GLFW_RELEASE) { if (WheelLifecycleEventListener.hammerKeyWasDown) { - CONTROLLER.onHoldKeyReleased(); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyReleased(); } WheelLifecycleEventListener.hammerKeyWasDown = false; WheelLifecycleEventListener.hammerKeyTime = -1L; @@ -635,7 +637,7 @@ private static void processMultiphasePress(Minecraft client, int action) { if (client.level == null) return; if (action == GLFW.GLFW_RELEASE) { if (WheelLifecycleEventListener.multiphaseKeyWasDown) { - CONTROLLER.onHoldKeyReleased(); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyReleased(); } else { ClientPacketDistributor.sendToServer(new MultiphasePackets.SwitchPhase()); } @@ -656,7 +658,7 @@ private static void processResonatorPress(Minecraft client, int action) { if (client.level == null) return; if (action == GLFW.GLFW_RELEASE) { if (WheelLifecycleEventListener.resonatorKeyWasDown) { - CONTROLLER.onHoldKeyReleased(); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyReleased(); } WheelLifecycleEventListener.resonatorKeyWasDown = false; WheelLifecycleEventListener.resonatorKeyTime = -1L; @@ -675,7 +677,7 @@ private static void processMultitoolPress(Minecraft client, int action) { if (client.level == null) return; if (action == GLFW.GLFW_RELEASE) { if (WheelLifecycleEventListener.multitoolKeyWasDown) { - CONTROLLER.onHoldKeyReleased(); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyReleased(); } WheelLifecycleEventListener.multitoolKeyWasDown = false; WheelLifecycleEventListener.multitoolKeyTime = -1L; @@ -694,7 +696,7 @@ private static void processHeavyHalberdPress(Minecraft client, int action) { if (client.level == null) return; if (action == GLFW.GLFW_RELEASE) { if (WheelLifecycleEventListener.heavyHalberdKeyWasDown) { - CONTROLLER.onHoldKeyReleased(); + WheelLifecycleEventListener.CONTROLLER.onHoldKeyReleased(); } WheelLifecycleEventListener.heavyHalberdKeyWasDown = false; WheelLifecycleEventListener.heavyHalberdKeyTime = -1L; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CommandEntry.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CommandEntry.java index 2e843bc394..2452fdca52 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CommandEntry.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CommandEntry.java @@ -3,7 +3,6 @@ import dev.dubhe.anvilcraft.AnvilCraft; import lombok.Getter; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.ActiveTextCollector; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.input.InputWithModifiers; @@ -39,11 +38,11 @@ protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mo } this.isHovered = this.isMouseOver(mouseX, mouseY); if (this.isFocused()) { - graphics.horizontalLine(this.getX(), this.getX() + width, this.getY(), -1); - graphics.horizontalLine(this.getX(), this.getX() + width, this.getY() + height, -1); - graphics.verticalLine(this.getX(), this.getY(), this.getY() + height, -1); - graphics.verticalLine(this.getX() + width, this.getY(), this.getY() + height, -1); - graphics.fill(this.getX() + 1, this.getY() + 1, this.getX() + width - 1, this.getY() + height - 1, -16777216); + graphics.horizontalLine(this.getX(), this.getX() + this.width, this.getY(), -1); + graphics.horizontalLine(this.getX(), this.getX() + this.width, this.getY() + this.height, -1); + graphics.verticalLine(this.getX(), this.getY(), this.getY() + this.height, -1); + graphics.verticalLine(this.getX() + this.width, this.getY(), this.getY() + this.height, -1); + graphics.fill(this.getX() + 1, this.getY() + 1, this.getX() + this.width - 1, this.getY() + this.height - 1, -16777216); } Font font = Minecraft.getInstance().font; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CycleFilterModeButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CycleFilterModeButton.java index febfadde88..2962770073 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CycleFilterModeButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/CycleFilterModeButton.java @@ -23,7 +23,7 @@ public class CycleFilterModeButton extends Button { Component.translatable("screen.anvilcraft.button.filter_mode_any")); public CycleFilterModeButton(int x, int y, OnPress onPress, Supplier filterMode) { - super(x, y, 16, 16, DEFAULT_MESSAGE, onPress, Button.DEFAULT_NARRATION); + super(x, y, 16, 16, CycleFilterModeButton.DEFAULT_MESSAGE, onPress, Button.DEFAULT_NARRATION); this.filterMode = filterMode; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/EnableFilterButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/EnableFilterButton.java index 69f376cc9d..f7a3ea5c1e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/EnableFilterButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/EnableFilterButton.java @@ -22,7 +22,7 @@ public class EnableFilterButton extends Button { "screen.anvilcraft.button.record", Component.translatable("screen.anvilcraft.button.off")); public EnableFilterButton(int x, int y, OnPress onPress, Supplier filterEnabled) { - super(x, y, 16, 16, defaultMessage, onPress, var -> defaultMessage); + super(x, y, 16, 16, EnableFilterButton.defaultMessage, onPress, var -> EnableFilterButton.defaultMessage); this.filterEnabled = filterEnabled; } @@ -31,7 +31,7 @@ protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mo if (this.isHovered()) { graphics.tooltip( Minecraft.getInstance().font, - List.of(ClientTooltipComponent.create(getMessage().getVisualOrderText())), + List.of(ClientTooltipComponent.create(this.getMessage().getVisualOrderText())), mouseX, mouseY, DefaultTooltipPositioner.INSTANCE, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/FluidRateSlider.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/FluidRateSlider.java index 50c0892207..9ca8fb4a22 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/FluidRateSlider.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/FluidRateSlider.java @@ -16,7 +16,7 @@ public class FluidRateSlider extends AbstractWidget { public static final int MAX = 2000; public static final int STEP = 50; - private static final int TOTAL_STEPS = MAX / STEP; + private static final int TOTAL_STEPS = FluidRateSlider.MAX / FluidRateSlider.STEP; private final int posX; private final int posY; @@ -35,11 +35,11 @@ public FluidRateSlider(int x, int y, int length, Callback callback) { } public void setValue(int value) { - this.value = clampSnap(value); + this.value = FluidRateSlider.clampSnap(value); } public void setExactValue(int value) { - this.value = Math.clamp(value, 0, MAX); + this.value = Math.clamp(value, 0, FluidRateSlider.MAX); } public void setValueWithUpdate(int value) { @@ -48,7 +48,7 @@ public void setValueWithUpdate(int value) { } public void step(int direction) { - this.setValueWithUpdate(this.value + STEP * direction); + this.setValueWithUpdate(this.value + FluidRateSlider.STEP * direction); } private void update() { @@ -56,12 +56,12 @@ private void update() { } private static int clampSnap(int value) { - int snapped = Math.round((float) value / STEP) * STEP; - return Math.clamp(snapped, 0, MAX); + int snapped = Math.round((float) value / FluidRateSlider.STEP) * FluidRateSlider.STEP; + return Math.clamp(snapped, 0, FluidRateSlider.MAX); } private double proportion() { - return (double) this.value / MAX; + return (double) this.value / FluidRateSlider.MAX; } private int knobX() { @@ -98,8 +98,8 @@ public void onReleased() { private void applyMouse(double mouseX) { double offset = (mouseX - this.posX - 8.0) / (this.length - 16); - int step = (int) Math.round(Math.clamp(offset, 0.0, 1.0) * TOTAL_STEPS); - this.setValueWithUpdate(step * STEP); + int step = (int) Math.round(Math.clamp(offset, 0.0, 1.0) * FluidRateSlider.TOTAL_STEPS); + this.setValueWithUpdate(step * FluidRateSlider.STEP); } @Override @@ -108,7 +108,7 @@ protected void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouse boolean hovered = this.scrolling || this.isInKnob(mouseX, mouseY); graphics.blit( RenderPipelines.GUI_TEXTURED, - SLIDER, + FluidRateSlider.SLIDER, this.knobX(), this.posY, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/OutputDirectionButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/OutputDirectionButton.java index 5e6b22a24a..cb6839499d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/OutputDirectionButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/OutputDirectionButton.java @@ -20,7 +20,7 @@ public class OutputDirectionButton extends Button { "screen.anvilcraft.button.direction", Component.translatable("screen.anvilcraft.button.direction.up")); public OutputDirectionButton(int x, int y, OnPress onPress, Direction direction) { - super(x, y, 16, 16, DEFAULT_MESSAGE, onPress, _ -> DEFAULT_MESSAGE); + super(x, y, 16, 16, OutputDirectionButton.DEFAULT_MESSAGE, onPress, _ -> OutputDirectionButton.DEFAULT_MESSAGE); this.direction = direction; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/RecipeCycleButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/RecipeCycleButton.java index 61119efdde..bd48507c39 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/RecipeCycleButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/RecipeCycleButton.java @@ -20,7 +20,7 @@ public RecipeCycleButton(int x, int y, OnPress onPress) { 18, Component.translatable("screen.anvilcraft.batch_crafter.switch_recipe"), onPress, - DEFAULT_NARRATION + Button.DEFAULT_NARRATION ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SapcetimeSupercomputerCommandSuggestions.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SapcetimeSupercomputerCommandSuggestions.java index 0090db61ca..a567e5553f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SapcetimeSupercomputerCommandSuggestions.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SapcetimeSupercomputerCommandSuggestions.java @@ -11,6 +11,7 @@ import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientSuggestionProvider; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.SharedSuggestionProvider; import net.minecraft.core.RegistryAccess; @@ -18,6 +19,7 @@ import net.minecraft.world.flag.FeatureFlagSet; import java.util.Collection; +import java.util.Objects; import java.util.function.BiConsumer; public class SapcetimeSupercomputerCommandSuggestions extends CommandSuggestions { @@ -82,6 +84,12 @@ public void updateCommandInfo() { } this.commandUsage.clear(); + LocalPlayer player = this.minecraft.player; + if (player == null) { + this.pendingSuggestions = null; + return; + } + ClientSuggestionProvider suggestionProvider = player.connection.getSuggestionsProvider(); StringReader reader = new StringReader(command); boolean startsWithSlash = reader.canRead() && reader.peek() == '/'; if (startsWithSlash) { @@ -91,32 +99,35 @@ public void updateCommandInfo() { boolean isCommand = this.commandsOnly || startsWithSlash; int cursorPosition = this.input.getCursorPosition(); if (isCommand) { - CommandDispatcher commands = buildCommands(this.commandFactory); + CommandDispatcher commands = SapcetimeSupercomputerCommandSuggestions.buildCommands( + this.commandFactory); if (this.currentParse == null) { - this.currentParse = commands.parse(reader, this.minecraft.player.connection.getSuggestionsProvider()); + this.currentParse = commands.parse(reader, suggestionProvider); this.currentParseIsCommand = true; - this.currentParseIsMessage = hasMessageArguments(this.currentParse); + this.currentParseIsMessage = CommandSuggestions.hasMessageArguments(this.currentParse); } + var currentParse = Objects.requireNonNull(this.currentParse); int parseStart = this.onlyShowIfCursorPastError ? reader.getCursor() : 1; if (cursorPosition >= parseStart && (this.suggestions == null || !this.keepSuggestions)) { - this.pendingSuggestions = commands.getCompletionSuggestions(this.currentParse, cursorPosition); - this.pendingSuggestions.thenAccept(suggestionResult -> { - if (this.pendingSuggestions.isDone()) { - this.updateUsageInfo(this.currentParse, suggestionResult); + var pendingSuggestions = commands.getCompletionSuggestions(currentParse, cursorPosition); + this.pendingSuggestions = pendingSuggestions; + pendingSuggestions.thenAccept(suggestionResult -> { + if (pendingSuggestions.isDone()) { + this.updateUsageInfo(currentParse, suggestionResult); } }); } } else if (!command.isBlank()) { this.currentParseIsMessage = true; String partialCommand = command.substring(0, cursorPosition); - int lastWord = getLastWordIndex(partialCommand); - Collection nonCommandSuggestions = this.minecraft.player.connection.getSuggestionsProvider().getCustomTabSuggestions(); + int lastWord = CommandSuggestions.getLastWordIndex(partialCommand); + Collection nonCommandSuggestions = suggestionProvider.getCustomTabSuggestions(); this.pendingSuggestions = SharedSuggestionProvider.suggest( nonCommandSuggestions, new SuggestionsBuilder(partialCommand, lastWord) ); if (this.currentParseIsMessage && !this.messagesAllowed) { - this.commandUsage.add(MESSAGES_NOT_ALLOWED_TEXT.getVisualOrderText()); + this.commandUsage.add(CommandSuggestions.MESSAGES_NOT_ALLOWED_TEXT.getVisualOrderText()); } this.recomputeUsageBoxWidth(); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SilencerButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SilencerButton.java index 38b4545d88..4d28c26b4a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SilencerButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SilencerButton.java @@ -65,7 +65,7 @@ protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mo if (searchText.startsWith("#") || searchText.startsWith("~")) { message = this.parent.getSoundTextAt(this.index, this.variant); } else { - message = highlighted( + message = SilencerButton.highlighted( this.parent.getSoundTextAt(this.index, this.variant).getString(), searchText, ChatFormatting.WHITE, @@ -76,7 +76,7 @@ protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mo Font font = Minecraft.getInstance().font; graphics.centeredText(font, message, this.getX() + this.width / 2, this.getY() + 3, color); if (this.isHovered()) { - Component soundIdText = highlighted( + Component soundIdText = SilencerButton.highlighted( soundId.toString(), searchText.replaceFirst("#", ""), ChatFormatting.GRAY, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SliderWidget.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SliderWidget.java index cfe1742208..bd876c7ffb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SliderWidget.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SliderWidget.java @@ -131,19 +131,19 @@ private void update() { public void onClick(MouseButtonEvent event, boolean doubleClick) { super.onClick(event, doubleClick); if (this.isInSlider(event.x(), event.y())) { - scrolling = true; + SliderWidget.scrolling = true; return; } - scrolling = false; + SliderWidget.scrolling = false; } @Override public void onDrag(MouseButtonEvent event, double dx, double dy) { super.onDrag(event, dx, dy); - if (scrolling || this.scroll) { - if (scrolling) { + if (SliderWidget.scrolling || this.scroll) { + if (SliderWidget.scrolling) { this.scroll = true; - scrolling = false; + SliderWidget.scrolling = false; } double offset = (event.x() - 8 - this.posX) / this.length; this.setProportion(offset); @@ -154,7 +154,7 @@ public void onDrag(MouseButtonEvent event, double dx, double dy) { public void onReleased() { if (this.scroll) this.update(); this.scroll = false; - scrolling = false; + SliderWidget.scrolling = false; } protected boolean isInSlider(double mouseX, double mouseY) { @@ -168,7 +168,8 @@ protected void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouse this.isHovered = this.isInSlider(mouseX, mouseY); double prop = this.getProportion(); int offsetX = this.posX + (int) ((this.length) * prop); - graphics.blit(RenderPipelines.GUI_TEXTURED, SLIDER, offsetX, this.posY, 0, this.isHovered || this.scroll ? 8 : 0, 16, 8, 16, 16); + graphics.blit( + RenderPipelines.GUI_TEXTURED, SliderWidget.SLIDER, offsetX, this.posY, 0, this.isHovered || this.scroll ? 8 : 0, 16, 8, 16, 16); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SwitchableButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SwitchableButton.java index 23b45a9247..96bfeede91 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SwitchableButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/SwitchableButton.java @@ -52,7 +52,7 @@ public SwitchableButton( OnPress onPress, List message ) { - super(x, y, width, height, Component.empty(), onPress, DEFAULT_NARRATION); + super(x, y, width, height, Component.empty(), onPress, Button.DEFAULT_NARRATION); this.textures = textures; this.message = message; this.texYDiff = texYDiff; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TeslaTowerButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TeslaTowerButton.java index d291b879c8..2a9cb96d5b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TeslaTowerButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TeslaTowerButton.java @@ -67,7 +67,7 @@ protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mo if (searchText.startsWith("#") || searchText.startsWith("~")) { message = this.parent.getFilterTitle(this.index, this.variant); } else { - message = highlighted( + message = TeslaTowerButton.highlighted( this.parent.getFilterTitle(this.index, this.variant).getString(), searchText, ChatFormatting.WHITE @@ -91,7 +91,7 @@ protected void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mo } if (this.isHovered()) { - Component filterText = highlighted( + Component filterText = TeslaTowerButton.highlighted( id, searchText.replaceFirst("#", ""), ChatFormatting.GRAY); List tooltipComponents = filterText.getString().isEmpty() ? List.of(message.getVisualOrderText()) diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TextWidget.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TextWidget.java index 1712dd57cd..9328aed7cf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TextWidget.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TextWidget.java @@ -57,7 +57,7 @@ public void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouseX, int j = font.width(component); int k = this.getX() + Math.round(this.alignX * (float) (i - j)); int l = this.getY() + (this.getHeight() - font.lineHeight) / 2; - graphics.text(font, component.getVisualOrderText(), k, l, DEFAULT_COLOR); + graphics.text(font, component.getVisualOrderText(), k, l, TextWidget.DEFAULT_COLOR); } case SCALED -> { float scaleX = this.getWidth() / (float) font.width(component); @@ -66,7 +66,7 @@ public void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouseX, if (scaleX >= 1 && scaleY >= 1) { int k = this.getX() + Math.round(this.alignX * (float) (this.getWidth() - font.width(component))); int l = this.getY() + (this.getHeight() - font.lineHeight) / 2; - graphics.text(font, component, k, l, DEFAULT_COLOR); + graphics.text(font, component, k, l, TextWidget.DEFAULT_COLOR); return; } @@ -82,7 +82,7 @@ public void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouseX, poseStack.pushMatrix(); poseStack.translate(this.getX() + offsetX, this.getY() + offsetY); poseStack.scale(scaleX, scaleY); - graphics.text(font, component, 0, 0, DEFAULT_COLOR); + graphics.text(font, component, 0, 0, TextWidget.DEFAULT_COLOR); poseStack.popMatrix(); } default -> { @@ -90,7 +90,7 @@ public void extractWidgetRenderState(GuiGraphicsExtractor graphics, int mouseX, int j = font.width(component); int k = this.getX() + Math.round(this.alignX * (float) (i - j)); int l = this.getY() + (this.getHeight() - font.lineHeight) / 2; - graphics.text(font, component.getVisualOrderText(), k, l, DEFAULT_COLOR); + graphics.text(font, component.getVisualOrderText(), k, l, TextWidget.DEFAULT_COLOR); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TexturedButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TexturedButton.java index f38c4bc7f6..064752a0af 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TexturedButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TexturedButton.java @@ -23,7 +23,7 @@ public TexturedButton( int textureHeight, OnPress onPress ) { - super(x, y, width, height, Component.empty(), onPress, DEFAULT_NARRATION); + super(x, y, width, height, Component.empty(), onPress, Button.DEFAULT_NARRATION); this.texYDiff = texYDiff; this.textureWidth = textureWidth; @@ -43,7 +43,7 @@ public TexturedButton( OnPress onPress, Component message ) { - super(x, y, width, height, message, onPress, DEFAULT_NARRATION); + super(x, y, width, height, message, onPress, Button.DEFAULT_NARRATION); this.texYDiff = texYDiff; this.textureWidth = textureWidth; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/ToggleButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/ToggleButton.java index 4a49b650fd..e486e0d2ff 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/ToggleButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/ToggleButton.java @@ -6,7 +6,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.Identifier; -import java.util.Collections; import java.util.List; public class ToggleButton extends Button { @@ -28,7 +27,7 @@ public ToggleButton( OnPress onPress, List tooltips ) { - super(x, y, width, height, Component.empty(), onPress, DEFAULT_NARRATION); + super(x, y, width, height, Component.empty(), onPress, Button.DEFAULT_NARRATION); this.texture = texture; this.textureWidth = textureWidth; this.textureHeight = textureHeight; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TriStateButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TriStateButton.java index 61dcf3604a..2857a408d5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TriStateButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/TriStateButton.java @@ -6,7 +6,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.resources.Identifier; -import java.util.Collections; import java.util.List; public class TriStateButton extends Button { @@ -28,7 +27,7 @@ public TriStateButton( OnPress onPress, List tooltips ) { - super(x, y, width, height, Component.empty(), onPress, DEFAULT_NARRATION); + super(x, y, width, height, Component.empty(), onPress, Button.DEFAULT_NARRATION); this.texture = texture; this.textureWidth = textureWidth; this.textureHeight = textureHeight; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/category/CategoryButton.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/category/CategoryButton.java index a9c450096f..904f0351ab 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/component/category/CategoryButton.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/component/category/CategoryButton.java @@ -41,7 +41,7 @@ public CategoryButton(int x, PlayerSetting setting, int index, CategoryMode mode category.mode = category.entry().changeMode(); onPress.onPress(button); }, - DEFAULT_NARRATION + Button.DEFAULT_NARRATION ); this.setting = setting; this.index = index; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ActiveSilencerScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ActiveSilencerScreen.java index de0f04d7dd..cb2ae8d7d5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ActiveSilencerScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ActiveSilencerScreen.java @@ -148,7 +148,7 @@ void removeMutedSound(Identifier sound) { /// 获取屏幕上某一项的声音字幕 public Component getSoundTextAt(int index, int variant) { int actualIndex = index; - if (variant == SOUND_FILTERED) { + if (variant == ActiveSilencerScreen.SOUND_FILTERED) { actualIndex += this.leftScrollOff; if (this.filteredSounds.isEmpty() || actualIndex >= this.filteredSounds.size()) return Component.empty(); return this.filteredSounds.get(actualIndex).right(); @@ -162,7 +162,7 @@ public Component getSoundTextAt(int index, int variant) { /// 获取屏幕上某一项的声音id public @Nullable Identifier getSoundIdAt(int index, int variant) { int actualIndex = index; - if (variant == SOUND_FILTERED) { + if (variant == ActiveSilencerScreen.SOUND_FILTERED) { actualIndex += this.leftScrollOff; if (this.filteredSounds.isEmpty() || actualIndex >= this.filteredSounds.size()) return null; return this.filteredSounds.get(actualIndex).left(); @@ -184,13 +184,13 @@ protected void init() { super.init(); this.titleLabelX = (this.getImageWidth() - this.font.width(this.title)) / 2; this.titleLabelY = Constant.SCREEN_TITLE_Y; - int buttonTop = topPos + 35; + int buttonTop = this.topPos + 35; for (int l = 0; l < 8; ++l) { this.addRenderableWidget(new SilencerButton( - leftPos + START_LEFT_X, + this.leftPos + ActiveSilencerScreen.START_LEFT_X, buttonTop, l, - SOUND_FILTERED, + ActiveSilencerScreen.SOUND_FILTERED, b -> { if (b instanceof SilencerButton silencerButton) { this.onAllSoundButtonClick(silencerButton.getIndex()); @@ -202,13 +202,13 @@ protected void init() { buttonTop += 15; } - buttonTop = topPos + 35; + buttonTop = this.topPos + 35; for (int l = 0; l < 8; ++l) { this.addRenderableWidget(new SilencerButton( - leftPos + START_RIGHT_X, + this.leftPos + ActiveSilencerScreen.START_RIGHT_X, buttonTop, l, - SOUND_MUTED, + ActiveSilencerScreen.SOUND_MUTED, b -> { if (b instanceof SilencerButton silencerButton) { this.onMutedSoundButtonClick(silencerButton.getIndex()); @@ -222,20 +222,22 @@ protected void init() { this.addRenderableWidget(new EditBox( Objects.requireNonNull(this.minecraft).font, - leftPos + 78, - topPos + 19, + this.leftPos + 78, + this.topPos + 19, 100, 12, Component.translatable("screen.anvilcraft.active_silencer.search") )).setResponder(this::onSearchTextChange); SoundManager manager = Minecraft.getInstance().getSoundManager(); - // noinspection NullableProblems - BuiltInRegistries.SOUND_EVENT.stream() - .map(it -> Pair.of(it.location(), manager.getSoundEvent(it.location()))) - .filter(it -> it.second() != null) - .filter(it -> it.second().getSubtitle() != null) - .forEach(it -> this.allSounds.add(Pair.of(it.first(), it.second().getSubtitle()))); + BuiltInRegistries.SOUND_EVENT.forEach(soundEvent -> { + var sound = manager.getSoundEvent(soundEvent.location()); + if (sound == null) return; + Component subtitle = sound.getSubtitle(); + if (subtitle != null) { + this.allSounds.add(Pair.of(soundEvent.location(), subtitle)); + } + }); this.filteredSounds.addAll(this.allSounds); } @@ -243,10 +245,10 @@ private boolean mouseInLeft(double mouseX, double mouseY, int leftPos, int topPo return MathUtil.isInRange( mouseX, mouseY, - leftPos + START_LEFT_X, - topPos + SCROLL_BAR_TOP_POS_Y, - leftPos + SCROLL_BAR_START_LEFT_X + SCROLL_BAR_WIDTH, - topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT + leftPos + ActiveSilencerScreen.START_LEFT_X, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y, + leftPos + ActiveSilencerScreen.SCROLL_BAR_START_LEFT_X + ActiveSilencerScreen.SCROLL_BAR_WIDTH, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y + ActiveSilencerScreen.SCROLL_BAR_HEIGHT ); } @@ -254,10 +256,10 @@ private boolean mouseInRight(double mouseX, double mouseY, int leftPos, int topP return MathUtil.isInRange( mouseX, mouseY, - leftPos + START_RIGHT_X, - topPos + SCROLL_BAR_TOP_POS_Y, - leftPos + SCROLL_BAR_START_RIGHT_X + SCROLL_BAR_WIDTH, - topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT + leftPos + ActiveSilencerScreen.START_RIGHT_X, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y, + leftPos + ActiveSilencerScreen.SCROLL_BAR_START_RIGHT_X + ActiveSilencerScreen.SCROLL_BAR_WIDTH, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y + ActiveSilencerScreen.SCROLL_BAR_HEIGHT ); } @@ -265,10 +267,10 @@ private boolean mouseInLeftSlider(double mouseX, double mouseY, int leftPos, int return MathUtil.isInRange( mouseX, mouseY, - leftPos + SCROLL_BAR_START_LEFT_X, - topPos + SCROLL_BAR_TOP_POS_Y, - leftPos + SCROLL_BAR_START_LEFT_X + SCROLL_BAR_WIDTH, - topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT + leftPos + ActiveSilencerScreen.SCROLL_BAR_START_LEFT_X, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y, + leftPos + ActiveSilencerScreen.SCROLL_BAR_START_LEFT_X + ActiveSilencerScreen.SCROLL_BAR_WIDTH, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y + ActiveSilencerScreen.SCROLL_BAR_HEIGHT ); } @@ -276,10 +278,10 @@ private boolean mouseInRightSlider(double mouseX, double mouseY, int leftPos, in return MathUtil.isInRange( mouseX, mouseY, - leftPos + SCROLL_BAR_START_RIGHT_X, - topPos + SCROLL_BAR_TOP_POS_Y, - leftPos + SCROLL_BAR_START_RIGHT_X + SCROLL_BAR_WIDTH, - topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT + leftPos + ActiveSilencerScreen.SCROLL_BAR_START_RIGHT_X, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y, + leftPos + ActiveSilencerScreen.SCROLL_BAR_START_RIGHT_X + ActiveSilencerScreen.SCROLL_BAR_WIDTH, + topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y + ActiveSilencerScreen.SCROLL_BAR_HEIGHT ); } @@ -316,8 +318,8 @@ public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, doubl public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) { if (this.isDraggingLeft) { int i = this.filteredSounds.size(); - int j = this.topPos + SCROLL_BAR_TOP_POS_Y; - int k = j + SCROLL_BAR_HEIGHT; + int j = this.topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y; + int k = j + ActiveSilencerScreen.SCROLL_BAR_HEIGHT; int dragMax = i - 7; float scroll = (float) ((event.y() - j - 13.5F) / ((k - j) - 27.0F)); scroll = scroll * dragMax + 0.5F; @@ -325,8 +327,8 @@ public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) return true; } else if (this.isDraggingRight) { int i = this.mutedSounds.size(); - int j = this.topPos + SCROLL_BAR_TOP_POS_Y; - int k = j + SCROLL_BAR_HEIGHT; + int j = this.topPos + ActiveSilencerScreen.SCROLL_BAR_TOP_POS_Y; + int k = j + ActiveSilencerScreen.SCROLL_BAR_HEIGHT; int dragMax = i - 7; float scroll = (float) ((event.y() - j - 13.5F) / ((k - j) - 27.0F)); scroll = scroll * dragMax + 0.5F; @@ -358,13 +360,14 @@ public boolean mouseClicked(MouseButtonEvent event, boolean handled) { private void extractScroller(GuiGraphicsExtractor graphics, int posX, int posY, int totalCount, int scrollOff) { int i = totalCount + 1 - 8; if (i > 1) { - int maxY = posY + SCROLL_BAR_HEIGHT - SCROLLER_HEIGHT; - int scrollY = (int) (posY + (scrollOff / (totalCount - 7F)) * (SCROLL_BAR_HEIGHT - SCROLLER_HEIGHT)); + int maxY = posY + ActiveSilencerScreen.SCROLL_BAR_HEIGHT - ActiveSilencerScreen.SCROLLER_HEIGHT; + int scrollY = (int) (posY + (scrollOff / (totalCount - 7F)) * (ActiveSilencerScreen.SCROLL_BAR_HEIGHT + - ActiveSilencerScreen.SCROLLER_HEIGHT)); scrollY = Mth.clamp(scrollY, posY, maxY); - graphics.blit(RenderPipelines.GUI_TEXTURED, SLIDER, posX, scrollY, 0, 0, 5, 9, 10, 9); + graphics.blit(RenderPipelines.GUI_TEXTURED, ActiveSilencerScreen.SLIDER, posX, scrollY, 0, 0, 5, 9, 10, 9); } else { - graphics.blit(RenderPipelines.GUI_TEXTURED, SLIDER, posX, posY, 0, 0, 5, 9, 10, 9); + graphics.blit(RenderPipelines.GUI_TEXTURED, ActiveSilencerScreen.SLIDER, posX, posY, 0, 0, 5, 9, 10, 9); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdjacentSmithingScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdjacentSmithingScreen.java index c9fc2033d6..6305734745 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdjacentSmithingScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdjacentSmithingScreen.java @@ -93,22 +93,22 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou if (!this.isTemplatePanelVisible()) return; graphics.blit( RenderPipelines.GUI_TEXTURED, - TEMPLATE_PANEL, + AdjacentSmithingScreen.TEMPLATE_PANEL, this.panelX(), this.panelY(), 0, 0, - PANEL_WIDTH, - PANEL_HEIGHT, - PANEL_WIDTH, - PANEL_HEIGHT + AdjacentSmithingScreen.PANEL_WIDTH, + AdjacentSmithingScreen.PANEL_HEIGHT, + AdjacentSmithingScreen.PANEL_WIDTH, + AdjacentSmithingScreen.PANEL_HEIGHT ); int maxScrollRow = this.maxScrollRow(); if (maxScrollRow > 0) { graphics.blit( RenderPipelines.GUI_TEXTURED, SharedTextures.SWITCH_TABLE_SLIDER, - this.panelX() + SLIDER_X, + this.panelX() + AdjacentSmithingScreen.SLIDER_X, this.sliderY(maxScrollRow), 0, 0, @@ -171,7 +171,6 @@ public boolean mouseClicked(MouseButtonEvent event, boolean handled) { } private void playTemplateClickSound() { - if (this.minecraft == null) return; this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F)); } @@ -204,12 +203,14 @@ public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, doubl private void renderTemplateItems(GuiGraphicsExtractor graphics) { List templates = this.filteredTemplates(); - int start = this.scrollRow * COLUMN_COUNT; - int end = Math.min(start + COLUMN_COUNT * VISIBLE_ROW_COUNT, templates.size()); + int start = this.scrollRow * AdjacentSmithingScreen.COLUMN_COUNT; + int end = Math.min(start + AdjacentSmithingScreen.COLUMN_COUNT * AdjacentSmithingScreen.VISIBLE_ROW_COUNT, templates.size()); for (int index = start; index < end; index++) { int visibleIndex = index - start; - int x = this.panelX() + SLOT_X + visibleIndex % COLUMN_COUNT * SLOT_SIZE; - int y = this.panelY() + SLOT_Y + visibleIndex / COLUMN_COUNT * SLOT_SIZE; + int x = this.panelX() + AdjacentSmithingScreen.SLOT_X + + visibleIndex % AdjacentSmithingScreen.COLUMN_COUNT * AdjacentSmithingScreen.SLOT_SIZE; + int y = this.panelY() + AdjacentSmithingScreen.SLOT_Y + + visibleIndex / AdjacentSmithingScreen.COLUMN_COUNT * AdjacentSmithingScreen.SLOT_SIZE; ItemStack template = templates.get(index); if (this.isFavorite(template)) { graphics.fill(RenderPipelines.GUI, x, y, x + 16, y + 16, 0x66FFFF00); @@ -232,14 +233,16 @@ private List filteredTemplates() { } private ItemStack templateAt(double mouseX, double mouseY) { - int relativeX = (int) mouseX - this.panelX() - SLOT_X; - int relativeY = (int) mouseY - this.panelY() - SLOT_Y; + int relativeX = (int) mouseX - this.panelX() - AdjacentSmithingScreen.SLOT_X; + int relativeY = (int) mouseY - this.panelY() - AdjacentSmithingScreen.SLOT_Y; if (relativeX < 0 || relativeY < 0) return ItemStack.EMPTY; - int column = relativeX / SLOT_SIZE; - int row = relativeY / SLOT_SIZE; - if (column >= COLUMN_COUNT || row >= VISIBLE_ROW_COUNT) return ItemStack.EMPTY; - if (relativeX % SLOT_SIZE >= 16 || relativeY % SLOT_SIZE >= 16) return ItemStack.EMPTY; - int index = (this.scrollRow + row) * COLUMN_COUNT + column; + int column = relativeX / AdjacentSmithingScreen.SLOT_SIZE; + int row = relativeY / AdjacentSmithingScreen.SLOT_SIZE; + if (column >= AdjacentSmithingScreen.COLUMN_COUNT || row >= AdjacentSmithingScreen.VISIBLE_ROW_COUNT) return ItemStack.EMPTY; + if (relativeX % AdjacentSmithingScreen.SLOT_SIZE >= 16 || relativeY % AdjacentSmithingScreen.SLOT_SIZE >= 16) { + return ItemStack.EMPTY; + } + int index = (this.scrollRow + row) * AdjacentSmithingScreen.COLUMN_COUNT + column; List templates = this.filteredTemplates(); return index < templates.size() ? templates.get(index) : ItemStack.EMPTY; } @@ -249,14 +252,14 @@ private void clampScrollRow() { } private int maxScrollRow() { - int rowCount = (this.filteredTemplates().size() + COLUMN_COUNT - 1) / COLUMN_COUNT; - return Math.max(0, rowCount - VISIBLE_ROW_COUNT); + int rowCount = (this.filteredTemplates().size() + AdjacentSmithingScreen.COLUMN_COUNT - 1) / AdjacentSmithingScreen.COLUMN_COUNT; + return Math.max(0, rowCount - AdjacentSmithingScreen.VISIBLE_ROW_COUNT); } private int sliderY(int maxScrollRow) { - if (maxScrollRow <= 0) return this.panelY() + SLIDER_MIN_Y; - int travel = SLIDER_MAX_Y - SLIDER_MIN_Y; - return this.panelY() + SLIDER_MIN_Y + Math.round((float) this.scrollRow / maxScrollRow * travel); + if (maxScrollRow <= 0) return this.panelY() + AdjacentSmithingScreen.SLIDER_MIN_Y; + int travel = AdjacentSmithingScreen.SLIDER_MAX_Y - AdjacentSmithingScreen.SLIDER_MIN_Y; + return this.panelY() + AdjacentSmithingScreen.SLIDER_MIN_Y + Math.round((float) this.scrollRow / maxScrollRow * travel); } private void updateScrollFromSlider(double mouseY, int maxScrollRow) { @@ -264,8 +267,8 @@ private void updateScrollFromSlider(double mouseY, int maxScrollRow) { this.scrollRow = 0; return; } - double sliderCenter = mouseY - this.panelY() - SLIDER_MIN_Y - 6; - double progress = Mth.clamp(sliderCenter / (SLIDER_MAX_Y - SLIDER_MIN_Y), 0.0, 1.0); + double sliderCenter = mouseY - this.panelY() - AdjacentSmithingScreen.SLIDER_MIN_Y - 6; + double progress = Mth.clamp(sliderCenter / (AdjacentSmithingScreen.SLIDER_MAX_Y - AdjacentSmithingScreen.SLIDER_MIN_Y), 0.0, 1.0); this.scrollRow = Mth.clamp((int) Math.round(progress * maxScrollRow), 0, maxScrollRow); } @@ -287,23 +290,23 @@ private boolean isOverTemplateGrid(double mouseX, double mouseY) { private boolean isOverTemplatePanel(double mouseX, double mouseY) { return mouseX >= this.panelX() - && mouseX < this.panelX() + PANEL_WIDTH + && mouseX < this.panelX() + AdjacentSmithingScreen.PANEL_WIDTH && mouseY >= this.panelY() - && mouseY < this.panelY() + PANEL_HEIGHT; + && mouseY < this.panelY() + AdjacentSmithingScreen.PANEL_HEIGHT; } private boolean isOverSlider(double mouseX, double mouseY) { - return mouseX >= this.panelX() + SLIDER_X - && mouseX < this.panelX() + SLIDER_X + 8 - && mouseY >= this.panelY() + SLIDER_MIN_Y - && mouseY < this.panelY() + SLIDER_MAX_Y + 12; + return mouseX >= this.panelX() + AdjacentSmithingScreen.SLIDER_X + && mouseX < this.panelX() + AdjacentSmithingScreen.SLIDER_X + 8 + && mouseY >= this.panelY() + AdjacentSmithingScreen.SLIDER_MIN_Y + && mouseY < this.panelY() + AdjacentSmithingScreen.SLIDER_MAX_Y + 12; } private int panelX() { - return this.leftPos - PANEL_RIGHT_BORDER; + return this.leftPos - AdjacentSmithingScreen.PANEL_RIGHT_BORDER; } private int panelY() { - return this.topPos + PANEL_TOP_OFFSET; + return this.topPos + AdjacentSmithingScreen.PANEL_TOP_OFFSET; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdvancedComparatorScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdvancedComparatorScreen.java index 6a75306ce0..ee78b0a9fd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdvancedComparatorScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AdvancedComparatorScreen.java @@ -134,7 +134,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + AdvancedComparatorScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -146,8 +146,10 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou ); int slider1OffsetY = this.isInSlider(mouseX, mouseY, this.slider1X, this.sliderY) ? 11 : 0; int slider2OffsetY = this.isInSlider(mouseX, mouseY, this.slider2X, this.sliderY) ? 11 : 0; - graphics.blit(RenderPipelines.GUI_TEXTURED, SLIDER, this.slider1X, this.sliderY, 0, slider1OffsetY, 7, 11, 7, 22); - graphics.blit(RenderPipelines.GUI_TEXTURED, SLIDER, this.slider2X, this.sliderY, 0, slider2OffsetY, 7, 11, 7, 22); + graphics.blit( + RenderPipelines.GUI_TEXTURED, AdvancedComparatorScreen.SLIDER, this.slider1X, this.sliderY, 0, slider1OffsetY, 7, 11, 7, 22); + graphics.blit( + RenderPipelines.GUI_TEXTURED, AdvancedComparatorScreen.SLIDER, this.slider2X, this.sliderY, 0, slider2OffsetY, 7, 11, 7, 22); Matrix3x2fStack pose = graphics.pose(); pose.pushMatrix(); pose.scale(0.5F, 0.5F); @@ -212,7 +214,7 @@ public boolean mouseReleased(MouseButtonEvent event) { @Override public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) { if (this.scrolling1) { - this.slider1Pos = Math.clamp((int) (event.x() - this.sliderMin) / GRID, 0, 15); + this.slider1Pos = Math.clamp((int) (event.x() - this.sliderMin) / AdvancedComparatorScreen.GRID, 0, 15); this.slider1X = Math.clamp( (long) this.slider1Pos * AdvancedComparatorScreen.GRID + this.sliderMin, this.sliderMin, @@ -220,7 +222,7 @@ public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) ); return true; } else if (this.scrolling2) { - this.slider2Pos = Math.clamp((int) (event.x() - this.sliderMin) / GRID, 0, 15); + this.slider2Pos = Math.clamp((int) (event.x() - this.sliderMin) / AdvancedComparatorScreen.GRID, 0, 15); this.slider2X = Math.clamp( (long) this.slider2Pos * AdvancedComparatorScreen.GRID + this.sliderMin, this.sliderMin, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AnvilHammerSlotOverlay.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AnvilHammerSlotOverlay.java index c000e2b229..6e1ea6f206 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AnvilHammerSlotOverlay.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/AnvilHammerSlotOverlay.java @@ -20,6 +20,6 @@ public static void render(GuiGraphicsExtractor guiGraphics, HammerOpenedAnvilMen if (slot.container != inventory) return; if (slot.getContainerSlot() != menu.anvilcraft$getOpenedHammerSlot()) return; if (!slot.getItem().is(ModItemTags.ANVIL_HAMMER)) return; - guiGraphics.fill(slot.x, slot.y, slot.x + 16, slot.y + 16, COLOR); + guiGraphics.fill(slot.x, slot.y, slot.x + 16, slot.y + 16, AnvilHammerSlotOverlay.COLOR); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BaseChuteScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BaseChuteScreen.java index 32c975090d..5ccb80df16 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BaseChuteScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BaseChuteScreen.java @@ -62,7 +62,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + BaseChuteScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -92,8 +92,8 @@ protected List getTooltipFromContainerItem(ItemStack stack) { if (this.hoveredSlot instanceof SlotItemHandlerWithFilter filterSlot && filterSlot.isFilter() && !filterSlot.getItem().isEmpty()) { - components.add(SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); - components.add(SHIFT_TO_SCROLL_FASTER_TOOLTIP); + components.add(IFilterScreen.SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); + components.add(IFilterScreen.SHIFT_TO_SCROLL_FASTER_TOOLTIP); } return components; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCrafterScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCrafterScreen.java index 1ba0302de7..e9ee40ea9c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCrafterScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCrafterScreen.java @@ -75,7 +75,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + BatchCrafterScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -107,8 +107,8 @@ protected List getTooltipFromContainerItem(ItemStack stack) { && filterSlot.isFilter() && !filterSlot.getItem().isEmpty() ) { - components.add(SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); - components.add(SHIFT_TO_SCROLL_FASTER_TOOLTIP); + components.add(IFilterScreen.SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); + components.add(IFilterScreen.SHIFT_TO_SCROLL_FASTER_TOOLTIP); } return components; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCutterScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCutterScreen.java index 93366a6d00..14842717d5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCutterScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/BatchCutterScreen.java @@ -86,7 +86,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + BatchCutterScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -194,8 +194,8 @@ protected List getTooltipFromContainerItem(ItemStack stack) { && filterSlot.isFilter() && !filterSlot.getItem().isEmpty() ) { - components.add(SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); - components.add(SHIFT_TO_SCROLL_FASTER_TOOLTIP); + components.add(IFilterScreen.SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); + components.add(IFilterScreen.SHIFT_TO_SCROLL_FASTER_TOOLTIP); } return components; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/CategorySettingsScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/CategorySettingsScreen.java index ccdcaf46d1..b0ad35ff0a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/CategorySettingsScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/CategorySettingsScreen.java @@ -385,21 +385,21 @@ private void extractInventorySlot(GuiGraphicsExtractor graphics, Inventory inv, private void extractInventorySlotHighlightBack(GuiGraphicsExtractor graphics, int slot, int x, int y, int mouseX, int mouseY) { if (this.selected == slot) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_SELECTED_BACK_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, CategorySettingsScreen.SLOT_SELECTED_BACK_SPRITE, x - 4, y - 4, 24, 24); } if (MathUtil.isInRange(mouseX, mouseY, x - 2, y - 2, x + 17, y + 17)) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_HIGHLIGHT_BACK_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, CategorySettingsScreen.SLOT_HIGHLIGHT_BACK_SPRITE, x - 4, y - 4, 24, 24); } } private void extractInventorySlotHighlightFront(GuiGraphicsExtractor graphics, int slot, int x, int y, int mouseX, int mouseY) { if (this.selected == slot) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_SELECTED_FRONT_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, CategorySettingsScreen.SLOT_SELECTED_FRONT_SPRITE, x - 4, y - 4, 24, 24); } if (MathUtil.isInRange(mouseX, mouseY, x - 2, y - 2, x + 17, y + 17)) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_HIGHLIGHT_FRONT_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, CategorySettingsScreen.SLOT_HIGHLIGHT_FRONT_SPRITE, x - 4, y - 4, 24, 24); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ControlValveScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ControlValveScreen.java index 92c482b533..468d7bd7b1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ControlValveScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ControlValveScreen.java @@ -77,7 +77,7 @@ protected void init() { offsetY + 53, 16, 16, - BUTTON_MIN, + ControlValveScreen.BUTTON_MIN, 16, 16, 32, @@ -88,7 +88,7 @@ protected void init() { offsetY + 53, 16, 16, - BUTTON_MINUS, + ControlValveScreen.BUTTON_MINUS, 16, 16, 32, @@ -100,7 +100,7 @@ protected void init() { offsetY + 53, 16, 16, - BUTTON_ADD, + ControlValveScreen.BUTTON_ADD, 16, 16, 32, @@ -111,7 +111,7 @@ protected void init() { offsetY + 53, 16, 16, - BUTTON_MAX, + ControlValveScreen.BUTTON_MAX, 16, 16, 32, @@ -202,29 +202,31 @@ private void sendFilter(FluidStack fluid) { @Override public Collection getGhostSlots() { - return List.of(FILTER_GHOST_ID); + return List.of(ControlValveScreen.FILTER_GHOST_ID); } @Override public @Nullable Rect2i getGhostSlotArea(int slotIndex) { - return slotIndex == FILTER_GHOST_ID ? new Rect2i(FILTER_X, FILTER_Y, 16, 16) : null; + return slotIndex == ControlValveScreen.FILTER_GHOST_ID ? new Rect2i( + ControlValveScreen.FILTER_X, ControlValveScreen.FILTER_Y, 16, 16) : null; } @Override public void acceptGhost(Slot slot, ItemStack ingredient) { - this.sendFilter(fluidOf(ingredient)); + this.sendFilter(ControlValveScreen.fluidOf(ingredient)); } @Override public void acceptFluidGhost(int slotIndex, FluidStack fluid) { - if (slotIndex != FILTER_GHOST_ID) return; + if (slotIndex != ControlValveScreen.FILTER_GHOST_ID) return; this.sendFilter(fluid.isEmpty() ? FluidStack.EMPTY : fluid.copyWithAmount(1)); } @Override public boolean mouseClicked(MouseButtonEvent event, boolean handled) { - if (event.button() == 0 && this.isHovering(FILTER_X, FILTER_Y, 16, 16, event.x(), event.y())) { - this.sendFilter(fluidOf(this.getMenu().getCarried())); + if (event.button() == 0 && this.isHovering( + ControlValveScreen.FILTER_X, ControlValveScreen.FILTER_Y, 16, 16, event.x(), event.y())) { + this.sendFilter(ControlValveScreen.fluidOf(this.getMenu().getCarried())); return true; } if (event.button() == 0 && !this.isLocked() && this.slider != null) { @@ -257,7 +259,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + ControlValveScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -276,12 +278,12 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse if (this.valueBox != null) this.valueBox.setEditable(!locked); super.extractContents(graphics, mouseX, mouseY, a); - int fx = this.leftPos + FILTER_X; - int fy = this.topPos + FILTER_Y; + int fx = this.leftPos + ControlValveScreen.FILTER_X; + int fy = this.topPos + ControlValveScreen.FILTER_Y; if (!this.filter.isEmpty()) { this.extractFluidSwatch(graphics, this.filter, fx, fy); } - if (this.isHovering(FILTER_X, FILTER_Y, 16, 16, mouseX, mouseY)) { + if (this.isHovering(ControlValveScreen.FILTER_X, ControlValveScreen.FILTER_Y, 16, 16, mouseX, mouseY)) { graphics.fill(fx, fy, fx + 16, fy + 16, 0x80FFFFFF); } if (locked) { @@ -303,7 +305,7 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse protected void extractTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { super.extractTooltip(graphics, mouseX, mouseY); if (!this.filter.isEmpty() && this.getMenu().getCarried().isEmpty() - && this.isHovering(FILTER_X, FILTER_Y, 16, 16, mouseX, mouseY)) { + && this.isHovering(ControlValveScreen.FILTER_X, ControlValveScreen.FILTER_Y, 16, 16, mouseX, mouseY)) { graphics.setTooltipForNextFrame(this.font, this.filter.getHoverName(), mouseX, mouseY); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberAnvilScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberAnvilScreen.java index 1ba1ac6d2e..ed21f8bdf0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberAnvilScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberAnvilScreen.java @@ -30,7 +30,7 @@ public class EmberAnvilScreen extends ItemCombinerScreen { /// @param playerInventory 背包 /// @param title 标题 public EmberAnvilScreen(EmberAnvilMenu menu, Inventory playerInventory, Component title) { - super(menu, playerInventory, title, BACKGROUND); + super(menu, playerInventory, title, EmberAnvilScreen.BACKGROUND); this.player = playerInventory.player; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberGrindstoneScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberGrindstoneScreen.java index 83b093fa8c..d6bcd17cb5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberGrindstoneScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberGrindstoneScreen.java @@ -163,7 +163,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + EmberGrindstoneScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberSmithingScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberSmithingScreen.java index 43b2b073f9..eaaa47f7df 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberSmithingScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EmberSmithingScreen.java @@ -39,9 +39,9 @@ public class EmberSmithingScreen extends AdjacentSmithingScreen EMPTY_SLOT_SMITHING_TEMPLATES = List.of( - EMPTY_SLOT_TWO_TO_ONE_SMITHING_TEMPLATE, - EMPTY_SLOT_FOUR_TO_ONE_SMITHING_TEMPLATE, - EMPTY_SLOT_EIGHT_TO_ONE_SMITHING_TEMPLATE + EmberSmithingScreen.EMPTY_SLOT_TWO_TO_ONE_SMITHING_TEMPLATE, + EmberSmithingScreen.EMPTY_SLOT_FOUR_TO_ONE_SMITHING_TEMPLATE, + EmberSmithingScreen.EMPTY_SLOT_EIGHT_TO_ONE_SMITHING_TEMPLATE ); private final CyclingSlotBackground templateIcon = new CyclingSlotBackground(0); @@ -63,7 +63,7 @@ public class EmberSmithingScreen extends AdjacentSmithingScreen icon.tick(List.of())); } } else { - this.templateIcon.tick(EMPTY_SLOT_SMITHING_TEMPLATES); + this.templateIcon.tick(EmberSmithingScreen.EMPTY_SLOT_SMITHING_TEMPLATES); this.materialIcon.tick(List.of()); this.inputIcons.forEach(icon -> icon.tick(List.of())); } @@ -159,7 +159,7 @@ protected void extractErrorIcon(GuiGraphicsExtractor graphics, int xo, int yo) { private void extractOnboardingTooltips(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { Optional optional = Optional.empty(); if (!this.menu.canCreateResult() && this.isHovering(123, 48, 16, 16, mouseX, mouseY)) { - optional = Optional.of(ERROR_TOOLTIP); + optional = Optional.of(EmberSmithingScreen.ERROR_TOOLTIP); } if (this.hoveredSlot != null) { ItemStack template = this.menu.getSlot(0).getItem(); @@ -167,7 +167,7 @@ private void extractOnboardingTooltips(GuiGraphicsExtractor graphics, int mouseX ItemStack hovered = this.hoveredSlot.getItem(); if (template.isEmpty()) { if (this.hoveredSlot.index == 0) { - optional = Optional.of(MISSING_TEMPLATE_TOOLTIP); + optional = Optional.of(EmberSmithingScreen.MISSING_TEMPLATE_TOOLTIP); } } else { if (template.getItem() instanceof BaseMultipleToOneTemplateItem templateItem && hovered.isEmpty()) { diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EnergyWeaponMakeScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EnergyWeaponMakeScreen.java index 54a448e27b..c979ea9cc0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EnergyWeaponMakeScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/EnergyWeaponMakeScreen.java @@ -220,7 +220,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + EnergyWeaponMakeScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ExpCollectorScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ExpCollectorScreen.java index 67a469ee7d..9f99224e2f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ExpCollectorScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ExpCollectorScreen.java @@ -110,7 +110,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, partialTick); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + ExpCollectorScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -130,7 +130,7 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse int amount = handler.getAmountAsInt(0); if (resource.isEmpty() || amount <= 0) return; int capacity = handler.getCapacityAsInt(0, resource); - int fluidHeight = Math.max(1, amount * FLUID_HEIGHT / capacity); + int fluidHeight = Math.max(1, amount * ExpCollectorScreen.FLUID_HEIGHT / capacity); FluidModel model = FluidRenderHelper.getModel( Minecraft.getInstance().getModelManager().getFluidStateModelSet(), resource.getFluid() @@ -141,9 +141,9 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse graphics.blitSprite( RenderPipelines.GUI_TEXTURED, sprite, - this.leftPos + FLUID_X, - this.topPos + FLUID_Y + FLUID_HEIGHT - fluidHeight, - FLUID_WIDTH, + this.leftPos + ExpCollectorScreen.FLUID_X, + this.topPos + ExpCollectorScreen.FLUID_Y + ExpCollectorScreen.FLUID_HEIGHT - fluidHeight, + ExpCollectorScreen.FLUID_WIDTH, fluidHeight, tint ); @@ -152,7 +152,12 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse @Override protected void extractTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { super.extractTooltip(graphics, mouseX, mouseY); - if (!this.isHovering(FLUID_X, FLUID_Y, FLUID_WIDTH, FLUID_HEIGHT, mouseX, mouseY)) return; + if (!this.isHovering( + ExpCollectorScreen.FLUID_X, ExpCollectorScreen.FLUID_Y, ExpCollectorScreen.FLUID_WIDTH, ExpCollectorScreen.FLUID_HEIGHT, mouseX, + mouseY + )) { + return; + } ResourceHandler handler = this.menu.getBlockEntity().getFluidHandler(); graphics.setTooltipForNextFrame( this.font, @@ -169,7 +174,10 @@ protected void extractTooltip(GuiGraphicsExtractor graphics, int mouseX, int mou @Override public boolean mouseClicked(MouseButtonEvent event, boolean handled) { if (event.button() == 1 - && this.isHovering(FLUID_X, FLUID_Y, FLUID_WIDTH, FLUID_HEIGHT, event.x(), event.y())) { + && this.isHovering( + ExpCollectorScreen.FLUID_X, ExpCollectorScreen.FLUID_Y, ExpCollectorScreen.FLUID_WIDTH, ExpCollectorScreen.FLUID_HEIGHT, + event.x(), event.y() + )) { ClientPacketDistributor.sendToServer( new ExpCollectorSyncPacket(this.menu.getBlockEntity().getBlockPos()) ); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FilterScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FilterScreen.java index 0b9532f29d..e416e78d72 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FilterScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FilterScreen.java @@ -53,7 +53,7 @@ protected void init() { this.topPos + 26, 16, 16, - List.of(INCLUDE_COMPONENTS_ENABLE, INCLUDE_COMPONENTS_DISABLE), + List.of(FilterScreen.INCLUDE_COMPONENTS_ENABLE, FilterScreen.INCLUDE_COMPONENTS_DISABLE), 16, 16, 32, @@ -71,7 +71,7 @@ protected void init() { this.topPos + 44, 16, 16, - List.of(BLACK_LIST_ENABLE, BLACK_LIST_DISABLE), + List.of(FilterScreen.BLACK_LIST_ENABLE, FilterScreen.BLACK_LIST_DISABLE), 16, 16, 32, @@ -91,7 +91,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + FilterScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostAnvilScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostAnvilScreen.java index 3f44d67692..d88be30e4d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostAnvilScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostAnvilScreen.java @@ -30,7 +30,7 @@ public class FrostAnvilScreen extends ItemCombinerScreen { /// @param playerInventory 背包 /// @param title 标题 public FrostAnvilScreen(FrostAnvilMenu menu, Inventory playerInventory, Component title) { - super(menu, playerInventory, title, BACKGROUND); + super(menu, playerInventory, title, FrostAnvilScreen.BACKGROUND); this.player = playerInventory.player; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostGrindstoneScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostGrindstoneScreen.java index de95333b42..cd08cbdacc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostGrindstoneScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostGrindstoneScreen.java @@ -136,7 +136,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + FrostGrindstoneScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostSmithingScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostSmithingScreen.java index 0032a7342b..b590ad1918 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostSmithingScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/FrostSmithingScreen.java @@ -3,6 +3,7 @@ import dev.anvilcraft.lib.v2.util.Util; import dev.dubhe.anvilcraft.AnvilCraft; import dev.dubhe.anvilcraft.api.item.IPermutationMaterial; +import dev.dubhe.anvilcraft.api.recipe.result.RecipeResult; import dev.dubhe.anvilcraft.client.gui.component.TexturedButton; import dev.dubhe.anvilcraft.constant.Constant; import dev.dubhe.anvilcraft.constant.SharedTextures; @@ -56,11 +57,11 @@ public class FrostSmithingScreen extends AdjacentSmithingScreen EMPTY_SLOT_SMITHING_TEMPLATES = List.of( - EMPTY_SLOT_PERMUTATION_SMITHING_TEMPLATE, - EMPTY_SLOT_DEFORMATION_SMITHING_TEMPLATE + FrostSmithingScreen.EMPTY_SLOT_PERMUTATION_SMITHING_TEMPLATE, + FrostSmithingScreen.EMPTY_SLOT_DEFORMATION_SMITHING_TEMPLATE ); private static final List EMPTY_SLOT_DEFORM_MATERIAL = List.of( - EMPTY_SLOT_INGOT + FrostSmithingScreen.EMPTY_SLOT_INGOT ); private static final Vector3f ARMOR_STAND_TRANSLATION = new Vector3f(0.0F, 1.0F, 0.0F); public static final Quaternionf ARMOR_STAND_ANGLE = new Quaternionf().rotationXYZ(0.43633232F, 0.0F, (float) Math.PI); @@ -80,7 +81,7 @@ public class FrostSmithingScreen extends AdjacentSmithingScreen results = this.menu.results; + this.modifyButtons(this.menu.selected != -1 && results != null && results.size() != 1); } else { this.modifyButtons(false); } @@ -201,8 +203,8 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou graphics.entity( this.armorStandPreview, 25, - ARMOR_STAND_TRANSLATION, - ARMOR_STAND_ANGLE, + FrostSmithingScreen.ARMOR_STAND_TRANSLATION, + FrostSmithingScreen.ARMOR_STAND_ANGLE, null, x0, y0, @@ -212,10 +214,13 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou } private void modifyButtons(boolean enabled) { - this.left.active = enabled; - this.left.visible = enabled; - this.right.active = enabled; - this.right.visible = enabled; + TexturedButton left = this.left; + TexturedButton right = this.right; + if (left == null || right == null) return; + left.active = enabled; + left.visible = enabled; + right.active = enabled; + right.visible = enabled; } @Override @@ -273,7 +278,7 @@ private void extractOnboardingTooltips(GuiGraphicsExtractor graphics, int mouseX && !this.menu.getSlot(this.menu.getResultSlot()).hasItem() && this.isHovering(83, 48, 16, 16, mouseX, mouseY) ) { - graphics.setTooltipForNextFrame(this.font, this.font.split(ERROR_TOOLTIP, 115), mouseX, mouseY); + graphics.setTooltipForNextFrame(this.font, this.font.split(FrostSmithingScreen.ERROR_TOOLTIP, 115), mouseX, mouseY); return; } @@ -282,7 +287,8 @@ private void extractOnboardingTooltips(GuiGraphicsExtractor graphics, int mouseX ItemStack template = this.menu.getSlot(0).getItem(); if (template.isEmpty()) { if (this.hoveredSlot.index == 0) { - graphics.setTooltipForNextFrame(this.font, this.font.split(MISSING_TEMPLATE_TOOLTIP, 115), mouseX, mouseY); + graphics.setTooltipForNextFrame( + this.font, this.font.split(FrostSmithingScreen.MISSING_TEMPLATE_TOOLTIP, 115), mouseX, mouseY); } return; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/IntegrationScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/IntegrationScreen.java index 34cceeec17..e7567a6883 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/IntegrationScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/IntegrationScreen.java @@ -72,7 +72,7 @@ public IntegrationScreen(@Nullable Screen screen) { @Override protected void init() { this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.BOOK_PAGE_TURN, 1.0F)); - this.layout.addTitleHeader(TITLE, this.font); + this.layout.addTitleHeader(IntegrationScreen.TITLE, this.font); this.integrationList = this.layout.addToContents(new IntegrationList()); LinearLayout linearlayout = this.layout.addToFooter(LinearLayout.horizontal().spacing(8)); linearlayout.addChild(Button.builder(CommonComponents.GUI_DONE, _ -> this.onClose()).build()); @@ -267,8 +267,8 @@ public void extractContent(GuiGraphicsExtractor graphics, int mouseX, int mouseY Matrix3x2fStack pose = graphics.pose(); pose.pushMatrix(); pose.translate(this.getContentX(), this.getContentY()); - pose.scale(SCALE, SCALE); - int maxWidth = (int) (width / SCALE); + pose.scale(NoteIntegrationEntry.SCALE, NoteIntegrationEntry.SCALE); + int maxWidth = (int) (IntegrationScreen.this.width / NoteIntegrationEntry.SCALE); graphics.textWithWordWrap(Minecraft.getInstance().font, this.note, 0, 0, maxWidth, -1); pose.popMatrix(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemCollectorScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemCollectorScreen.java index 978633126b..a1797de011 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemCollectorScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemCollectorScreen.java @@ -126,7 +126,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + ItemCollectorScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -156,8 +156,8 @@ protected List getTooltipFromContainerItem(ItemStack stack) { if (this.hoveredSlot instanceof SlotItemHandlerWithFilter filterSlot && filterSlot.isFilter() && !filterSlot.getItem().isEmpty()) { - components.add(SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); - components.add(SHIFT_TO_SCROLL_FASTER_TOOLTIP); + components.add(IFilterScreen.SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); + components.add(IFilterScreen.SHIFT_TO_SCROLL_FASTER_TOOLTIP); } return components; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemDetectorScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemDetectorScreen.java index 8bf47bc550..8655e8c508 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemDetectorScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/ItemDetectorScreen.java @@ -56,7 +56,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + ItemDetectorScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -75,8 +75,8 @@ protected void init() { this.titleLabelY = Constant.SCREEN_TITLE_Y; // filter mode this.cycleFilterModeButton = new CycleFilterModeButton( - leftPos + 75, - topPos + 54, + this.leftPos + 75, + this.topPos + 54, b -> { if (!(b instanceof CycleFilterModeButton button)) return; ClientPacketDistributor.sendToServer(new MachineCycleFilterModePacket(button.cycle())); @@ -87,8 +87,8 @@ protected void init() { this.addRenderableWidget(this.cycleFilterModeButton); // range this.addRenderableWidget(new TextWidget( - leftPos + 57, - topPos + 24, + this.leftPos + 57, + this.topPos + 24, 20, 8, Minecraft.getInstance().font, @@ -96,8 +96,8 @@ protected void init() { )); // range - + this.addRenderableWidget(new ItemCollectorButton( - leftPos + 43, - topPos + 23, + this.leftPos + 43, + this.topPos + 23, "minus", _ -> { this.menu.getBlockEntity().decreaseRange(); @@ -107,8 +107,8 @@ protected void init() { } )); this.addRenderableWidget(new ItemCollectorButton( - leftPos + 81, - topPos + 23, + this.leftPos + 81, + this.topPos + 23, "add", _ -> { this.menu.getBlockEntity().increaseRange(); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/JewelCraftingScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/JewelCraftingScreen.java index 2a774d2a51..72c240fe51 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/JewelCraftingScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/JewelCraftingScreen.java @@ -44,7 +44,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + JewelCraftingScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/PulseGeneratorScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/PulseGeneratorScreen.java index 9457120652..4ed99bc6d4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/PulseGeneratorScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/PulseGeneratorScreen.java @@ -122,7 +122,7 @@ protected void init() { this.leftPos + offsetX, this.topPos + 25, 10, 10, - BUTTON_ADD_T, + PulseGeneratorScreen.BUTTON_ADD_T, 10, 10, 20, _ -> tickAdder.accept(!this.minecraft.hasShiftDown() ? 1 : 5) ); @@ -130,7 +130,7 @@ protected void init() { this.leftPos + offsetX, this.topPos + 25, 10, 10, - BUTTON_ADD_S, + PulseGeneratorScreen.BUTTON_ADD_S, 10, 10, 20, _ -> tickAdder.accept(!this.minecraft.hasShiftDown() ? 20 : 100) ); @@ -138,7 +138,7 @@ protected void init() { this.leftPos + offsetX, this.topPos + 25, 10, 10, - BUTTON_ADD_M, + PulseGeneratorScreen.BUTTON_ADD_M, 10, 10, 20, _ -> tickAdder.accept(!this.minecraft.hasShiftDown() ? 1200 : 6000) ); @@ -146,7 +146,7 @@ protected void init() { this.leftPos + offsetX, this.topPos + 49, 10, 10, - BUTTON_MINUS_T, + PulseGeneratorScreen.BUTTON_MINUS_T, 10, 10, 20, _ -> tickAdder.accept(!this.minecraft.hasShiftDown() ? -1 : -5) ); @@ -154,7 +154,7 @@ protected void init() { this.leftPos + offsetX, this.topPos + 49, 10, 10, - BUTTON_MINUS_S, + PulseGeneratorScreen.BUTTON_MINUS_S, 10, 10, 20, _ -> tickAdder.accept(!this.minecraft.hasShiftDown() ? -20 : -100) ); @@ -162,7 +162,7 @@ protected void init() { this.leftPos + offsetX, this.topPos + 49, 10, 10, - BUTTON_MINUS_M, + PulseGeneratorScreen.BUTTON_MINUS_M, 10, 10, 20, _ -> tickAdder.accept(!this.minecraft.hasShiftDown() ? -1200 : -6000) ); @@ -210,7 +210,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + PulseGeneratorScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalAnvilScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalAnvilScreen.java index 5ea2da8566..aa913c4e99 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalAnvilScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalAnvilScreen.java @@ -30,7 +30,7 @@ public class RoyalAnvilScreen extends ItemCombinerScreen { /// @param playerInventory 背包 /// @param title 标题 public RoyalAnvilScreen(RoyalAnvilMenu menu, Inventory playerInventory, Component title) { - super(menu, playerInventory, title, BACKGROUND); + super(menu, playerInventory, title, RoyalAnvilScreen.BACKGROUND); this.player = playerInventory.player; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalGrindstoneScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalGrindstoneScreen.java index 41db788669..e65c44b279 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalGrindstoneScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalGrindstoneScreen.java @@ -84,7 +84,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + RoyalGrindstoneScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalSmithingScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalSmithingScreen.java index 56329ac472..01996f9fb1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalSmithingScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/RoyalSmithingScreen.java @@ -37,7 +37,10 @@ public class RoyalSmithingScreen extends AdjacentSmithingScreen EMPTY_SLOT_SMITHING_TEMPLATES = - List.of(EMPTY_SLOT_SMITHING_TEMPLATE_ARMOR_TRIM, EMPTY_SLOT_SMITHING_TEMPLATE_NETHERITE_UPGRADE); + List.of( + RoyalSmithingScreen.EMPTY_SLOT_SMITHING_TEMPLATE_ARMOR_TRIM, + RoyalSmithingScreen.EMPTY_SLOT_SMITHING_TEMPLATE_NETHERITE_UPGRADE + ); private static final Vector3f ARMOR_STAND_TRANSLATION = new Vector3f(0.0F, 1.0F, 0.0F); public static final Quaternionf ARMOR_STAND_ANGLE = new Quaternionf().rotationXYZ(0.43633232F, 0.0F, (float) Math.PI); @@ -53,7 +56,7 @@ public class RoyalSmithingScreen extends AdjacentSmithingScreen optional = this.getTemplateItem(); - this.templateIcon.tick(EMPTY_SLOT_SMITHING_TEMPLATES); + this.templateIcon.tick(RoyalSmithingScreen.EMPTY_SLOT_SMITHING_TEMPLATES); this.baseIcon.tick( optional.map(SmithingTemplateItem::getBaseSlotEmptyIcons).orElse(List.of())); this.additionalIcon.tick( @@ -119,8 +122,8 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou graphics.entity( this.armorStandPreview, 25, - ARMOR_STAND_TRANSLATION, - ARMOR_STAND_ANGLE, + RoyalSmithingScreen.ARMOR_STAND_TRANSLATION, + RoyalSmithingScreen.ARMOR_STAND_ANGLE, null, x0, y0, @@ -178,14 +181,14 @@ protected void extractErrorIcon(GuiGraphicsExtractor graphics, int x, int y) { private void extractOnboardingTooltips(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { Optional optional = Optional.empty(); if (this.hasRecipeError() && this.isHovering(83, 48, 16, 16, mouseX, mouseY)) { - optional = Optional.of(ERROR_TOOLTIP); + optional = Optional.of(RoyalSmithingScreen.ERROR_TOOLTIP); } if (this.hoveredSlot != null) { ItemStack itemStack = this.menu.getSlot(0).getItem(); ItemStack itemStack2 = this.hoveredSlot.getItem(); if (itemStack.isEmpty()) { if (this.hoveredSlot.index == 0) { - optional = Optional.of(MISSING_TEMPLATE_TOOLTIP); + optional = Optional.of(RoyalSmithingScreen.MISSING_TEMPLATE_TOOLTIP); } } else { Item item = itemStack.getItem(); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SliderScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SliderScreen.java index 4a831de3e1..302061fcb9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SliderScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SliderScreen.java @@ -51,7 +51,7 @@ protected void init() { 43 + offsetY, 16, 16, - BUTTON_MAX, + SliderScreen.BUTTON_MAX, 16, 16, 32, @@ -61,7 +61,7 @@ protected void init() { 43 + offsetY, 16, 16, - BUTTON_ADD, + SliderScreen.BUTTON_ADD, 16, 16, 32, @@ -75,7 +75,7 @@ protected void init() { 43 + offsetY, 16, 16, - BUTTON_MIN, + SliderScreen.BUTTON_MIN, 16, 16, 32, @@ -85,7 +85,7 @@ protected void init() { 43 + offsetY, 16, 16, - BUTTON_MINUS, + SliderScreen.BUTTON_MINUS, 16, 16, 32, @@ -177,7 +177,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + SliderScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SmartBlockPlacerScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SmartBlockPlacerScreen.java index b38f409ef5..b774da8d6d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SmartBlockPlacerScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SmartBlockPlacerScreen.java @@ -165,7 +165,7 @@ private void initLayerButtons() { buttonStartY + (4 - i) * 18, 16, 16, - LAYER_DEFAULT[i], + SmartBlockPlacerScreen.LAYER_DEFAULT[i], 16, 48, _ -> this.onLayerButtonClick(index), @@ -222,7 +222,7 @@ private void initLayerModeButton() { buttonY, 16, 16, - this.showAllLayers ? LAYER_ALL : LAYER_SINGLE, + this.showAllLayers ? SmartBlockPlacerScreen.LAYER_ALL : SmartBlockPlacerScreen.LAYER_SINGLE, 16, 32, _ -> this.onLayerModeButtonClick(), @@ -241,7 +241,7 @@ private void initOperationModeButton() { buttonY, 16, 16, - this.isPickupMode ? PICKUP_MODE : MOVE_MODE, + this.isPickupMode ? SmartBlockPlacerScreen.PICKUP_MODE : SmartBlockPlacerScreen.MOVE_MODE, 16, 32, _ -> this.onOperationModeButtonClick(), @@ -266,7 +266,7 @@ private void initMissingModeButton() { buttonY, 16, 16, - SKIP_MISSING, + SmartBlockPlacerScreen.SKIP_MISSING, 16, 48, _ -> this.onSkipMissingButtonClick(), @@ -280,7 +280,7 @@ private void initMissingModeButton() { buttonY, 16, 16, - STOP_MISSING, + SmartBlockPlacerScreen.STOP_MISSING, 16, 48, _ -> this.onStopMissingButtonClick(), @@ -397,7 +397,7 @@ private TriStateButton createPositionButton( TriStateButton button = new TriStateButton( xpos, ypos, 16, 16, - POSITION_SELECT, 16, 48, + SmartBlockPlacerScreen.POSITION_SELECT, 16, 48, (_) -> this.onPositionButtonClick(row, col, positionIndex, tooltipSelected, tooltipUnselected), selected ? tooltipSelected : tooltipUnselected ); @@ -425,7 +425,7 @@ private void onLayerModeButtonClick() { this.showAllLayers = !this.showAllLayers; if (this.layerModeButton != null) { this.layerModeButton.setSelected(this.showAllLayers); - this.layerModeButton.setTexture(this.showAllLayers ? LAYER_ALL : LAYER_SINGLE); + this.layerModeButton.setTexture(this.showAllLayers ? SmartBlockPlacerScreen.LAYER_ALL : SmartBlockPlacerScreen.LAYER_SINGLE); this.layerModeButton.setTooltips(List.of(this.getLayerModeTooltip())); } } @@ -434,7 +434,7 @@ private void onOperationModeButtonClick() { this.isPickupMode = !this.isPickupMode; if (this.operationModeButton != null) { this.operationModeButton.setSelected(this.isPickupMode); - this.operationModeButton.setTexture(this.isPickupMode ? PICKUP_MODE : MOVE_MODE); + this.operationModeButton.setTexture(this.isPickupMode ? SmartBlockPlacerScreen.PICKUP_MODE : SmartBlockPlacerScreen.MOVE_MODE); this.operationModeButton.setTooltips(List.of(this.getOperationModeTooltip())); } ClientPacketDistributor.sendToServer(new SmartBlockPlacerActionPacket("mode", this.isPickupMode ? 1 : 0)); @@ -592,7 +592,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou int j = this.topPos; graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + SmartBlockPlacerScreen.BACKGROUND, i, j, 0, @@ -608,7 +608,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou int blueprintY = j + (this.imageHeight - 128) / 2 - 19; graphics.blit( RenderPipelines.GUI_TEXTURED, - BLUEPRINT_MODE_BG, + SmartBlockPlacerScreen.BLUEPRINT_MODE_BG, blueprintX, blueprintY, 0, @@ -1004,13 +1004,17 @@ private LevelLike buildPreviewLevelLike() { int renderX = sizeX - 1 - bp.x(); int renderZ = sizeZ - bp.z(); int renderY = upsideDown ? (2 - bp.y()) : (bp.y() - 2); + BlockPos renderPos = new BlockPos(renderX, renderY, renderZ); BlockState state = bp.state(); if (upsideDown) { - // noinspection deprecation - state = state.rotate(Rotation.CLOCKWISE_180); + state = state.rotate( + level, + placerPos.offset(renderX, renderY, renderZ), + Rotation.CLOCKWISE_180 + ); state = SmartBlockPlacerBlockEntity.flipHalfPropertyStatic(state); } - previewLevelLike.setBlockState(new BlockPos(renderX, renderY, renderZ), state); + previewLevelLike.setBlockState(renderPos, state); } } else { // 普通模式:显示 UI 中的选区模式(不读取世界方块) diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SpacetimeSupercomputerScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SpacetimeSupercomputerScreen.java index a36ee9dba7..673c666632 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SpacetimeSupercomputerScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/SpacetimeSupercomputerScreen.java @@ -48,7 +48,9 @@ public class SpacetimeSupercomputerScreen extends Screen { SharedTextures.textureGui("machine/spacetime_supercomputer/charging_progress"); private final SpacetimeSupercomputerBlockEntity spacetimeSupercomputerBlockEntity; + @SuppressWarnings("NotNullFieldNotInitialized") private EditBox commandEditBox; + @SuppressWarnings("NotNullFieldNotInitialized") private SapcetimeSupercomputerCommandSuggestions commandSuggestions; private int currentAvailableCommandButtonIndex = 0; @@ -236,7 +238,7 @@ protected void init() { new TexturedButton( x + 132, y + 144, 16, 16, - BUTTON_CONFIRM_RUN, + SpacetimeSupercomputerScreen.BUTTON_CONFIRM_RUN, 16, 16, 32, (btn) -> this.onDone(true) ) @@ -245,7 +247,7 @@ protected void init() { new TexturedButton( x + 150, y + 144, 16, 16, - BUTTON_CONFIRM_RETAIN, + SpacetimeSupercomputerScreen.BUTTON_CONFIRM_RETAIN, 16, 16, 32, (btn) -> this.onDone(false) ) @@ -254,7 +256,7 @@ protected void init() { new TexturedButton( x + 168, y + 144, 16, 16, - BUTTON_CANCEL, + SpacetimeSupercomputerScreen.BUTTON_CANCEL, 16, 16, 32, (btn) -> this.onClose() ) @@ -461,7 +463,8 @@ private void renderScroller(GuiGraphicsExtractor guiGraphics, int posX, int posY int scrollY = posY + scrollOff * trackHeight / maxIndex; scrollY = Mth.clamp(scrollY, posY, maxY); - guiGraphics.blitSprite(RenderPipelines.GUI_TEXTURED, SCROLLER_SPRITE, 6, 32, 0, 0, posX, scrollY, 6, 32); + guiGraphics.blitSprite( + RenderPipelines.GUI_TEXTURED, SpacetimeSupercomputerScreen.SCROLLER_SPRITE, 6, 32, 0, 0, posX, scrollY, 6, 32); } } @@ -476,39 +479,42 @@ public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mo // 渲染命令列表标题 graphics.drawScrollingString( - graphics.textRenderer(), - this.font, - Component.literal("Available Commands"), - x + 6, x + 68, - y + 15 + graphics.textRenderer(), + this.font, + Component.literal("Available Commands"), + x + 6, x + 68, + y + 15 ); graphics.drawScrollingString( - graphics.textRenderer(), - this.font, - Component.literal("History Commands"), - x + 188, x + 250, - y + 15 + graphics.textRenderer(), + this.font, + Component.literal("History Commands"), + x + 188, x + 250, + y + 15 ); // 渲染充能进度条 - graphics.blit(RenderPipelines.GUI_TEXTURED, BUTTON_CHARGING_PROGRESS, x + 72, y + 154, 0, 0, this.getChangingProgress(), 6, 56, 6); + graphics.blit( + RenderPipelines.GUI_TEXTURED, SpacetimeSupercomputerScreen.BUTTON_CHARGING_PROGRESS, x + 72, y + 154, 0, 0, + this.getChangingProgress(), 6, 56, 6 + ); // 渲染命令建议 this.commandSuggestions.extractRenderState(graphics, mouseX, mouseY); // 渲染滚动条 this.renderScroller( - graphics, - x + 62, y + 25, - this.spacetimeSupercomputerBlockEntity.getAvailableCommands().size(), - this.availableCommandScrollOffset + graphics, + x + 62, y + 25, + this.spacetimeSupercomputerBlockEntity.getAvailableCommands().size(), + this.availableCommandScrollOffset ); this.renderScroller( - graphics, - x + 244, y + 25, - this.spacetimeSupercomputerBlockEntity.getHistoryCommands().size(), - this.historyCommandScrollOffset + graphics, + x + 244, y + 25, + this.spacetimeSupercomputerBlockEntity.getHistoryCommands().size(), + this.historyCommandScrollOffset ); // 渲染列表上下边界 @@ -536,7 +542,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou int x = (this.width - 256) / 2; int y = (this.height - 166) / 2; this.extractTransparentBackground(graphics); - graphics.blit(RenderPipelines.GUI_TEXTURED, BACKGROUND, x, y, 0, 0, 256, 166, 256, 256); + graphics.blit(RenderPipelines.GUI_TEXTURED, SpacetimeSupercomputerScreen.BACKGROUND, x, y, 0, 0, 256, 166, 256, 256); } public void updateGui() { diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StorageScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StorageScreen.java index f4b5b310f7..724862386f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StorageScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StorageScreen.java @@ -88,7 +88,7 @@ public class StorageScreen extends Screen { private static final int BG_HEIGHT = 222; private static final int STORAGE_COLUMNS = 9; private static final int STORAGE_ROWS = 6; - private static final int VISIBLE_STORAGE_SLOTS = STORAGE_COLUMNS * STORAGE_ROWS; + private static final int VISIBLE_STORAGE_SLOTS = StorageScreen.STORAGE_COLUMNS * StorageScreen.STORAGE_ROWS; private static final int STORAGE_X = 114; private static final int STORAGE_Y = 18; private static final int SLOT_SIZE = 18; @@ -392,7 +392,7 @@ private void extractStorageContents(GuiGraphicsExtractor graphics, int mouseX, i + displayIndex / StorageScreen.STORAGE_COLUMNS * StorageScreen.SLOT_SIZE; boolean hovered = MathUtil.isInRange(mouseX, mouseY, x - 2, y - 2, x + 17, y + 17); if (hovered) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_HIGHLIGHT_BACK_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, StorageScreen.SLOT_HIGHLIGHT_BACK_SPRITE, x - 4, y - 4, 24, 24); } int slot = this.displayOrder.getInt(orderIndex); @@ -414,7 +414,7 @@ private void extractStorageContents(GuiGraphicsExtractor graphics, int mouseX, i } if (hovered) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_HIGHLIGHT_FRONT_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, StorageScreen.SLOT_HIGHLIGHT_FRONT_SPRITE, x - 4, y - 4, 24, 24); } } this.extractStorageSlider(graphics); @@ -464,7 +464,7 @@ private void extractPlayerInventory(GuiGraphicsExtractor graphics, int mouseX, i private void extractInventorySlot(GuiGraphicsExtractor graphics, Inventory inv, int slot, int x, int y, int mouseX, int mouseY) { boolean hovered = MathUtil.isInRange(mouseX, mouseY, x - 2, y - 2, x + 17, y + 17); if (hovered) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_HIGHLIGHT_BACK_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, StorageScreen.SLOT_HIGHLIGHT_BACK_SPRITE, x - 4, y - 4, 24, 24); } ItemStack stack = inv.getItem(slot); @@ -482,7 +482,7 @@ private void extractInventorySlot(GuiGraphicsExtractor graphics, Inventory inv, } if (hovered) { - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_HIGHLIGHT_FRONT_SPRITE, x - 4, y - 4, 24, 24); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, StorageScreen.SLOT_HIGHLIGHT_FRONT_SPRITE, x - 4, y - 4, 24, 24); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureScannerScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureScannerScreen.java index fff341e41c..a878548089 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureScannerScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureScannerScreen.java @@ -204,7 +204,7 @@ protected void init() { this.topPos + 119, 16, 16, - REDO_TEXTURE, + StructureScannerScreen.REDO_TEXTURE, 16, 32, (_) -> this.onModeToggleClick(), @@ -219,7 +219,7 @@ protected void init() { this.topPos + 90, 16, 16, - CONFIRM_TEXTURE, + StructureScannerScreen.CONFIRM_TEXTURE, 16, 16, 32, @@ -257,8 +257,11 @@ private void renderMaskedItem(GuiGraphicsExtractor g, ItemStack stack, int x, in @Override public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { super.extractBackground(graphics, mouseX, mouseY, a); - graphics.blit(RenderPipelines - .GUI_TEXTURED, BACKGROUND, this.leftPos, this.topPos, 0, 0, this.getImageWidth(), this.getImageHeight(), 256, 256); + graphics.blit( + RenderPipelines + .GUI_TEXTURED, StructureScannerScreen.BACKGROUND, this.leftPos, this.topPos, 0, 0, this.getImageWidth(), + this.getImageHeight(), 256, 256 + ); // 渲染磁盘槽位的虚影(当槽位为空时) var blockEntity = this.menu.getBlockEntity(); @@ -292,8 +295,11 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse this.renderInfoPanel(graphics); // 渲染STRUCTURE_TOOL_LOCKED贴图 - graphics.blit(RenderPipelines - .GUI_TEXTURED, STRUCTURE_TOOL_LOCKED_TEXTURE, this.leftPos + 6, this.topPos + 18, 0, 0, 126, 26, 126, 26); + graphics.blit( + RenderPipelines + .GUI_TEXTURED, StructureScannerScreen.STRUCTURE_TOOL_LOCKED_TEXTURE, this.leftPos + 6, this.topPos + 18, 0, 0, 126, 26, 126, + 26 + ); // 收集并渲染所有tooltip List tooltipsToRender = new ArrayList<>(); @@ -501,13 +507,13 @@ private void updateModeToggleButton() { if (this.isScanMode) { this.isScanMode = false; this.modeToggleButton.setSelected(false); - this.modeToggleButton.setTexture(STOP_TEXTURE); + this.modeToggleButton.setTexture(StructureScannerScreen.STOP_TEXTURE); } } else if (this.cachedIsScanComplete) { if (!this.isScanMode) { this.isScanMode = true; this.modeToggleButton.setSelected(true); - this.modeToggleButton.setTexture(REDO_TEXTURE); + this.modeToggleButton.setTexture(StructureScannerScreen.REDO_TEXTURE); } } } @@ -628,9 +634,11 @@ private void renderPreviewWithFixedSize( if (!scannedBlocks.isEmpty()) { for (StructureScannerBlockEntity.CachedBlockData data : scannedBlocks) { - BlockState rotatedState = this.rotateBlockStateForPreview(data.state(), facing); int renderY = upsideDown ? (Math.max(1, rangeY) - 1 - data.y()) : data.y(); - previewLevelLike.setBlockState(new BlockPos(data.x(), renderY, data.z() + 1), rotatedState); + BlockPos renderPos = new BlockPos(data.x(), renderY, data.z() + 1); + BlockPos worldPos = this.cachedBlockEntity.getBlockPos().offset(renderPos); + BlockState rotatedState = this.rotateBlockStateForPreview(data.state(), facing, level, worldPos); + previewLevelLike.setBlockState(renderPos, rotatedState); } } @@ -641,14 +649,19 @@ private void renderPreviewWithFixedSize( } /// 根据 Scanner 朝向旋转方块状态 - private BlockState rotateBlockStateForPreview(BlockState state, Direction scannerFacing) { + private BlockState rotateBlockStateForPreview( + BlockState state, + Direction scannerFacing, + ClientLevel level, + BlockPos pos + ) { Rotation rotation = switch (scannerFacing) { case SOUTH -> Rotation.CLOCKWISE_180; case WEST -> Rotation.CLOCKWISE_90; case EAST -> Rotation.COUNTERCLOCKWISE_90; default -> Rotation.NONE; }; - return state.rotate(rotation); + return state.rotate(level, pos, rotation); } @SuppressWarnings("unused") @@ -742,9 +755,10 @@ public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) float deltaX = currentMouseX - this.lastMouseX; float deltaY = currentMouseY - this.lastMouseY; - this.previewRotationY += deltaX * ROTATION_SENSITIVITY; - this.previewRotationX += deltaY * ROTATION_SENSITIVITY; - this.previewRotationX = Math.clamp(this.previewRotationX, MIN_ROTATION_X, MAX_ROTATION_X); + this.previewRotationY += deltaX * StructureScannerScreen.ROTATION_SENSITIVITY; + this.previewRotationX += deltaY * StructureScannerScreen.ROTATION_SENSITIVITY; + this.previewRotationX = Math.clamp( + this.previewRotationX, StructureScannerScreen.MIN_ROTATION_X, StructureScannerScreen.MAX_ROTATION_X); this.lastMouseX = currentMouseX; this.lastMouseY = currentMouseY; @@ -775,13 +789,13 @@ private void onModeToggleClick() { this.isScanMode = false; this.modeToggleButton.setSelected(false); - this.modeToggleButton.setTexture(STOP_TEXTURE); + this.modeToggleButton.setTexture(StructureScannerScreen.STOP_TEXTURE); } else { ClientPacketDistributor.sendToServer(new StructureScannerActionPacket(Action.STOP)); this.isScanMode = true; this.modeToggleButton.setSelected(true); - this.modeToggleButton.setTexture(REDO_TEXTURE); + this.modeToggleButton.setTexture(StructureScannerScreen.REDO_TEXTURE); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureToolScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureToolScreen.java index 539353c3ab..01220fada8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureToolScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/StructureToolScreen.java @@ -73,9 +73,9 @@ public class StructureToolScreen extends AbstractContainerScreen RESULT_SLOT_TOOLTIPS = ImmutableList.of( - REGULAR_RECIPE_TOOLTIP, - CONVERSION_RECIPE_TOOLTIP, - CONVERSION_OUTPUT_TOOLTIP + StructureToolScreen.REGULAR_RECIPE_TOOLTIP, + StructureToolScreen.CONVERSION_RECIPE_TOOLTIP, + StructureToolScreen.CONVERSION_OUTPUT_TOOLTIP ); private static char currentSymbol; @@ -101,7 +101,7 @@ protected void init() { offsetY + 21, 46, 16, - BUTTON, + StructureToolScreen.BUTTON, 16, 46, 32, @@ -129,7 +129,7 @@ protected void init() { offsetY + 37, 46, 16, - BUTTON, + StructureToolScreen.BUTTON, 16, 46, 32, @@ -140,7 +140,7 @@ protected void init() { offsetY + 53, 46, 16, - BUTTON, + StructureToolScreen.BUTTON, 16, 46, 32, @@ -161,7 +161,7 @@ protected void init() { case IDatagen datagenRecipe -> datagenRecipe.getSuggestedName(); default -> Integer.toHexString(recipe.hashCode()); }; - String pathString = getFilePath(defaultName, "*.json"); + String pathString = StructureToolScreen.getFilePath(defaultName, "*.json"); if (pathString == null) { this.minecraft.player.sendSystemMessage( Component.translatable("message.anvilcraft.no_file_selected") @@ -224,7 +224,7 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse } graphics.text( - font, + this.font, Component.translatable("screen.anvilcraft.structure_tool.count", blockCount), 18, 72, @@ -269,8 +269,8 @@ public void extractContents(GuiGraphicsExtractor graphics, int mouseX, int mouse @Override protected void extractTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { - if (this.hoveredSlot != null && this.hoveredSlot.index == SLOT_ID_RESULT && !this.hoveredSlot.hasItem()) { - graphics.setComponentTooltipForNextFrame(this.font, RESULT_SLOT_TOOLTIPS, mouseX, mouseY); + if (this.hoveredSlot != null && this.hoveredSlot.index == StructureToolScreen.SLOT_ID_RESULT && !this.hoveredSlot.hasItem()) { + graphics.setComponentTooltipForNextFrame(this.font, StructureToolScreen.RESULT_SLOT_TOOLTIPS, mouseX, mouseY); } super.extractTooltip(graphics, mouseX, mouseY); } @@ -280,7 +280,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + StructureToolScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -308,26 +308,26 @@ private static String getFilePath(String defaultName, String filter) { private Recipe toRecipe() { BlockPattern inputPattern = this.toBlockPattern(this.structureData); if (inputPattern == null) return null; - ItemStack result = menu.slots.get(SLOT_ID_RESULT).getItem().copy(); + ItemStack result = this.menu.slots.get(StructureToolScreen.SLOT_ID_RESULT).getItem().copy(); if (result.is(ModItems.STRUCTURE_TOOL)) { StructureData outputData = result.get(ModComponents.STRUCTURE_DATA); if (outputData == null) return null; if (!outputData.isCube()) { - minecraft.player.sendSystemMessage( + this.minecraft.player.sendSystemMessage( Component.translatable("tooltip.anvilcraft.item.structure_tool.must_cube") .withStyle(ChatFormatting.RED) ); return null; } if (!outputData.isOddCubeWithinSize(15)) { - minecraft.player.sendSystemMessage( + this.minecraft.player.sendSystemMessage( Component.translatable("tooltip.anvilcraft.item.structure_tool.must_odd") .withStyle(ChatFormatting.RED) ); return null; } if (this.structureData.getSizeX() != outputData.getSizeX()) { - minecraft.player.sendSystemMessage( + this.minecraft.player.sendSystemMessage( Component.translatable("tooltip.anvilcraft.item.structure_tool.inconsistent_size") .withStyle(ChatFormatting.RED) ); @@ -393,8 +393,8 @@ private BlockPredicateWithState buildPredicate(BlockState state, boolean recordA BlockPredicateWithState predicate = BlockPredicateWithState.of(block); state.getProperties().stream() .filter(p -> recordAllStates - || DEFAULT_RECORDED_PROPERTIES.contains(p) - || (BlockStateUtil.isMultifaceLike(block) + || StructureToolScreen.DEFAULT_RECORDED_PROPERTIES.contains(p) + || (BlockStateUtil.isMultifaceLike(block) && p instanceof BooleanProperty && PipeBlock.PROPERTY_BY_DIRECTION.containsValue(p))) .forEach(p -> predicate.copyPropertyFrom(state, p)); @@ -408,10 +408,10 @@ private BlockPattern toBlockPattern(@Nullable StructureData data) { @Nullable private BlockPattern toBlockPattern(@Nullable StructureData data, boolean recordAllStates) { - ClientLevel level = minecraft.level; + ClientLevel level = this.minecraft.level; if (data != null && level != null) { BlockPattern pattern = BlockPattern.create(); - currentSymbol = '@'; + StructureToolScreen.currentSymbol = '@'; BlockPos.MutableBlockPos mpos = new BlockPos.MutableBlockPos(); for (int y = data.minY(); y <= data.maxY(); y++) { List layer = new ArrayList<>(); @@ -439,8 +439,8 @@ private BlockPattern toBlockPattern(@Nullable StructureData data, boolean record private char getAndPutSymbol(Map symbols, BlockPredicateWithState predicate) { if (symbols.entrySet().stream().noneMatch(e -> e.getValue().equals(predicate))) { - currentSymbol++; - symbols.put(currentSymbol, predicate); + StructureToolScreen.currentSymbol++; + symbols.put(StructureToolScreen.currentSymbol, predicate); } else { for (Map.Entry entry : symbols.entrySet()) { if (entry.getValue().equals(predicate)) { @@ -448,6 +448,6 @@ private char getAndPutSymbol(Map symbols, Bl } } } - return currentSymbol; + return StructureToolScreen.currentSymbol; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TeslaTowerScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TeslaTowerScreen.java index 8ef57f3323..4c55885af4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TeslaTowerScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TeslaTowerScreen.java @@ -152,7 +152,7 @@ void removeWhiteFilter(String id, String arg) { public Component getFilterTitle(int index, int variant) { int actualIndex = index; - if (variant == FILTER_FILTERED) { + if (variant == TeslaTowerScreen.FILTER_FILTERED) { actualIndex += this.leftScrollOff; if (this.filteredFilters.isEmpty() || actualIndex >= this.filteredFilters.size()) return Component.empty(); Pair filter = this.filteredFilters.get(actualIndex); @@ -167,7 +167,7 @@ public Component getFilterTitle(int index, int variant) { public @Nullable String getFilterToolTipAt(int index, int variant) { int actualIndex = index; - if (variant == FILTER_FILTERED) { + if (variant == TeslaTowerScreen.FILTER_FILTERED) { actualIndex += this.leftScrollOff; if (this.filteredFilters.isEmpty() || actualIndex >= this.filteredFilters.size()) return null; Pair filter = this.filteredFilters.get(actualIndex); @@ -191,13 +191,13 @@ protected void init() { super.init(); this.titleLabelX = (this.getImageWidth() - this.font.width(this.title)) / 2; this.titleLabelY = Constant.SCREEN_TITLE_Y; - int buttonTop = topPos + 35; + int buttonTop = this.topPos + 35; for (int l = 0; l < 8; ++l) { TeslaTowerButton button = new TeslaTowerButton( - leftPos + START_LEFT_X, + this.leftPos + TeslaTowerScreen.START_LEFT_X, buttonTop, l, - FILTER_FILTERED, + TeslaTowerScreen.FILTER_FILTERED, b -> { if (b instanceof TeslaTowerButton silencerButton) { this.onAllFilterButtonClick(silencerButton.getIndex()); @@ -210,13 +210,13 @@ protected void init() { buttonTop += 15; } - buttonTop = topPos + 35; + buttonTop = this.topPos + 35; for (int l = 0; l < 8; ++l) { TeslaTowerButton button = new TeslaTowerButton( - leftPos + START_RIGHT_X, + this.leftPos + TeslaTowerScreen.START_RIGHT_X, buttonTop, l, - SOUND_MUTED, + TeslaTowerScreen.SOUND_MUTED, b -> { if (b instanceof TeslaTowerButton silencerButton) { this.onWhiteListFilterButtonClick(silencerButton.getIndex()); @@ -230,8 +230,8 @@ protected void init() { this.editBox = new EditBox( this.minecraft.font, - leftPos + 78, - topPos + 19, + this.leftPos + 78, + this.topPos + 19, 100, 12, Component.translatable("screen.anvilcraft.active_silencer.search")); @@ -257,31 +257,31 @@ protected void init() { } private boolean mouseInLeft(double mouseX, double mouseY, int leftPos, int topPos) { - return mouseX >= leftPos + START_LEFT_X - && mouseX <= leftPos + SCROLL_BAR_START_LEFT_X + SCROLL_BAR_WIDTH - && mouseY >= topPos + SCROLL_BAR_TOP_POS_Y - && mouseY <= topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT; + return mouseX >= leftPos + TeslaTowerScreen.START_LEFT_X + && mouseX <= leftPos + TeslaTowerScreen.SCROLL_BAR_START_LEFT_X + TeslaTowerScreen.SCROLL_BAR_WIDTH + && mouseY >= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + && mouseY <= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + TeslaTowerScreen.SCROLL_BAR_HEIGHT; } private boolean mouseInRight(double mouseX, double mouseY, int leftPos, int topPos) { - return mouseX >= leftPos + START_RIGHT_X - && mouseX <= leftPos + SCROLL_BAR_START_RIGHT_X + SCROLL_BAR_WIDTH - && mouseY >= topPos + SCROLL_BAR_TOP_POS_Y - && mouseY <= topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT; + return mouseX >= leftPos + TeslaTowerScreen.START_RIGHT_X + && mouseX <= leftPos + TeslaTowerScreen.SCROLL_BAR_START_RIGHT_X + TeslaTowerScreen.SCROLL_BAR_WIDTH + && mouseY >= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + && mouseY <= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + TeslaTowerScreen.SCROLL_BAR_HEIGHT; } private boolean mouseInLeftSlider(double mouseX, double mouseY, int leftPos, int topPos) { - return mouseX >= leftPos + SCROLL_BAR_START_LEFT_X - && mouseX <= leftPos + SCROLL_BAR_START_LEFT_X + SCROLL_BAR_WIDTH - && mouseY >= topPos + SCROLL_BAR_TOP_POS_Y - && mouseY <= topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT; + return mouseX >= leftPos + TeslaTowerScreen.SCROLL_BAR_START_LEFT_X + && mouseX <= leftPos + TeslaTowerScreen.SCROLL_BAR_START_LEFT_X + TeslaTowerScreen.SCROLL_BAR_WIDTH + && mouseY >= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + && mouseY <= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + TeslaTowerScreen.SCROLL_BAR_HEIGHT; } private boolean mouseInRightSlider(double mouseX, double mouseY, int leftPos, int topPos) { - return mouseX >= leftPos + SCROLL_BAR_START_RIGHT_X - && mouseX <= leftPos + SCROLL_BAR_START_RIGHT_X + SCROLL_BAR_WIDTH - && mouseY >= topPos + SCROLL_BAR_TOP_POS_Y - && mouseY <= topPos + SCROLL_BAR_TOP_POS_Y + SCROLL_BAR_HEIGHT; + return mouseX >= leftPos + TeslaTowerScreen.SCROLL_BAR_START_RIGHT_X + && mouseX <= leftPos + TeslaTowerScreen.SCROLL_BAR_START_RIGHT_X + TeslaTowerScreen.SCROLL_BAR_WIDTH + && mouseY >= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + && mouseY <= topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y + TeslaTowerScreen.SCROLL_BAR_HEIGHT; } @Override @@ -311,8 +311,8 @@ public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) if (this.mouseInLeftSlider(event.x(), event.y(), leftPos, topPos)) { int i = this.filteredFilters.size(); if (this.isDraggingLeft) { - int j = this.topPos + SCROLL_BAR_TOP_POS_Y; - int k = j + SCROLL_BAR_HEIGHT; + int j = this.topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y; + int k = j + TeslaTowerScreen.SCROLL_BAR_HEIGHT; int dragMax = i - 7; float scroll = (float) ((event.y() - j - 13.5F) / ((k - j) - 27.0F)); scroll = scroll * dragMax + 0.5F; @@ -325,8 +325,8 @@ public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) if (this.mouseInRightSlider(event.x(), event.y(), leftPos, topPos)) { int i = this.whiteFilters.size(); if (this.isDraggingRight) { - int j = this.topPos + SCROLL_BAR_TOP_POS_Y; - int k = j + SCROLL_BAR_HEIGHT; + int j = this.topPos + TeslaTowerScreen.SCROLL_BAR_TOP_POS_Y; + int k = j + TeslaTowerScreen.SCROLL_BAR_HEIGHT; int dragMax = i - 7; float scroll = (float) ((event.y() - j - 13.5F) / ((k - j) - 27.0F)); scroll = scroll * dragMax + 0.5F; @@ -365,8 +365,8 @@ public boolean mouseClicked(MouseButtonEvent event, boolean handled) { private void extractScroller(GuiGraphicsExtractor graphics, int posX, int posY, int totalCount, int scrollOff) { int i = totalCount + 1 - 8; if (i > 1) { - int maxY = posY + SCROLL_BAR_HEIGHT - SCROLLER_HEIGHT; - int scrollY = (int) (posY + (scrollOff / (float) totalCount) * SCROLL_BAR_HEIGHT); + int maxY = posY + TeslaTowerScreen.SCROLL_BAR_HEIGHT - TeslaTowerScreen.SCROLLER_HEIGHT; + int scrollY = (int) (posY + (scrollOff / (float) totalCount) * TeslaTowerScreen.SCROLL_BAR_HEIGHT); scrollY = Mth.clamp(scrollY, posY, maxY); graphics.blit(RenderPipelines.GUI_TEXTURED, SharedTextures.SMALL_MACHINE_SLIDER, posX, scrollY, 0, 0, 5, 9, 10, 9); @@ -401,7 +401,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, a); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + TeslaTowerScreen.BACKGROUND, this.leftPos, this.topPos, 0, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TradingStationScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TradingStationScreen.java index a5ba900501..5ac3400cee 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TradingStationScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TradingStationScreen.java @@ -64,7 +64,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, partialTick); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + TradingStationScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -92,8 +92,8 @@ protected void init() { 16, 16, List.of( - PLAYER_NOT_ALLOW, - PLAYER_ALLOW + TradingStationScreen.PLAYER_NOT_ALLOW, + TradingStationScreen.PLAYER_ALLOW ), 16, 16, @@ -117,8 +117,8 @@ protected void init() { 16, 16, List.of( - VILLAGER_NOT_ALLOW, - VILLAGER_ALLOW + TradingStationScreen.VILLAGER_NOT_ALLOW, + TradingStationScreen.VILLAGER_ALLOW ), 16, 16, @@ -142,8 +142,8 @@ protected void init() { 16, 16, List.of( - INPUT_NOT_ALLOW, - INPUT_ALLOW + TradingStationScreen.INPUT_NOT_ALLOW, + TradingStationScreen.INPUT_ALLOW ), 16, 16, @@ -167,8 +167,8 @@ protected void init() { 16, 16, List.of( - OUTPUT_NOT_ALLOW, - OUTPUT_ALLOW + TradingStationScreen.OUTPUT_NOT_ALLOW, + TradingStationScreen.OUTPUT_ALLOW ), 16, 16, @@ -290,8 +290,8 @@ protected List getTooltipFromContainerItem(ItemStack stack) { .withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY) ); } else if (this.hoveredSlot instanceof SlotItemHandlerWithFilter filterSlot && filterSlot.isFilter()) { - components.add(SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); - components.add(SHIFT_TO_SCROLL_FASTER_TOOLTIP); + components.add(IFilterScreen.SCROLL_WHEEL_TO_CHANGE_STACK_LIMIT_TOOLTIP); + components.add(IFilterScreen.SHIFT_TO_SCROLL_FASTER_TOOLTIP); } return components; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TranscendenceAnvilScreen.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TranscendenceAnvilScreen.java index 37b3ddc219..37af842504 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TranscendenceAnvilScreen.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/TranscendenceAnvilScreen.java @@ -30,7 +30,7 @@ public class TranscendenceAnvilScreen extends ItemCombinerScreen EMPTY_SLOT_DEFORMATION_MATERIAL = List.of(EMPTY_SLOT_INGOT); + private static final List EMPTY_SLOT_DEFORMATION_MATERIAL = List.of(TranscendenceSmithingScreen.EMPTY_SLOT_INGOT); private static final Quaternionf ARMOR_STAND_ANGLE = new Quaternionf().rotationXYZ(0.43633232f, 0.0f, (float) Math.PI); private static final Vector3f ARMOR_STAND_TRANSLATION = new Vector3f(0.0F, 1.0F, 0.0F); @@ -173,7 +173,7 @@ private void createFrostButtons() { this.topPos + 32, 7, 11, - LEFT, + TranscendenceSmithingScreen.LEFT, 11, 7, 22, @@ -184,7 +184,7 @@ private void createFrostButtons() { this.topPos + 32, 7, 11, - RIGHT, + TranscendenceSmithingScreen.RIGHT, 11, 7, 22, @@ -262,7 +262,7 @@ private void tickFrostIcons() { return; } if (item instanceof DeformationTemplateItem deformation) { - this.firstInputIcon.tick(EMPTY_SLOT_DEFORMATION_MATERIAL); + this.firstInputIcon.tick(TranscendenceSmithingScreen.EMPTY_SLOT_DEFORMATION_MATERIAL); this.secondInputIcon.tick(deformation.getEmptySlotTextures()); return; } @@ -301,7 +301,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou super.extractBackground(graphics, mouseX, mouseY, partialTick); graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + TranscendenceSmithingScreen.BACKGROUND, this.leftPos, this.topPos, 0, @@ -319,7 +319,7 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou 0, 0, this.getImageWidth(), - OVERLAY_HEIGHT, + TranscendenceSmithingScreen.OVERLAY_HEIGHT, 256, 128 ); @@ -333,31 +333,31 @@ public void extractBackground(GuiGraphicsExtractor graphics, int mouseX, int mou private Identifier modeOverlay() { return switch (this.menu.getMode()) { - case ROYAL -> ROYAL_OVERLAY; - case EMBER -> EMBER_OVERLAY; - case FROST -> FROST_OVERLAY; + case ROYAL -> TranscendenceSmithingScreen.ROYAL_OVERLAY; + case EMBER -> TranscendenceSmithingScreen.EMBER_OVERLAY; + case FROST -> TranscendenceSmithingScreen.FROST_OVERLAY; }; } private void extractTemplatePanel(GuiGraphicsExtractor graphics) { graphics.blit( RenderPipelines.GUI_TEXTURED, - TEMPLATE_PANEL, + TranscendenceSmithingScreen.TEMPLATE_PANEL, this.panelX(), this.panelY(), 0, 0, - PANEL_WIDTH, - PANEL_HEIGHT, - PANEL_WIDTH, - PANEL_HEIGHT + TranscendenceSmithingScreen.PANEL_WIDTH, + TranscendenceSmithingScreen.PANEL_HEIGHT, + TranscendenceSmithingScreen.PANEL_WIDTH, + TranscendenceSmithingScreen.PANEL_HEIGHT ); int maxScrollRow = this.maxScrollRow(); if (maxScrollRow > 0) { graphics.blit( RenderPipelines.GUI_TEXTURED, SharedTextures.SWITCH_TABLE_SLIDER, - this.panelX() + SLIDER_X, + this.panelX() + TranscendenceSmithingScreen.SLIDER_X, this.sliderY(maxScrollRow), 0, 0, @@ -372,12 +372,15 @@ private void extractTemplatePanel(GuiGraphicsExtractor graphics) { private void extractTemplateItems(GuiGraphicsExtractor graphics) { List templates = this.filteredTemplates(); - int start = this.scrollRow * COLUMN_COUNT; - int end = Math.min(start + COLUMN_COUNT * VISIBLE_ROW_COUNT, templates.size()); + int start = this.scrollRow * TranscendenceSmithingScreen.COLUMN_COUNT; + int end = Math.min( + start + TranscendenceSmithingScreen.COLUMN_COUNT * TranscendenceSmithingScreen.VISIBLE_ROW_COUNT, templates.size()); for (int index = start; index < end; index++) { int visibleIndex = index - start; - int x = this.panelX() + TEMPLATE_GRID_X + visibleIndex % COLUMN_COUNT * TEMPLATE_SLOT_SIZE; - int y = this.panelY() + TEMPLATE_GRID_Y + visibleIndex / COLUMN_COUNT * TEMPLATE_SLOT_SIZE; + int x = this.panelX() + TranscendenceSmithingScreen.TEMPLATE_GRID_X + + visibleIndex % TranscendenceSmithingScreen.COLUMN_COUNT * TranscendenceSmithingScreen.TEMPLATE_SLOT_SIZE; + int y = this.panelY() + TranscendenceSmithingScreen.TEMPLATE_GRID_Y + + visibleIndex / TranscendenceSmithingScreen.COLUMN_COUNT * TranscendenceSmithingScreen.TEMPLATE_SLOT_SIZE; ItemStack template = templates.get(index); if (this.isFavorite(template)) { graphics.fill(RenderPipelines.GUI, x, y, x + 16, y + 16, 0x66FFFF00); @@ -392,7 +395,10 @@ private void extractTemplateItems(GuiGraphicsExtractor graphics) { private void extractVirtualTemplate(GuiGraphicsExtractor graphics) { ItemStack template = this.menu.getSelectedTemplate(); if (template.isEmpty()) return; - graphics.item(template, this.leftPos + VIRTUAL_TEMPLATE_X, this.topPos + VIRTUAL_TEMPLATE_Y); + graphics.item( + template, this.leftPos + TranscendenceSmithingScreen.VIRTUAL_TEMPLATE_X, + this.topPos + TranscendenceSmithingScreen.VIRTUAL_TEMPLATE_Y + ); } private void extractSlotIcons(GuiGraphicsExtractor graphics, float partialTick) { @@ -469,8 +475,8 @@ private void extractArmorStand(GuiGraphicsExtractor graphics) { graphics.entity( this.armorStandPreview, 25, - ARMOR_STAND_TRANSLATION, - ARMOR_STAND_ANGLE, + TranscendenceSmithingScreen.ARMOR_STAND_TRANSLATION, + TranscendenceSmithingScreen.ARMOR_STAND_ANGLE, null, this.leftPos + 131, this.topPos + 20, @@ -506,10 +512,14 @@ private void extractTemplateTooltip(GuiGraphicsExtractor graphics, int mouseX, i } private void extractVirtualTemplateTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { - if (!this.isHovering(VIRTUAL_TEMPLATE_X, VIRTUAL_TEMPLATE_Y, 16, 16, mouseX, mouseY)) return; + if (!this.isHovering( + TranscendenceSmithingScreen.VIRTUAL_TEMPLATE_X, TranscendenceSmithingScreen.VIRTUAL_TEMPLATE_Y, 16, 16, mouseX, mouseY)) { + return; + } ItemStack template = this.menu.getSelectedTemplate(); if (template.isEmpty()) { - graphics.setTooltipForNextFrame(this.font, this.font.split(MISSING_TEMPLATE_TOOLTIP, 115), mouseX, mouseY); + graphics.setTooltipForNextFrame( + this.font, this.font.split(TranscendenceSmithingScreen.MISSING_TEMPLATE_TOOLTIP, 115), mouseX, mouseY); return; } graphics.setTooltipForNextFrame( @@ -524,11 +534,12 @@ private void extractVirtualTemplateTooltip(GuiGraphicsExtractor graphics, int mo private void extractOnboardingTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { if (this.extractErrorTooltip(graphics, mouseX, mouseY)) return; - if (this.hoveredSlot == null || !this.hoveredSlot.getItem().isEmpty()) return; + Slot hoveredSlot = this.hoveredSlot; + if (hoveredSlot == null || !hoveredSlot.getItem().isEmpty()) return; switch (this.menu.getMode()) { - case ROYAL -> this.extractRoyalSlotTooltip(graphics, mouseX, mouseY); - case EMBER -> this.extractEmberSlotTooltip(graphics, mouseX, mouseY); - case FROST -> this.extractFrostSlotTooltip(graphics, mouseX, mouseY); + case ROYAL -> this.extractRoyalSlotTooltip(graphics, mouseX, mouseY, hoveredSlot); + case EMBER -> this.extractEmberSlotTooltip(graphics, mouseX, mouseY, hoveredSlot); + case FROST -> this.extractFrostSlotTooltip(graphics, mouseX, mouseY, hoveredSlot); default -> throw new IllegalStateException("Unknown smithing mode: " + this.menu.getMode()); } } @@ -538,7 +549,7 @@ private boolean extractErrorTooltip(GuiGraphicsExtractor graphics, int mouseX, i if (this.hasCompleteEmberInput() && this.menu.getActiveResult().isEmpty() && this.isHovering(123, 48, 16, 16, mouseX, mouseY)) { - graphics.setTooltipForNextFrame(this.font, this.font.split(ERROR_TOOLTIP, 115), mouseX, mouseY); + graphics.setTooltipForNextFrame(this.font, this.font.split(TranscendenceSmithingScreen.ERROR_TOOLTIP, 115), mouseX, mouseY); return true; } return false; @@ -546,16 +557,16 @@ private boolean extractErrorTooltip(GuiGraphicsExtractor graphics, int mouseX, i if (this.hasCompleteRoyalFrostInput() && this.menu.getActiveResult().isEmpty() && this.isHovering(83, 48, 16, 16, mouseX, mouseY)) { - graphics.setTooltipForNextFrame(this.font, this.font.split(ERROR_TOOLTIP, 115), mouseX, mouseY); + graphics.setTooltipForNextFrame(this.font, this.font.split(TranscendenceSmithingScreen.ERROR_TOOLTIP, 115), mouseX, mouseY); return true; } return false; } - private void extractRoyalSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { + private void extractRoyalSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY, Slot hoveredSlot) { Item item = this.menu.getSelectedTemplate().getItem(); if (!(item instanceof SmithingTemplateItem template)) return; - Component tooltip = switch (this.hoveredSlot.index) { + Component tooltip = switch (hoveredSlot.index) { case TranscendenceSmithingMenu.ROYAL_FROST_FIRST_INPUT_SLOT -> template.getBaseSlotDescription(); case TranscendenceSmithingMenu.ROYAL_FROST_SECOND_INPUT_SLOT -> template.getAdditionSlotDescription(); default -> null; @@ -565,10 +576,10 @@ private void extractRoyalSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, } } - private void extractEmberSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { + private void extractEmberSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY, Slot hoveredSlot) { Item item = this.menu.getSelectedTemplate().getItem(); if (!(item instanceof BaseMultipleToOneTemplateItem template)) return; - if (this.hoveredSlot.index == TranscendenceSmithingMenu.EMBER_MATERIAL_SLOT) { + if (hoveredSlot.index == TranscendenceSmithingMenu.EMBER_MATERIAL_SLOT) { graphics.setTooltipForNextFrame( this.font, this.font.split(template.getMaterialTooltip(), 115), @@ -577,8 +588,8 @@ private void extractEmberSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, ); return; } - if (this.hoveredSlot.index < TranscendenceSmithingMenu.EMBER_INPUT_SLOT_START - || this.hoveredSlot.index >= TranscendenceSmithingMenu.EMBER_INPUT_SLOT_END) { + if (hoveredSlot.index < TranscendenceSmithingMenu.EMBER_INPUT_SLOT_START + || hoveredSlot.index >= TranscendenceSmithingMenu.EMBER_INPUT_SLOT_END) { return; } ItemStack material = this.menu.getEmberMaterial(); @@ -591,23 +602,23 @@ private void extractEmberSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, } } - private void extractFrostSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY) { + private void extractFrostSlotTooltip(GuiGraphicsExtractor graphics, int mouseX, int mouseY, Slot hoveredSlot) { Item item = this.menu.getSelectedTemplate().getItem(); if (item instanceof PermutationTemplateItem permutation) { - if (this.hoveredSlot.index == TranscendenceSmithingMenu.ROYAL_FROST_FIRST_INPUT_SLOT) { + if (hoveredSlot.index == TranscendenceSmithingMenu.ROYAL_FROST_FIRST_INPUT_SLOT) { graphics.setTooltipForNextFrame( this.font, this.font.split(permutation.getMaterialTooltip(), 115), mouseX, mouseY ); - } else if (this.hoveredSlot.index == TranscendenceSmithingMenu.ROYAL_FROST_SECOND_INPUT_SLOT + } else if (hoveredSlot.index == TranscendenceSmithingMenu.ROYAL_FROST_SECOND_INPUT_SLOT && this.menu.getRoyalFrostFirstInput().getItem() instanceof IPermutationMaterial material) { Component tooltip = material.getInputTooltip(this.menu.getRoyalFrostFirstInput()); graphics.setTooltipForNextFrame(this.font, this.font.split(tooltip, 115), mouseX, mouseY); } } else if (item instanceof DeformationTemplateItem deformation - && this.hoveredSlot.index == TranscendenceSmithingMenu.ROYAL_FROST_SECOND_INPUT_SLOT) { + && hoveredSlot.index == TranscendenceSmithingMenu.ROYAL_FROST_SECOND_INPUT_SLOT) { graphics.setTooltipForNextFrame( this.font, this.font.split(deformation.getInputTooltip(), 115), @@ -665,7 +676,6 @@ public boolean mouseClicked(MouseButtonEvent event, boolean handled) { } private void playTemplateClickSound() { - if (this.minecraft == null) return; this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); } @@ -707,16 +717,19 @@ private List filteredTemplates() { } private ItemStack templateAt(double mouseX, double mouseY) { - int relativeX = (int) mouseX - this.panelX() - TEMPLATE_GRID_X; - int relativeY = (int) mouseY - this.panelY() - TEMPLATE_GRID_Y; + int relativeX = (int) mouseX - this.panelX() - TranscendenceSmithingScreen.TEMPLATE_GRID_X; + int relativeY = (int) mouseY - this.panelY() - TranscendenceSmithingScreen.TEMPLATE_GRID_Y; if (relativeX < 0 || relativeY < 0) return ItemStack.EMPTY; - int column = relativeX / TEMPLATE_SLOT_SIZE; - int row = relativeY / TEMPLATE_SLOT_SIZE; - if (column >= COLUMN_COUNT || row >= VISIBLE_ROW_COUNT) return ItemStack.EMPTY; - if (relativeX % TEMPLATE_SLOT_SIZE >= 16 || relativeY % TEMPLATE_SLOT_SIZE >= 16) { + int column = relativeX / TranscendenceSmithingScreen.TEMPLATE_SLOT_SIZE; + int row = relativeY / TranscendenceSmithingScreen.TEMPLATE_SLOT_SIZE; + if (column >= TranscendenceSmithingScreen.COLUMN_COUNT || row >= TranscendenceSmithingScreen.VISIBLE_ROW_COUNT) { + return ItemStack.EMPTY; + } + if (relativeX % TranscendenceSmithingScreen.TEMPLATE_SLOT_SIZE >= 16 + || relativeY % TranscendenceSmithingScreen.TEMPLATE_SLOT_SIZE >= 16) { return ItemStack.EMPTY; } - int index = (this.scrollRow + row) * COLUMN_COUNT + column; + int index = (this.scrollRow + row) * TranscendenceSmithingScreen.COLUMN_COUNT + column; List templates = this.filteredTemplates(); return index < templates.size() ? templates.get(index) : ItemStack.EMPTY; } @@ -731,14 +744,15 @@ private void clampScrollRow() { } private int maxScrollRow() { - int rowCount = (this.filteredTemplates().size() + COLUMN_COUNT - 1) / COLUMN_COUNT; - return Math.max(0, rowCount - VISIBLE_ROW_COUNT); + int rowCount = + (this.filteredTemplates().size() + TranscendenceSmithingScreen.COLUMN_COUNT - 1) / TranscendenceSmithingScreen.COLUMN_COUNT; + return Math.max(0, rowCount - TranscendenceSmithingScreen.VISIBLE_ROW_COUNT); } private int sliderY(int maxScrollRow) { - if (maxScrollRow <= 0) return this.panelY() + SLIDER_MIN_Y; - int travel = SLIDER_MAX_Y - SLIDER_MIN_Y; - return this.panelY() + SLIDER_MIN_Y + Math.round((float) this.scrollRow / maxScrollRow * travel); + if (maxScrollRow <= 0) return this.panelY() + TranscendenceSmithingScreen.SLIDER_MIN_Y; + int travel = TranscendenceSmithingScreen.SLIDER_MAX_Y - TranscendenceSmithingScreen.SLIDER_MIN_Y; + return this.panelY() + TranscendenceSmithingScreen.SLIDER_MIN_Y + Math.round((float) this.scrollRow / maxScrollRow * travel); } private void updateScrollFromSlider(double mouseY, int maxScrollRow) { @@ -746,38 +760,39 @@ private void updateScrollFromSlider(double mouseY, int maxScrollRow) { this.scrollRow = 0; return; } - double sliderCenter = mouseY - this.panelY() - SLIDER_MIN_Y - 6; - double progress = Mth.clamp(sliderCenter / (SLIDER_MAX_Y - SLIDER_MIN_Y), 0.0, 1.0); + double sliderCenter = mouseY - this.panelY() - TranscendenceSmithingScreen.SLIDER_MIN_Y - 6; + double progress = Mth.clamp( + sliderCenter / (TranscendenceSmithingScreen.SLIDER_MAX_Y - TranscendenceSmithingScreen.SLIDER_MIN_Y), 0.0, 1.0); this.scrollRow = Mth.clamp((int) Math.round(progress * maxScrollRow), 0, maxScrollRow); } private boolean isOverTemplateGrid(double mouseX, double mouseY) { return mouseX >= this.panelX() + 3 - && mouseX < this.panelX() + 66 - && mouseY >= this.panelY() + 17 - && mouseY < this.panelY() + 129; + && mouseX < this.panelX() + 66 + && mouseY >= this.panelY() + 17 + && mouseY < this.panelY() + 129; } private boolean isOverTemplatePanel(double mouseX, double mouseY) { return mouseX >= this.panelX() - && mouseX < this.panelX() + PANEL_WIDTH - && mouseY >= this.panelY() - && mouseY < this.panelY() + PANEL_HEIGHT; + && mouseX < this.panelX() + TranscendenceSmithingScreen.PANEL_WIDTH + && mouseY >= this.panelY() + && mouseY < this.panelY() + TranscendenceSmithingScreen.PANEL_HEIGHT; } private boolean isOverSlider(double mouseX, double mouseY) { - return mouseX >= this.panelX() + SLIDER_X - && mouseX < this.panelX() + SLIDER_X + 8 - && mouseY >= this.panelY() + SLIDER_MIN_Y - && mouseY < this.panelY() + SLIDER_MAX_Y + 12; + return mouseX >= this.panelX() + TranscendenceSmithingScreen.SLIDER_X + && mouseX < this.panelX() + TranscendenceSmithingScreen.SLIDER_X + 8 + && mouseY >= this.panelY() + TranscendenceSmithingScreen.SLIDER_MIN_Y + && mouseY < this.panelY() + TranscendenceSmithingScreen.SLIDER_MAX_Y + 12; } private int panelX() { - return this.leftPos - PANEL_RIGHT_BORDER; + return this.leftPos - TranscendenceSmithingScreen.PANEL_RIGHT_BORDER; } private int panelY() { - return this.topPos + PANEL_TOP_OFFSET; + return this.topPos + TranscendenceSmithingScreen.PANEL_TOP_OFFSET; } private void updateArmorStandPreview() { diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyInfoFormatter.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyInfoFormatter.java index fbf9f50193..207f927225 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyInfoFormatter.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyInfoFormatter.java @@ -38,44 +38,47 @@ public static List format( List lines = new ArrayList<>(); boolean isError = body instanceof SpecialCelestialBodyData special && special.isErrorPlanet(); - lines.add(Component.translatable(PREFIX + "type", Component.translatable(typeKey(body)))); - lines.add(measurement( + lines.add(Component.translatable( + CelestialBodyInfoFormatter.PREFIX + "type", + Component.translatable(CelestialBodyInfoFormatter.typeKey(body)) + )); + lines.add(CelestialBodyInfoFormatter.measurement( "age", isError ? "???" : CelestialForgingAnvilMenu.formatAgeOffset(ageAnvilCount, offsetAge) )); - lines.add(measurement( + lines.add(CelestialBodyInfoFormatter.measurement( "radius", isError ? "???" : CelestialForgingAnvilMenu.formatRadiusOffset(body.size(), offsetRadius) )); - lines.add(measurement( + lines.add(CelestialBodyInfoFormatter.measurement( "mass", isError ? "???" : CelestialForgingAnvilMenu.formatMassOffset(massAnvilCount, offsetMass) )); switch (body) { - case SpecialCelestialBodyData special -> addSpecialBodyLines(lines, special); - case StarData star -> addStarLines(lines, star); - case RockyPlanetData rocky -> addRockyPlanetLines(lines, rocky); - case GiantPlanetData giant -> addGiantPlanetLines(lines, giant); + case SpecialCelestialBodyData special -> CelestialBodyInfoFormatter.addSpecialBodyLines(lines, special); + case StarData star -> CelestialBodyInfoFormatter.addStarLines(lines, star); + case RockyPlanetData rocky -> CelestialBodyInfoFormatter.addRockyPlanetLines(lines, rocky); + case GiantPlanetData giant -> CelestialBodyInfoFormatter.addGiantPlanetLines(lines, giant); } return lines; } private static Component measurement(String name, String value) { - return Component.translatable(PREFIX + name, Component.literal(value)); + return Component.translatable(CelestialBodyInfoFormatter.PREFIX + name, Component.literal(value)); } private static String typeKey(CelestialBodyData body) { - if (body instanceof RockyPlanetData rocky) return rockyTypeKey(rocky); - if (body instanceof SpecialCelestialBodyData special) return PREFIX + "class.special." + special.name(); - return PREFIX + "class." + body.bodyClass().name().toLowerCase(Locale.ROOT); + if (body instanceof RockyPlanetData rocky) return CelestialBodyInfoFormatter.rockyTypeKey(rocky); + if (body instanceof SpecialCelestialBodyData special) return CelestialBodyInfoFormatter.PREFIX + "class.special." + special.name(); + return CelestialBodyInfoFormatter.PREFIX + "class." + body.bodyClass().name().toLowerCase(Locale.ROOT); } private static void addSpecialBodyLines(List lines, SpecialCelestialBodyData body) { if (body.isErrorPlanet()) { for (String name : List.of("temp", "atmos", "liquid", "mag", "spin", "tilt")) { - lines.add(measurement(name, "???")); + lines.add(CelestialBodyInfoFormatter.measurement(name, "???")); } return; } - addPlanetLines( + CelestialBodyInfoFormatter.addPlanetLines( lines, body.temperature(), body.hasAtmosphere(), @@ -87,15 +90,15 @@ private static void addSpecialBodyLines(List lines, SpecialCelestialB } private static void addStarLines(List lines, StarData body) { - lines.add(magneticFieldText(body.magneticFieldStrength())); - lines.add(rotationText(body.rotationSpeed())); + lines.add(CelestialBodyInfoFormatter.magneticFieldText(body.magneticFieldStrength())); + lines.add(CelestialBodyInfoFormatter.rotationText(body.rotationSpeed())); if (body.axialTilt() > 0.1f) { - lines.add(axialTiltText(body.axialTilt())); + lines.add(CelestialBodyInfoFormatter.axialTiltText(body.axialTilt())); } } private static void addRockyPlanetLines(List lines, RockyPlanetData body) { - addPlanetLines( + CelestialBodyInfoFormatter.addPlanetLines( lines, body.temperature(), body.hasAtmosphere(), @@ -115,73 +118,77 @@ private static void addPlanetLines( int rotationSpeed, float axialTilt ) { - lines.add(temperatureText(temperature)); - lines.add(atmosphereText(hasAtmosphere)); - lines.add(liquidText(liquidCoverage)); - lines.add(magneticFieldText(magneticFieldStrength)); - lines.add(rotationText(rotationSpeed)); - lines.add(axialTiltText(axialTilt)); + lines.add(CelestialBodyInfoFormatter.temperatureText(temperature)); + lines.add(CelestialBodyInfoFormatter.atmosphereText(hasAtmosphere)); + lines.add(CelestialBodyInfoFormatter.liquidText(liquidCoverage)); + lines.add(CelestialBodyInfoFormatter.magneticFieldText(magneticFieldStrength)); + lines.add(CelestialBodyInfoFormatter.rotationText(rotationSpeed)); + lines.add(CelestialBodyInfoFormatter.axialTiltText(axialTilt)); } private static void addGiantPlanetLines(List lines, GiantPlanetData body) { if (!body.brownDwarf()) { lines.add(Component.translatable( - PREFIX + "pressure", - Component.translatable(PREFIX + "pressure." + body.pressureType().getSerializedName()) + CelestialBodyInfoFormatter.PREFIX + "pressure", + Component.translatable(CelestialBodyInfoFormatter.PREFIX + "pressure." + body.pressureType().getSerializedName()) )); } lines.add(Component.translatable( - PREFIX + "wind", - Component.translatable(PREFIX + "wind." + body.windSpeed().getSerializedName()) + CelestialBodyInfoFormatter.PREFIX + "wind", + Component.translatable(CelestialBodyInfoFormatter.PREFIX + "wind." + body.windSpeed().getSerializedName()) )); - lines.add(magneticFieldText(body.magneticFieldStrength())); - lines.add(rotationText(body.rotationSpeed())); - lines.add(axialTiltText(body.axialTilt())); + lines.add(CelestialBodyInfoFormatter.magneticFieldText(body.magneticFieldStrength())); + lines.add(CelestialBodyInfoFormatter.rotationText(body.rotationSpeed())); + lines.add(CelestialBodyInfoFormatter.axialTiltText(body.axialTilt())); } private static Component temperatureText(@Nullable Temperature temperature) { - String key = temperature == null ? PREFIX + "none" : PREFIX + "temp." + temperature.getSerializedName(); - return Component.translatable(PREFIX + "temp", Component.translatable(key)); + String key = temperature == null ? CelestialBodyInfoFormatter.PREFIX + "none" + : CelestialBodyInfoFormatter.PREFIX + "temp." + temperature.getSerializedName(); + return Component.translatable(CelestialBodyInfoFormatter.PREFIX + "temp", Component.translatable(key)); } private static Component atmosphereText(boolean hasAtmosphere) { return Component.translatable( - PREFIX + "atmos", Component.translatable(hasAtmosphere ? PREFIX + "atmos.yes" : PREFIX + "none") + CelestialBodyInfoFormatter.PREFIX + "atmos", Component.translatable( + hasAtmosphere ? CelestialBodyInfoFormatter.PREFIX + "atmos.yes" : CelestialBodyInfoFormatter.PREFIX + "none") ); } private static Component liquidText(@Nullable LiquidCoverage coverage) { - String key = coverage == null ? PREFIX + "none" : PREFIX + "liquid." + coverage.getSerializedName(); - return Component.translatable(PREFIX + "liquid", Component.translatable(key)); + String key = coverage == null ? CelestialBodyInfoFormatter.PREFIX + "none" + : CelestialBodyInfoFormatter.PREFIX + "liquid." + coverage.getSerializedName(); + return Component.translatable(CelestialBodyInfoFormatter.PREFIX + "liquid", Component.translatable(key)); } private static Component magneticFieldText(int level) { String key = switch (level) { - case 0 -> PREFIX + "none"; - case 1 -> PREFIX + "mag.very_weak"; - case 2 -> PREFIX + "mag.weak"; - case 3 -> PREFIX + "mag.medium"; - case 4 -> PREFIX + "mag.strong"; - case 5 -> PREFIX + "mag.very_strong"; - default -> PREFIX + "mag.extreme"; + case 0 -> CelestialBodyInfoFormatter.PREFIX + "none"; + case 1 -> CelestialBodyInfoFormatter.PREFIX + "mag.very_weak"; + case 2 -> CelestialBodyInfoFormatter.PREFIX + "mag.weak"; + case 3 -> CelestialBodyInfoFormatter.PREFIX + "mag.medium"; + case 4 -> CelestialBodyInfoFormatter.PREFIX + "mag.strong"; + case 5 -> CelestialBodyInfoFormatter.PREFIX + "mag.very_strong"; + default -> CelestialBodyInfoFormatter.PREFIX + "mag.extreme"; }; - return Component.translatable(PREFIX + "mag", Component.translatable(key)); + return Component.translatable(CelestialBodyInfoFormatter.PREFIX + "mag", Component.translatable(key)); } private static Component rotationText(int level) { String key = switch (level) { - case 0 -> PREFIX + "spin.very_slow"; - case 1 -> PREFIX + "spin.slow"; - case 2 -> PREFIX + "spin.medium"; - case 3 -> PREFIX + "spin.fast"; - case 4 -> PREFIX + "spin.very_fast"; - default -> PREFIX + "spin.super_fast"; + case 0 -> CelestialBodyInfoFormatter.PREFIX + "spin.very_slow"; + case 1 -> CelestialBodyInfoFormatter.PREFIX + "spin.slow"; + case 2 -> CelestialBodyInfoFormatter.PREFIX + "spin.medium"; + case 3 -> CelestialBodyInfoFormatter.PREFIX + "spin.fast"; + case 4 -> CelestialBodyInfoFormatter.PREFIX + "spin.very_fast"; + default -> CelestialBodyInfoFormatter.PREFIX + "spin.super_fast"; }; - return Component.translatable(PREFIX + "spin", Component.translatable(key)); + return Component.translatable(CelestialBodyInfoFormatter.PREFIX + "spin", Component.translatable(key)); } private static Component axialTiltText(float tilt) { - return Component.translatable(PREFIX + "tilt", formatThreeSignificantFigures(tilt) + "°"); + return Component.translatable( + CelestialBodyInfoFormatter.PREFIX + "tilt", CelestialBodyInfoFormatter.formatThreeSignificantFigures(tilt) + "°"); } private static String rockyTypeKey(RockyPlanetData body) { @@ -191,22 +198,22 @@ private static String rockyTypeKey(RockyPlanetData body) { boolean hasLiquid = liquid != LiquidCoverage.NONE; if (temperature == Temperature.FREEZING) { - if (!hasLiquid && !hasAtmosphere) return PREFIX + "class.freezing_no_liquid_no_atmos"; - if (!hasLiquid) return PREFIX + "class.freezing_no_liquid_atmos"; - return PREFIX + "class.freezing_liquid"; + if (!hasLiquid && !hasAtmosphere) return CelestialBodyInfoFormatter.PREFIX + "class.freezing_no_liquid_no_atmos"; + if (!hasLiquid) return CelestialBodyInfoFormatter.PREFIX + "class.freezing_no_liquid_atmos"; + return CelestialBodyInfoFormatter.PREFIX + "class.freezing_liquid"; } if (temperature == Temperature.SCORCHED) { - if (!hasLiquid && !hasAtmosphere) return PREFIX + "class.scorched_no_liquid_no_atmos"; - if (!hasLiquid) return PREFIX + "class.scorched_no_liquid_atmos"; - return PREFIX + "class.scorched_liquid"; + if (!hasLiquid && !hasAtmosphere) return CelestialBodyInfoFormatter.PREFIX + "class.scorched_no_liquid_no_atmos"; + if (!hasLiquid) return CelestialBodyInfoFormatter.PREFIX + "class.scorched_no_liquid_atmos"; + return CelestialBodyInfoFormatter.PREFIX + "class.scorched_liquid"; } - if (!hasAtmosphere) return PREFIX + "class.deathly_planet"; - if (!hasLiquid) return PREFIX + "class.desert_planet"; + if (!hasAtmosphere) return CelestialBodyInfoFormatter.PREFIX + "class.deathly_planet"; + if (!hasLiquid) return CelestialBodyInfoFormatter.PREFIX + "class.desert_planet"; return switch (liquid) { - case LOW -> temperatureTypeKey(temperature, "riverbank"); - case MEDIUM -> temperatureTypeKey(temperature, "land_ocean"); - case HIGH -> temperatureTypeKey(temperature, "ocean"); - default -> PREFIX + "class.deathly_planet"; + case LOW -> CelestialBodyInfoFormatter.temperatureTypeKey(temperature, "riverbank"); + case MEDIUM -> CelestialBodyInfoFormatter.temperatureTypeKey(temperature, "land_ocean"); + case HIGH -> CelestialBodyInfoFormatter.temperatureTypeKey(temperature, "ocean"); + default -> CelestialBodyInfoFormatter.PREFIX + "class.deathly_planet"; }; } @@ -216,7 +223,7 @@ private static String temperatureTypeKey(Temperature temperature, String suffix) case HOT -> "hot"; default -> "mild"; }; - return PREFIX + "class." + prefix + "_" + suffix; + return CelestialBodyInfoFormatter.PREFIX + "class." + prefix + "_" + suffix; } @SuppressWarnings("MalformedFormatString") diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyPreviewRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyPreviewRenderer.java index b4161e0e5c..5d587cef1b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyPreviewRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CelestialBodyPreviewRenderer.java @@ -65,13 +65,13 @@ public static void renderMegastructure( int width, int height ) { - StandaloneModelKey model = resolveMegastructureModel(option); + StandaloneModelKey model = CelestialBodyPreviewRenderer.resolveMegastructureModel(option); float divisor = switch (option.ring()) { - case 1 -> RING1_SCALE_DIVISOR; - case 2 -> RING2_SCALE_DIVISOR; - case 4 -> RING4_SCALE_DIVISOR; - case 5 -> RING5_SCALE_DIVISOR; - case 6 -> RING6_SCALE_DIVISOR; + case 1 -> CelestialBodyPreviewRenderer.RING1_SCALE_DIVISOR; + case 2 -> CelestialBodyPreviewRenderer.RING2_SCALE_DIVISOR; + case 4 -> CelestialBodyPreviewRenderer.RING4_SCALE_DIVISOR; + case 5 -> CelestialBodyPreviewRenderer.RING5_SCALE_DIVISOR; + case 6 -> CelestialBodyPreviewRenderer.RING6_SCALE_DIVISOR; default -> 1.0f; }; float scale = Math.min(width, height) * 1.15f / divisor; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CfaPreviewPipRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CfaPreviewPipRenderer.java index 3e14ed96be..58fd3bee74 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CfaPreviewPipRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/screen/cfa/CfaPreviewPipRenderer.java @@ -100,7 +100,7 @@ private void submitBody(BodyContent content, PoseStack poseStack, SubmitNodeColl float rotation = content.animationTick() * CelestialBodyData.getVisualRotationSpeed(body.rotationSpeed()); poseStack.pushPose(); - poseStack.mulPose(Axis.XP.rotationDegrees(UI_AXIAL_TILT)); + poseStack.mulPose(Axis.XP.rotationDegrees(CfaPreviewPipRenderer.UI_AXIAL_TILT)); poseStack.mulPose(Axis.YP.rotationDegrees(rotation)); poseStack.translate(-0.5f, -0.5f, -0.5f); @@ -266,7 +266,7 @@ private void submitCelestialRing( }; poseStack.pushPose(); poseStack.scale(ringScale, ringScale, ringScale); - poseStack.mulPose(Axis.XP.rotationDegrees(UI_AXIAL_TILT)); + poseStack.mulPose(Axis.XP.rotationDegrees(CfaPreviewPipRenderer.UI_AXIAL_TILT)); poseStack.mulPose(Axis.YP.rotationDegrees(rotation)); poseStack.translate(-0.5f, -0.5f, -0.5f); collector.submitCustomGeometry( diff --git a/src/main/java/dev/dubhe/anvilcraft/client/gui/tooltip/ClientCreativeContainerTooltip.java b/src/main/java/dev/dubhe/anvilcraft/client/gui/tooltip/ClientCreativeContainerTooltip.java index 48b43409d1..976e417bce 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/gui/tooltip/ClientCreativeContainerTooltip.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/gui/tooltip/ClientCreativeContainerTooltip.java @@ -25,14 +25,14 @@ public ClientCreativeContainerTooltip(CreativeContainerTooltip tooltip) { @Override public int getHeight(Font font) { - return this.tooltip.entries().size() * ROW_HEIGHT; + return this.tooltip.entries().size() * ClientCreativeContainerTooltip.ROW_HEIGHT; } @Override public int getWidth(Font font) { int width = 0; for (CreativeContainerTooltip.Entry entry : this.tooltip.entries()) { - width = Math.max(width, TEXT_X_OFFSET + font.width(entry.text())); + width = Math.max(width, ClientCreativeContainerTooltip.TEXT_X_OFFSET + font.width(entry.text())); } return width; } @@ -41,13 +41,16 @@ public int getWidth(Font font) { public void extractImage(Font font, int x, int y, int w, int h, GuiGraphicsExtractor graphics) { int row = 0; for (CreativeContainerTooltip.Entry entry : this.tooltip.entries()) { - int rowY = y + row * ROW_HEIGHT; + int rowY = y + row * ClientCreativeContainerTooltip.ROW_HEIGHT; if (entry.isFluid()) { - renderFluidIcon(graphics, entry.fluid(), x, rowY); + ClientCreativeContainerTooltip.renderFluidIcon(graphics, entry.fluid(), x, rowY); } else { graphics.item(entry.item(), x, rowY); } - graphics.text(font, entry.text(), x + TEXT_X_OFFSET, rowY + TEXT_Y_OFFSET, 0xFFFFFFFF, false); + graphics.text( + font, entry.text(), x + ClientCreativeContainerTooltip.TEXT_X_OFFSET, rowY + ClientCreativeContainerTooltip.TEXT_Y_OFFSET, + 0xFFFFFFFF, false + ); row++; } } @@ -62,6 +65,9 @@ private static void renderFluidIcon(GuiGraphicsExtractor graphics, FluidStack fl if (tintSource == null) return; TextureAtlasSprite sprite = model.stillMaterial().sprite(); int tint = tintSource.colorAsStack(resource.toStack(1)); - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, sprite, x, y, ICON_SIZE, ICON_SIZE, tint); + graphics.blitSprite( + RenderPipelines.GUI_TEXTURED, sprite, x, y, ClientCreativeContainerTooltip.ICON_SIZE, ClientCreativeContainerTooltip.ICON_SIZE, + tint + ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/hud/AttackIndicatorProgressHUD.java b/src/main/java/dev/dubhe/anvilcraft/client/hud/AttackIndicatorProgressHUD.java index 31fdbaa0e5..60127d563f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/hud/AttackIndicatorProgressHUD.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/hud/AttackIndicatorProgressHUD.java @@ -21,20 +21,23 @@ public static void render(GuiGraphicsExtractor graphics, float progress) { float clamped = Math.clamp(progress, 0.0F, 1.0F); int x = graphics.guiWidth() / 2 - 8; int y = graphics.guiHeight() / 2 + 9; - int progressWidth = Math.min(WIDTH, (int) (clamped * 17.0F)); - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, BACKGROUND, x, y, WIDTH, HEIGHT); + int progressWidth = Math.min(AttackIndicatorProgressHUD.WIDTH, (int) (clamped * 17.0F)); + graphics.blitSprite( + RenderPipelines.GUI_TEXTURED, AttackIndicatorProgressHUD.BACKGROUND, x, y, AttackIndicatorProgressHUD.WIDTH, + AttackIndicatorProgressHUD.HEIGHT + ); if (progressWidth > 0) { graphics.blitSprite( RenderPipelines.GUI_TEXTURED, - PROGRESS, - WIDTH, - HEIGHT, + AttackIndicatorProgressHUD.PROGRESS, + AttackIndicatorProgressHUD.WIDTH, + AttackIndicatorProgressHUD.HEIGHT, 0, 0, x, y, progressWidth, - HEIGHT + AttackIndicatorProgressHUD.HEIGHT ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/hud/EnergyWeaponUseHUD.java b/src/main/java/dev/dubhe/anvilcraft/client/hud/EnergyWeaponUseHUD.java index 1ebaf44ce5..feeea30786 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/hud/EnergyWeaponUseHUD.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/hud/EnergyWeaponUseHUD.java @@ -36,7 +36,7 @@ public static void render(GuiGraphicsExtractor graphics, DeltaTracker deltaTrack if (minecraft.options.hideGui || minecraft.screen != null) return; LocalPlayer player = minecraft.player; if (player == null || !player.isUsingItem()) { - LASER_PROGRESS.reset(); + EnergyWeaponUseHUD.LASER_PROGRESS.reset(); return; } @@ -45,18 +45,18 @@ public static void render(GuiGraphicsExtractor graphics, DeltaTracker deltaTrack float progress; switch (stack.getItem()) { case AnvilRailgunItem anvilRailgunItem -> { - LASER_PROGRESS.reset(); + EnergyWeaponUseHUD.LASER_PROGRESS.reset(); if (AnvilRailgunItem.isLoading(player, stack, player.getUsedItemHand())) return; int elapsed = stack.getUseDuration(player) - player.getUseItemRemainingTicks(); progress = AnvilRailgunItem.chargeProgress(player.level(), stack, elapsed, partialTick); } - case LaserGunItem laserGunItem -> progress = LASER_PROGRESS.get(player, stack, partialTick); + case LaserGunItem laserGunItem -> progress = EnergyWeaponUseHUD.LASER_PROGRESS.get(player, stack, partialTick); case TranscendenceResonatorItem transcendenceResonatorItem -> { - LASER_PROGRESS.reset(); + EnergyWeaponUseHUD.LASER_PROGRESS.reset(); progress = TranscendenceResonatorItem.resonanceMiningProgress(player.level(), player, partialTick); } default -> { - LASER_PROGRESS.reset(); + EnergyWeaponUseHUD.LASER_PROGRESS.reset(); return; } } @@ -96,8 +96,8 @@ private float get(LocalPlayer player, ItemStack stack, float partialTick) { this.targetTicks = 0; } this.targetTicks += elapsedDelta; - if (this.targetTicks >= DAMAGE_STAGE_TICKS * MAX_DAMAGE_STAGE) return 1.0F; - return ((this.targetTicks % DAMAGE_STAGE_TICKS) + partialTick) / DAMAGE_STAGE_TICKS; + if (this.targetTicks >= EnergyWeaponUseHUD.DAMAGE_STAGE_TICKS * EnergyWeaponUseHUD.MAX_DAMAGE_STAGE) return 1.0F; + return ((this.targetTicks % EnergyWeaponUseHUD.DAMAGE_STAGE_TICKS) + partialTick) / EnergyWeaponUseHUD.DAMAGE_STAGE_TICKS; } this.target = null; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/hud/IonoCraftBackpackHUD.java b/src/main/java/dev/dubhe/anvilcraft/client/hud/IonoCraftBackpackHUD.java index 1084ba97dd..c6e5188c8d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/hud/IonoCraftBackpackHUD.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/hud/IonoCraftBackpackHUD.java @@ -36,8 +36,8 @@ public static void render(GuiGraphicsExtractor graphics, DeltaTracker partialTic ItemStack backpack = IonoCraftBackpackItem.getByPlayer(player); boolean renderBackpack = config.enabled && backpack.is(ModItems.IONOCRAFT_BACKPACK); Inventory inventory = player.getInventory(); - int capacitorCount = count(inventory, ModItems.CAPACITOR.asStack()); - int superCapacitorCount = count(inventory, ModItems.SUPER_CAPACITOR.asStack()); + int capacitorCount = IonoCraftBackpackHUD.count(inventory, ModItems.CAPACITOR.asStack()); + int superCapacitorCount = IonoCraftBackpackHUD.count(inventory, ModItems.SUPER_CAPACITOR.asStack()); boolean renderCapacitors = config.capacitorCountEnabled && (capacitorCount > 0 || superCapacitorCount > 0); if (!renderBackpack && !renderCapacitors) return; @@ -47,11 +47,11 @@ public static void render(GuiGraphicsExtractor graphics, DeltaTracker partialTic pose.scale(config.hudScale, config.hudScale); pose.translate(config.hudX, config.hudY); if (renderBackpack) { - renderBackpack(graphics, mc.font, backpack); - pose.translate(0, ROW_HEIGHT); + IonoCraftBackpackHUD.renderBackpack(graphics, mc.font, backpack); + pose.translate(0, IonoCraftBackpackHUD.ROW_HEIGHT); } if (renderCapacitors) { - renderCapacitorCounts(graphics, mc.font, capacitorCount, superCapacitorCount); + IonoCraftBackpackHUD.renderCapacitorCounts(graphics, mc.font, capacitorCount, superCapacitorCount); } pose.popMatrix(); @@ -63,7 +63,7 @@ private static void renderBackpack(GuiGraphicsExtractor graphics, Font font, Ite int energy = IonoCraftBackpackItem.getEnergyStored(backpack); int percent = Math.round((float) energy / IonoCraftBackpackItem.MAX_ENERGY * 100); float ratio = Math.clamp((float) energy / IonoCraftBackpackItem.MAX_ENERGY, 0, 1); - int color = ColorUtil.lerpColor(ratio, BAR_COLOR, FULL_BAR_COLOR); + int color = ColorUtil.lerpColor(ratio, IonoCraftBackpackHUD.BAR_COLOR, IonoCraftBackpackHUD.FULL_BAR_COLOR); graphics.item(backpack, 0, 0); pose.translate(20, 4); @@ -76,7 +76,7 @@ private static void renderBackpack(GuiGraphicsExtractor graphics, Font font, Ite pose.translate(textWidth + 4, -4); graphics.blit( RenderPipelines.GUI_TEXTURED, - BATTERY_EMPTY, + IonoCraftBackpackHUD.BATTERY_EMPTY, 0, 0, 8, @@ -90,7 +90,7 @@ private static void renderBackpack(GuiGraphicsExtractor graphics, Font font, Ite pose.translate(0, 0); graphics.blit( RenderPipelines.GUI_TEXTURED, - BATTERY_FULL, + IonoCraftBackpackHUD.BATTERY_FULL, 0, 16 - batteryHeight, 0, @@ -113,11 +113,11 @@ private static void renderCapacitorCounts( graphics.item(ModItems.CAPACITOR.asStack(), 0, 0); graphics.text(font, Component.literal("x " + capacitorCount), 20, 4, 0xFFFFFFFF, true); - graphics.item(ModItems.SUPER_CAPACITOR.asStack(), SUPER_CAPACITOR_X, 0); + graphics.item(ModItems.SUPER_CAPACITOR.asStack(), IonoCraftBackpackHUD.SUPER_CAPACITOR_X, 0); graphics.text( font, Component.literal("x " + superCapacitorCount), - SUPER_CAPACITOR_X + 20, + IonoCraftBackpackHUD.SUPER_CAPACITOR_X + 20, 4, 0xFFFFFFFF, true diff --git a/src/main/java/dev/dubhe/anvilcraft/client/init/ModKeyMappings.java b/src/main/java/dev/dubhe/anvilcraft/client/init/ModKeyMappings.java index 0b08f41b91..dde3a5160b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/init/ModKeyMappings.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/init/ModKeyMappings.java @@ -15,31 +15,31 @@ public class ModKeyMappings { public static final KeyMapping.Category ANVILCRAFT_CATEGORY = new KeyMapping.Category(AnvilCraft.of("all")); - public static final Lazy SWITCH_PHASE = register( + public static final Lazy SWITCH_PHASE = ModKeyMappings.register( "switch_phase", KeyConflictContext.IN_GAME, Type.KEYSYM, GLFW.GLFW_KEY_X ); - public static final Lazy TOGGLE_GOGGLE = register( + public static final Lazy TOGGLE_GOGGLE = ModKeyMappings.register( "toggle_goggle", KeyConflictContext.IN_GAME, Type.KEYSYM, GLFW.GLFW_KEY_UNKNOWN ); - public static final Lazy SWITCH_TOOL_MODE = register( + public static final Lazy SWITCH_TOOL_MODE = ModKeyMappings.register( "switch_tool_mode", KeyConflictContext.IN_GAME, Type.KEYSYM, GLFW.GLFW_KEY_LEFT_ALT ); - public static final Lazy USE_PILL_BOX = register( + public static final Lazy USE_PILL_BOX = ModKeyMappings.register( "use_pill_box", KeyConflictContext.IN_GAME, Type.KEYSYM, GLFW.GLFW_KEY_V ); - public static final Lazy THOUGHT = register( + public static final Lazy THOUGHT = ModKeyMappings.register( "thought", KeyConflictContext.GUI, Type.KEYSYM, @@ -48,15 +48,15 @@ public class ModKeyMappings { @SuppressWarnings("SameParameterValue") private static Lazy register(String name, KeyConflictContext context, Type type, int key) { - return Lazy.of(() -> new KeyMapping("key.anvilcraft." + name, context, type, key, ANVILCRAFT_CATEGORY)); + return Lazy.of(() -> new KeyMapping("key.anvilcraft." + name, context, type, key, ModKeyMappings.ANVILCRAFT_CATEGORY)); } @SubscribeEvent public static void register(RegisterKeyMappingsEvent event) { event.registerCategory(ModKeyMappings.ANVILCRAFT_CATEGORY); - event.register(SWITCH_PHASE.get()); - event.register(TOGGLE_GOGGLE.get()); - event.register(SWITCH_TOOL_MODE.get()); - event.register(USE_PILL_BOX.get()); + event.register(ModKeyMappings.SWITCH_PHASE.get()); + event.register(ModKeyMappings.TOGGLE_GOGGLE.get()); + event.register(ModKeyMappings.SWITCH_TOOL_MODE.get()); + event.register(ModKeyMappings.USE_PILL_BOX.get()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/init/ModModelLayers.java b/src/main/java/dev/dubhe/anvilcraft/client/init/ModModelLayers.java index 5efbf7c7aa..ad8eef48c6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/init/ModModelLayers.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/init/ModModelLayers.java @@ -29,29 +29,29 @@ public class ModModelLayers { @SubscribeEvent public static void register(EntityRenderersEvent.RegisterLayerDefinitions event) { event.registerLayerDefinition( - IONOCRAFT, + ModModelLayers.IONOCRAFT, IonocraftModel::createBodyLayer ); event.registerLayerDefinition( - IONOCRAFT_BACKPACK, + ModModelLayers.IONOCRAFT_BACKPACK, IonocraftBackpackModel::createBodyLayer ); event.registerLayerDefinition( - THROWN_HEAVY_HALBERD, + ModModelLayers.THROWN_HEAVY_HALBERD, ThrownHeavyHalberdModel::createBodyLayer ); event.registerLayerDefinition( - MAGNETIZED_NODE, + ModModelLayers.MAGNETIZED_NODE, MagnetizedNodeModel::createBodyLayer ); event.registerLayerDefinition( - CAULDRON_OUTLET, + ModModelLayers.CAULDRON_OUTLET, CauldronOutletModel::createBodyLayer ); } @SubscribeEvent public static void createModel(EntityRenderersEvent.AddLayers event) { - ionocraftBackpackModel = new IonocraftBackpackModel(event.getContext().bakeLayer(IONOCRAFT_BACKPACK)); + ModModelLayers.ionocraftBackpackModel = new IonocraftBackpackModel(event.getContext().bakeLayer(ModModelLayers.IONOCRAFT_BACKPACK)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/init/ModPostEffects.java b/src/main/java/dev/dubhe/anvilcraft/client/init/ModPostEffects.java index 51dfd502b8..2163715d32 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/init/ModPostEffects.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/init/ModPostEffects.java @@ -3,7 +3,6 @@ import dev.anvilcraft.lib.v2.rendering.event.MainTargetResizeEvent; import dev.dubhe.anvilcraft.AnvilCraft; import dev.dubhe.anvilcraft.client.renderer.post.GravitationalLensPostEffect; -import lombok.Getter; import net.neoforged.api.distmarker.Dist; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber; @@ -15,21 +14,21 @@ public class ModPostEffects { private static GravitationalLensPostEffect gravitationalLensPostEffect = null; public static void createPostEffects() { - gravitationalLensPostEffect = new GravitationalLensPostEffect(); + ModPostEffects.gravitationalLensPostEffect = new GravitationalLensPostEffect(); } public static @Nullable GravitationalLensPostEffect getGravitationalLensPostEffect() { - if (gravitationalLensPostEffect == null) { - createPostEffects(); + if (ModPostEffects.gravitationalLensPostEffect == null) { + ModPostEffects.createPostEffects(); } - return gravitationalLensPostEffect; + return ModPostEffects.gravitationalLensPostEffect; } @SubscribeEvent public static void on(MainTargetResizeEvent event) { - if (gravitationalLensPostEffect == null) { - createPostEffects(); + if (ModPostEffects.gravitationalLensPostEffect == null) { + ModPostEffects.createPostEffects(); } - gravitationalLensPostEffect.resize(event.getNewWidth(), event.getNewHeight()); + ModPostEffects.gravitationalLensPostEffect.resize(event.getNewWidth(), event.getNewHeight()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderPipelines.java b/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderPipelines.java index ade11adcbf..693ad758e1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderPipelines.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderPipelines.java @@ -57,14 +57,14 @@ public class ModRenderPipelines { .build(); public static final RenderPipeline LASER_TRANSLUCENT = RenderPipeline.builder(RenderPipelines.BLOCK_SNIPPET) - .withColorTargetState(new ColorTargetState(LASER_BLEND)) + .withColorTargetState(new ColorTargetState(ModRenderPipelines.LASER_BLEND)) .withShaderDefine("ALPHA_CUTOUT", 0.01F) .withDepthStencilState(DepthStencilState.DEFAULT) .withLocation(AnvilCraft.of("pipeline/translucent_laser")) .build(); public static final RenderPipeline LIGHTNING = RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) - .withColorTargetState(new ColorTargetState(LASER_BLEND)) + .withColorTargetState(new ColorTargetState(ModRenderPipelines.LASER_BLEND)) .withShaderDefine("ALPHA_CUTOUT", 0.01F) .withVertexFormat(DefaultVertexFormat.POSITION_TEX_COLOR, VertexFormat.Mode.QUADS) .withVertexShader(Identifier.withDefaultNamespace("core/position_tex_color")) @@ -75,7 +75,7 @@ public class ModRenderPipelines { .build(); public static final RenderPipeline SUPERNOVA_BEAM = RenderPipeline.builder(RenderPipelines.BEACON_BEAM_SNIPPET) - .withColorTargetState(new ColorTargetState(ADDITIVE_BLEND)) + .withColorTargetState(new ColorTargetState(ModRenderPipelines.ADDITIVE_BLEND)) .withShaderDefine("ALPHA_CUTOUT", 0.01F) .withDepthStencilState(new DepthStencilState(CompareOp.LESS_THAN_OR_EQUAL, false)) .withCull(false) @@ -87,7 +87,7 @@ public class ModRenderPipelines { * 不采样纹理且不写入深度,与 1.21 的 POSITION_COLOR 渲染类型保持一致。 */ public static final RenderPipeline STELLAR_BEAM = RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) - .withColorTargetState(new ColorTargetState(ADDITIVE_BLEND)) + .withColorTargetState(new ColorTargetState(ModRenderPipelines.ADDITIVE_BLEND)) .withDepthStencilState(new DepthStencilState(CompareOp.LESS_THAN_OR_EQUAL, false)) .withCull(false) .withLocation(AnvilCraft.of("pipeline/stellar_beam")) @@ -108,7 +108,7 @@ public class ModRenderPipelines { .build(); public static final RenderPipeline STAR_COLOR_OVERLAY = RenderPipeline.builder(RenderPipelines.BLOCK_SNIPPET) - .withColorTargetState(new ColorTargetState(MULTIPLY_BLEND)) + .withColorTargetState(new ColorTargetState(ModRenderPipelines.MULTIPLY_BLEND)) .withShaderDefine("ALPHA_CUTOUT", 0.01F) .withDepthStencilState(DepthStencilState.DEFAULT) .withLocation(AnvilCraft.of("pipeline/star_color_overlay")) @@ -135,7 +135,7 @@ public class ModRenderPipelines { .build(); public static final RenderPipeline SUPERNOVA_FLASH = RenderPipeline.builder(RenderPipelines.BLOCK_SNIPPET) - .withColorTargetState(new ColorTargetState(ADDITIVE_BLEND)) + .withColorTargetState(new ColorTargetState(ModRenderPipelines.ADDITIVE_BLEND)) .withShaderDefine("ALPHA_CUTOUT", 0.01F) .withDepthStencilState(new DepthStencilState(CompareOp.LESS_THAN_OR_EQUAL, false)) .withCull(false) @@ -151,15 +151,15 @@ public class ModRenderPipelines { @SubscribeEvent public static void on(RegisterRenderPipelinesEvent event) { - event.registerPipeline(LASER_TRANSLUCENT); - event.registerPipeline(LIGHTNING); - event.registerPipeline(SUPERNOVA_BEAM); - event.registerPipeline(STELLAR_BEAM); - event.registerPipeline(CORRUPTED_BEACON_BEAM); - event.registerPipeline(STAR_COLOR_OVERLAY); - event.registerPipeline(CELESTIAL_ATMOSPHERE); - event.registerPipeline(CELESTIAL_RING); - event.registerPipeline(SUPERNOVA_FLASH); - event.registerPipeline(GRAVITATIONAL_LENS); + event.registerPipeline(ModRenderPipelines.LASER_TRANSLUCENT); + event.registerPipeline(ModRenderPipelines.LIGHTNING); + event.registerPipeline(ModRenderPipelines.SUPERNOVA_BEAM); + event.registerPipeline(ModRenderPipelines.STELLAR_BEAM); + event.registerPipeline(ModRenderPipelines.CORRUPTED_BEACON_BEAM); + event.registerPipeline(ModRenderPipelines.STAR_COLOR_OVERLAY); + event.registerPipeline(ModRenderPipelines.CELESTIAL_ATMOSPHERE); + event.registerPipeline(ModRenderPipelines.CELESTIAL_RING); + event.registerPipeline(ModRenderPipelines.SUPERNOVA_FLASH); + event.registerPipeline(ModRenderPipelines.GRAVITATIONAL_LENS); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderTypes.java b/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderTypes.java index dd4598f289..f8f7971d54 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/init/ModRenderTypes.java @@ -25,7 +25,7 @@ public class ModRenderTypes { .createRenderSetup() ); - public static final RenderType LASER_TRANSLUCENT_BLOOM = ALRRenderTypeExtension.copyWithBloom(LASER_TRANSLUCENT); + public static final RenderType LASER_TRANSLUCENT_BLOOM = ALRRenderTypeExtension.copyWithBloom(ModRenderTypes.LASER_TRANSLUCENT); public static final RenderType LASER_SOLID = RenderType.create( "anvilcraft:laser_solid", @@ -72,7 +72,7 @@ public class ModRenderTypes { RenderSetup.builder(ModRenderPipelines.STAR_COLOR_OVERLAY) .useLightmap() .useOverlay() - .withTexture("Sampler0", WHITE_TEXTURE) + .withTexture("Sampler0", ModRenderTypes.WHITE_TEXTURE) .createRenderSetup() ); @@ -82,7 +82,7 @@ public class ModRenderTypes { .useLightmap() .useOverlay() .sortOnUpload() - .withTexture("Sampler0", WHITE_TEXTURE) + .withTexture("Sampler0", ModRenderTypes.WHITE_TEXTURE) .createRenderSetup() ); @@ -137,6 +137,6 @@ public class ModRenderTypes { ) ); - public static final RenderType CUTOUT_BLOCK = CUTOUT_NO_LIGHTING.apply(Sheets.BLOCKS_MAPPER.sheet()); - public static final RenderType TRANSLUCENT_BLOCK = TRANSLUCENT_NO_LIGHTING.apply(Sheets.BLOCKS_MAPPER.sheet()); + public static final RenderType CUTOUT_BLOCK = ModRenderTypes.CUTOUT_NO_LIGHTING.apply(Sheets.BLOCKS_MAPPER.sheet()); + public static final RenderType TRANSLUCENT_BLOCK = ModRenderTypes.TRANSLUCENT_NO_LIGHTING.apply(Sheets.BLOCKS_MAPPER.sheet()); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDAnvilCollisionCraftRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDAnvilCollisionCraftRecipeComponent.java index 2fc54a93fc..7f687cbc1d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDAnvilCollisionCraftRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDAnvilCollisionCraftRecipeComponent.java @@ -20,27 +20,27 @@ public class MDAnvilCollisionCraftRecipeComponent extends MDRecipeComponent { public static final int ANVIL_X = 30; public static final int ANVIL_Y = 50; - public static final int MOVING_ANVIL_X = ANVIL_X + 36; + public static final int MOVING_ANVIL_X = MDAnvilCollisionCraftRecipeComponent.ANVIL_X + 36; public static final int MOVING_ANVIL_X_DELTA = 3; - public static final int MOVING_ANVIL_Y = ANVIL_Y; + public static final int MOVING_ANVIL_Y = MDAnvilCollisionCraftRecipeComponent.ANVIL_Y; - public static final int HIT_BLOCK_X = MOVING_ANVIL_X + 24; - public static final int HIT_BLOCK_Y = MOVING_ANVIL_Y; - public static final int EXPLOSION_X = HIT_BLOCK_X - 6; - public static final int EXPLOSION_Y = HIT_BLOCK_Y - 8; + public static final int HIT_BLOCK_X = MDAnvilCollisionCraftRecipeComponent.MOVING_ANVIL_X + 24; + public static final int HIT_BLOCK_Y = MDAnvilCollisionCraftRecipeComponent.MOVING_ANVIL_Y; + public static final int EXPLOSION_X = MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_X - 6; + public static final int EXPLOSION_Y = MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_Y - 8; - public static final int OUTPUT_ITEM_X = HIT_BLOCK_X + 80; - public static final int OUTPUT_ITEM_Y = HIT_BLOCK_Y; - public static final int OUTPUT_ARROW_X = HIT_BLOCK_X + 24; - public static final int OUTPUT_ARROW_Y = HIT_BLOCK_Y - 8; + public static final int OUTPUT_ITEM_X = MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_X + 80; + public static final int OUTPUT_ITEM_Y = MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_Y; + public static final int OUTPUT_ARROW_X = MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_X + 24; + public static final int OUTPUT_ARROW_Y = MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_Y - 8; public static final int TRANSFORM_X = 160; - public static final int TRANSFORM_ARROW_X = TRANSFORM_X - 16; + public static final int TRANSFORM_ARROW_X = MDAnvilCollisionCraftRecipeComponent.TRANSFORM_X - 16; public static final int TRANSFORM_INPUT_Y = 26; - public static final int TRANSFORM_ARROW_Y = TRANSFORM_INPUT_Y + 16; - public static final int TRANSFORM_OUTPUT_Y = TRANSFORM_INPUT_Y + 54; - public static final int TRANSFORM_INFO_X = TRANSFORM_X - 16; - public static final int TRANSFORM_INFO_Y = TRANSFORM_OUTPUT_Y + 20; + public static final int TRANSFORM_ARROW_Y = MDAnvilCollisionCraftRecipeComponent.TRANSFORM_INPUT_Y + 16; + public static final int TRANSFORM_OUTPUT_Y = MDAnvilCollisionCraftRecipeComponent.TRANSFORM_INPUT_Y + 54; + public static final int TRANSFORM_INFO_X = MDAnvilCollisionCraftRecipeComponent.TRANSFORM_X - 16; + public static final int TRANSFORM_INFO_Y = MDAnvilCollisionCraftRecipeComponent.TRANSFORM_OUTPUT_Y + 20; public static final int INFO_X = 12; public static final int INFO_Y = 100; @@ -52,7 +52,7 @@ public class MDAnvilCollisionCraftRecipeComponent extends MDRecipeComponent { private final AnvilCollisionCraftRecipe recipe; public MDAnvilCollisionCraftRecipeComponent(AnvilCollisionCraftRecipe recipe, boolean enableAlignCenter) { - super(TEXTURE, 256, 128, enableAlignCenter); + super(MDAnvilCollisionCraftRecipeComponent.TEXTURE, 256, 128, enableAlignCenter); this.recipe = recipe; } @@ -62,27 +62,38 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f // 此配方需要的铁砧 Ingredient anvil = Ingredient.of(this.recipe.anvil().getBlocks().stream().map(Holder::value) ); - AgeratumUtil.renderItemWithoutSlot(context, anvil, mouseX, mouseY, ANVIL_X, ANVIL_Y); + AgeratumUtil.renderItemWithoutSlot( + context, anvil, mouseX, mouseY, MDAnvilCollisionCraftRecipeComponent.ANVIL_X, MDAnvilCollisionCraftRecipeComponent.ANVIL_Y); for (int i = 0; i < 7; i++) { GuiRenderExtras.itemWithTransparency( guiGraphics, new ItemStack(Blocks.ANVIL), - MOVING_ANVIL_X - i * MOVING_ANVIL_X_DELTA, - MOVING_ANVIL_Y, + MDAnvilCollisionCraftRecipeComponent.MOVING_ANVIL_X - i * MDAnvilCollisionCraftRecipeComponent.MOVING_ANVIL_X_DELTA, + MDAnvilCollisionCraftRecipeComponent.MOVING_ANVIL_Y, 1f - (float) i / 10 ); } // 被撞击的方块 Ingredient hitBlock = Ingredient.of(this.recipe.hitBlock().getBlocks().stream().map(Holder::value) ); - AgeratumUtil.renderItemWithoutSlot(context, hitBlock, mouseX, mouseY, HIT_BLOCK_X, HIT_BLOCK_Y); + AgeratumUtil.renderItemWithoutSlot( + context, hitBlock, mouseX, mouseY, MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_X, + MDAnvilCollisionCraftRecipeComponent.HIT_BLOCK_Y + ); - guiGraphics.blit(EXPLOSION, EXPLOSION_X, EXPLOSION_Y, 0, 0, 32, 32, 32, 32); + guiGraphics.blit( + MDAnvilCollisionCraftRecipeComponent.EXPLOSION, MDAnvilCollisionCraftRecipeComponent.EXPLOSION_X, + MDAnvilCollisionCraftRecipeComponent.EXPLOSION_Y, 0, 0, 32, 32, 32, 32 + ); // 输出物品 if (!this.recipe.outputItems().isEmpty()) { - AgeratumUtil.renderArrow(guiGraphics, OUTPUT_ARROW_X, OUTPUT_ARROW_Y); - AgeratumUtil.renderItems(context, this.recipe.outputItems(), mouseX, mouseY, OUTPUT_ITEM_X, OUTPUT_ITEM_Y); + AgeratumUtil.renderArrow( + guiGraphics, MDAnvilCollisionCraftRecipeComponent.OUTPUT_ARROW_X, MDAnvilCollisionCraftRecipeComponent.OUTPUT_ARROW_Y); + AgeratumUtil.renderItems( + context, this.recipe.outputItems(), mouseX, mouseY, MDAnvilCollisionCraftRecipeComponent.OUTPUT_ITEM_X, + MDAnvilCollisionCraftRecipeComponent.OUTPUT_ITEM_Y + ); } // 转换方块 @@ -90,13 +101,24 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f List blockTransforms = this.recipe.transformBlocks(); for (BlockTransform blockTransform : blockTransforms) { - AgeratumUtil.renderBlock(context, blockTransform.inputBlock(), mouseX, mouseY, TRANSFORM_X, TRANSFORM_INPUT_Y); - AgeratumUtil.renderArrow(guiGraphics, TRANSFORM_ARROW_X, TRANSFORM_ARROW_Y, 90); - AgeratumUtil.renderBlock(context, blockTransform.outputBlock(), mouseX, mouseY, TRANSFORM_X, TRANSFORM_OUTPUT_Y); + AgeratumUtil.renderBlock( + context, blockTransform.inputBlock(), mouseX, mouseY, + MDAnvilCollisionCraftRecipeComponent.TRANSFORM_X, + MDAnvilCollisionCraftRecipeComponent.TRANSFORM_INPUT_Y + ); + AgeratumUtil.renderArrow( + guiGraphics, MDAnvilCollisionCraftRecipeComponent.TRANSFORM_ARROW_X, + MDAnvilCollisionCraftRecipeComponent.TRANSFORM_ARROW_Y, 90 + ); + AgeratumUtil.renderBlock( + context, blockTransform.outputBlock(), mouseX, mouseY, + MDAnvilCollisionCraftRecipeComponent.TRANSFORM_X, + MDAnvilCollisionCraftRecipeComponent.TRANSFORM_OUTPUT_Y + ); AgeratumUtil.renderText( guiGraphics, Component.translatable("gui.anvilcraft.category.anvil_collision.maxcount", blockTransform.maxCount()), - TRANSFORM_INFO_X, TRANSFORM_INFO_Y + MDAnvilCollisionCraftRecipeComponent.TRANSFORM_INFO_X, MDAnvilCollisionCraftRecipeComponent.TRANSFORM_INFO_Y ); } } @@ -104,13 +126,14 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f AgeratumUtil.renderText( guiGraphics, Component.translatable("gui.anvilcraft.category.anvil_collision.consume", this.recipe.consume()), - INFO_X, INFO_Y + MDAnvilCollisionCraftRecipeComponent.INFO_X, MDAnvilCollisionCraftRecipeComponent.INFO_Y ); AgeratumUtil.renderText( guiGraphics, Component.translatable("gui.anvilcraft.category.anvil_collision.speed", this.recipe.speed()), - INFO_X, INFO_Y + INFO_Y_OFFSET + MDAnvilCollisionCraftRecipeComponent.INFO_X, + MDAnvilCollisionCraftRecipeComponent.INFO_Y + MDAnvilCollisionCraftRecipeComponent.INFO_Y_OFFSET ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDChargerChargingRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDChargerChargingRecipeComponent.java index 5e79bd93a8..5f819c3511 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDChargerChargingRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDChargerChargingRecipeComponent.java @@ -15,14 +15,14 @@ public class MDChargerChargingRecipeComponent extends MDRecipeComponent { public static final Identifier TEXTURE = AnvilCraft.of("textures/gui/ageratum/128back.png"); public static final String KEY_CATEGORY = "gui.anvilcraft.category.charger_charging"; - public static final String KEY_POWER_CONSUME = KEY_CATEGORY + ".power_consume"; - public static final String KEY_POWER_PRODUCE = KEY_CATEGORY + ".power_produce"; - public static final String KEY_TIME = KEY_CATEGORY + ".time"; + public static final String KEY_POWER_CONSUME = MDChargerChargingRecipeComponent.KEY_CATEGORY + ".power_consume"; + public static final String KEY_POWER_PRODUCE = MDChargerChargingRecipeComponent.KEY_CATEGORY + ".power_produce"; + public static final String KEY_TIME = MDChargerChargingRecipeComponent.KEY_CATEGORY + ".time"; private final ChargerChargingRecipe recipe; public MDChargerChargingRecipeComponent(ChargerChargingRecipe recipe, boolean enableAlignCenter) { - super(TEXTURE, 128, 64, enableAlignCenter); + super(MDChargerChargingRecipeComponent.TEXTURE, 128, 64, enableAlignCenter); this.recipe = recipe; } @@ -37,11 +37,12 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f BlockState charger = this.recipe.getProcessingBlock().defaultBlockState().setValue(ChargerBlock.OVERLOAD, false); AgeratumUtil.renderBlock(context, charger, mouseX, mouseY, 24, 28); - String keyPower = this.recipe.power() < 0 ? KEY_POWER_CONSUME : KEY_POWER_PRODUCE; + String keyPower = this.recipe.power() < 0 ? MDChargerChargingRecipeComponent.KEY_POWER_CONSUME + : MDChargerChargingRecipeComponent.KEY_POWER_PRODUCE; Component power = Component.translatable(keyPower, Math.abs(this.recipe.power())); AgeratumUtil.renderText(graphics, power, 10, 8); - Component time = Component.translatable(KEY_TIME, 0.05 * this.recipe.power()); + Component time = Component.translatable(MDChargerChargingRecipeComponent.KEY_TIME, 0.05 * this.recipe.power()); AgeratumUtil.renderText(graphics, time, 10, 48); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDEnergyWeaponMakeRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDEnergyWeaponMakeRecipeComponent.java index cd2b28927b..ba04048d39 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDEnergyWeaponMakeRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDEnergyWeaponMakeRecipeComponent.java @@ -14,7 +14,7 @@ public class MDEnergyWeaponMakeRecipeComponent extends MDRecipeComponent { private final EnergyWeaponMakeRecipe recipe; public MDEnergyWeaponMakeRecipeComponent(EnergyWeaponMakeRecipe recipe, boolean enableAlignCenter) { - super(TEXTURE, 128, 64, enableAlignCenter); + super(MDEnergyWeaponMakeRecipeComponent.TEXTURE, 128, 64, enableAlignCenter); this.recipe = recipe; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDJewelCraftingRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDJewelCraftingRecipeComponent.java index b0b97bb9b4..99fabd2d34 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDJewelCraftingRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDJewelCraftingRecipeComponent.java @@ -17,7 +17,7 @@ public class MDJewelCraftingRecipeComponent extends MDRecipeComponent { private final List ingredients; public MDJewelCraftingRecipeComponent(JewelCraftingRecipe recipe, boolean enableAlignCenter) { - super(TEXTURE, 142, 62, enableAlignCenter); + super(MDJewelCraftingRecipeComponent.TEXTURE, 142, 62, enableAlignCenter); this.result = recipe.source(); this.ingredients = recipe.ingredients(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDPortalConversionRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDPortalConversionRecipeComponent.java index ff99b2beec..6afbca9a00 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDPortalConversionRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/MDPortalConversionRecipeComponent.java @@ -18,7 +18,7 @@ public class MDPortalConversionRecipeComponent extends MDRecipeComponent { private final PortalConversionRecipe recipe; public MDPortalConversionRecipeComponent(PortalConversionRecipe recipe, boolean enableAlignCenter) { - super(TEXTURE, 128, 64, enableAlignCenter); + super(MDPortalConversionRecipeComponent.TEXTURE, 128, 64, enableAlignCenter); this.recipe = recipe; } @@ -33,7 +33,10 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f if (AgeratumUtil.isHover(0, 0, 128, 64, mouseX, mouseY)) { if (context.tooltips().isEmpty()) { context.tooltips().add(new MDRenderContext.Tooltip( - List.of(Component.translatable(FALL_THROUGH, this.recipe.getPortalType().getPortalName())), Optional.empty() + List.of(Component.translatable( + MDPortalConversionRecipeComponent.FALL_THROUGH, + this.recipe.getPortalType().getPortalName() + )), Optional.empty() )); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBaseAnvilRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBaseAnvilRecipeComponent.java index f286904557..3b578ca214 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBaseAnvilRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBaseAnvilRecipeComponent.java @@ -21,7 +21,7 @@ public abstract class MDBaseAnvilRecipeComponent extends MDRecipeComponent { public static final int OUTPUT_BLOCK_X = 210; public MDBaseAnvilRecipeComponent(boolean enableAlignCenter) { - super(TEXTURE, 256, 128, enableAlignCenter); + super(MDBaseAnvilRecipeComponent.TEXTURE, 256, 128, enableAlignCenter); } protected List getIngredients() { @@ -53,14 +53,15 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f } // 渲染加工环境方块 - int anvilY = BLOCK_Y - 2 * AgeratumUtil.BLOCK_SIZE; - AgeratumUtil.renderBlock(context, Blocks.ANVIL.defaultBlockState(), mouseX, mouseY, INPUT_BLOCK_X, anvilY); + int anvilY = MDBaseAnvilRecipeComponent.BLOCK_Y - 2 * AgeratumUtil.BLOCK_SIZE; + AgeratumUtil.renderBlock( + context, Blocks.ANVIL.defaultBlockState(), mouseX, mouseY, MDBaseAnvilRecipeComponent.INPUT_BLOCK_X, anvilY); for (int i = 0; i < this.getInputBlockStates().size(); i++) { BlockState inputBlock = this.getInputBlockStates().get(i); if (inputBlock.isAir()) continue; - int y = AgeratumUtil.getRenderY(BLOCK_Y, i); - AgeratumUtil.renderBlock(context, inputBlock, mouseX, mouseY, INPUT_BLOCK_X, y); + int y = AgeratumUtil.getRenderY(MDBaseAnvilRecipeComponent.BLOCK_Y, i); + AgeratumUtil.renderBlock(context, inputBlock, mouseX, mouseY, MDBaseAnvilRecipeComponent.INPUT_BLOCK_X, y); } // 渲染输出箭头 @@ -71,7 +72,9 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f // 渲染输出方块(如果有) if (!this.getOutputBlockState().isEmpty() && !this.getOutputBlockState().isAir()) { - AgeratumUtil.renderBlock(context, this.getOutputBlockState(), mouseX, mouseY, OUTPUT_BLOCK_X, BLOCK_Y); + AgeratumUtil.renderBlock(context, this.getOutputBlockState(), mouseX, mouseY, MDBaseAnvilRecipeComponent.OUTPUT_BLOCK_X, + MDBaseAnvilRecipeComponent.BLOCK_Y + ); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCompressRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCompressRecipeComponent.java index 19ca9233fc..f1f3599473 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCompressRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCompressRecipeComponent.java @@ -29,7 +29,10 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f List states = this.inputBlocks.get(i).constructStatesForRender(); if (!states.isEmpty()) { BlockState blockState = states.get(RecipeUtil.getDisplayIndex(states.size())); - AgeratumUtil.renderBlock(context, blockState, mouseX, mouseY, INPUT_BLOCK_X, AgeratumUtil.getRenderY(BLOCK_Y, i)); + AgeratumUtil.renderBlock( + context, blockState, mouseX, mouseY, MDBaseAnvilRecipeComponent.INPUT_BLOCK_X, AgeratumUtil.getRenderY( + MDBaseAnvilRecipeComponent.BLOCK_Y, i) + ); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCrushRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCrushRecipeComponent.java index 6d26bae3f2..c7d7af5432 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCrushRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDBlockCrushRecipeComponent.java @@ -28,7 +28,10 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f List states = this.inputBlocks.get(i).constructStatesForRender(); if (!states.isEmpty()) { BlockState blockState = states.get(RecipeUtil.getDisplayIndex(states.size())); - AgeratumUtil.renderBlock(context, blockState, mouseX, mouseY, INPUT_BLOCK_X, BLOCK_Y + i * AgeratumUtil.BLOCK_SIZE); + AgeratumUtil.renderBlock( + context, blockState, mouseX, mouseY, MDBaseAnvilRecipeComponent.INPUT_BLOCK_X, MDBaseAnvilRecipeComponent.BLOCK_Y + + i * AgeratumUtil.BLOCK_SIZE + ); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDItemInjectRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDItemInjectRecipeComponent.java index ddb11b1362..fa4beca792 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDItemInjectRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDItemInjectRecipeComponent.java @@ -41,7 +41,8 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f List states = this.inputBlock.constructStatesForRender(); if (!states.isEmpty()) { BlockState blockState = states.get(RecipeUtil.getDisplayIndex(states.size())); - AgeratumUtil.renderBlock(context, blockState, mouseX, mouseY, INPUT_BLOCK_X, BLOCK_Y); + AgeratumUtil.renderBlock( + context, blockState, mouseX, mouseY, MDBaseAnvilRecipeComponent.INPUT_BLOCK_X, MDBaseAnvilRecipeComponent.BLOCK_Y); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSolidLiquidRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSolidLiquidRecipeComponent.java index 0dfe1c2d45..03ea1d78d8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSolidLiquidRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSolidLiquidRecipeComponent.java @@ -31,14 +31,14 @@ public MDSolidLiquidRecipeComponent(SolidLiquidRecipe recipe, boolean enableAlig this.ingredients = recipe.getInputItems(); this.resultItems = recipe.getResultItems(); this.inputBlockStates = List.of( - getInputCauldron(recipe) + MDSolidLiquidRecipeComponent.getInputCauldron(recipe) ); this.recipe = recipe; } protected BlockState getOutputBlockState() { if (this.resultItems == null || this.resultItems.isEmpty()) { - return getResultCauldron(this.recipe); + return MDSolidLiquidRecipeComponent.getResultCauldron(this.recipe); } return super.getOutputBlockState(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSqueezingRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSqueezingRecipeComponent.java index 206d27912a..4b59071089 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSqueezingRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSqueezingRecipeComponent.java @@ -29,9 +29,10 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f List states = this.inputBlocks.getFirst().constructStatesForRender(); if (!states.isEmpty()) { BlockState blockState = states.get(RecipeUtil.getDisplayIndex(states.size())); - AgeratumUtil.renderBlock(context, blockState, mouseX, mouseY, INPUT_BLOCK_X, BLOCK_Y); + AgeratumUtil.renderBlock( + context, blockState, mouseX, mouseY, MDBaseAnvilRecipeComponent.INPUT_BLOCK_X, MDBaseAnvilRecipeComponent.BLOCK_Y); } - int y = AgeratumUtil.getRenderY(BLOCK_Y, 1); - AgeratumUtil.renderBlock(context, Blocks.CAULDRON.defaultBlockState(), mouseX, mouseY, INPUT_BLOCK_X, y); + int y = AgeratumUtil.getRenderY(MDBaseAnvilRecipeComponent.BLOCK_Y, 1); + AgeratumUtil.renderBlock(context, Blocks.CAULDRON.defaultBlockState(), mouseX, mouseY, MDBaseAnvilRecipeComponent.INPUT_BLOCK_X, y); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSuperHeatingRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSuperHeatingRecipeComponent.java index 015420d881..9806ba6c1c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSuperHeatingRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDSuperHeatingRecipeComponent.java @@ -29,7 +29,7 @@ public MDSuperHeatingRecipeComponent(SuperHeatingRecipe recipe, boolean enableAl this.ingredients = recipe.getInputItems(); this.resultItems = recipe.getResultItems(); this.inputBlockStates = List.of( - getInputCauldron(recipe), + MDSuperHeatingRecipeComponent.getInputCauldron(recipe), ModBlocks.HEATER.getDefaultState().setValue(HeaterBlock.OVERLOAD, false) ); this.recipe = recipe; @@ -38,7 +38,7 @@ public MDSuperHeatingRecipeComponent(SuperHeatingRecipe recipe, boolean enableAl @Override protected BlockState getOutputBlockState() { if (this.resultItems.isEmpty()) { - return getResultCauldron(this.recipe); + return MDSuperHeatingRecipeComponent.getResultCauldron(this.recipe); } return super.getOutputBlockState(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDTimeWarpRecipeComponent.java b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDTimeWarpRecipeComponent.java index 8b17a52ad3..4dac0244d1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDTimeWarpRecipeComponent.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/markdown/recipe/anvil/MDTimeWarpRecipeComponent.java @@ -35,7 +35,7 @@ public MDTimeWarpRecipeComponent(TimeWarpRecipe recipe, boolean enableAlignCente this.ingredients = recipe.getInputItems(); this.resultItems = recipe.getResultItems(); this.inputBlockStates = List.of( - getInputCauldron(recipe), + MDTimeWarpRecipeComponent.getInputCauldron(recipe), ModBlocks.CORRUPTED_BEACON.getDefaultState() ); this.recipe = recipe; @@ -43,7 +43,7 @@ public MDTimeWarpRecipeComponent(TimeWarpRecipe recipe, boolean enableAlignCente protected BlockState getOutputBlockState() { if (this.resultItems.isEmpty()) { - return getResultCauldron(this.recipe); + return MDTimeWarpRecipeComponent.getResultCauldron(this.recipe); } return super.getOutputBlockState(); } @@ -59,14 +59,14 @@ protected void extractRecipeRenderState(MDRenderContext context, float mouseX, f this.recipe.getHasCauldron().consume(), this.recipe.getHasCauldron().getFluidCauldron().getName() ); - AgeratumUtil.renderText(graphics, text, INFO_X, INFO_Y); + AgeratumUtil.renderText(graphics, text, MDTimeWarpRecipeComponent.INFO_X, MDTimeWarpRecipeComponent.INFO_Y); } else if (this.recipe.isProduceFluid()) { Component text = Component.translatable( "gui.anvilcraft.category.time_warp.produce_fluid", this.recipe.getHasCauldron().produce(), this.recipe.getHasCauldron().getTransformCauldron().getName() ); - AgeratumUtil.renderText(graphics, text, INFO_X, INFO_Y); + AgeratumUtil.renderText(graphics, text, MDTimeWarpRecipeComponent.INFO_X, MDTimeWarpRecipeComponent.INFO_Y); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/RenderState.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/RenderState.java index decd87a018..75c7d49990 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/RenderState.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/RenderState.java @@ -16,15 +16,15 @@ public class RenderState { } public static boolean isIrisPresent() { - return IRIS_PRESENT; + return RenderState.IRIS_PRESENT; } public static void bloomStage() { - bloomRenderStage = true; + RenderState.bloomRenderStage = true; } public static void levelStage() { - bloomRenderStage = false; + RenderState.bloomRenderStage = false; } public static boolean isEnhancedRenderingAvailable() { @@ -36,6 +36,6 @@ public static boolean isBloomEffectEnabled() { } public static boolean isLensEffectEnabled() { - return isEnhancedRenderingAvailable() && AnvilCraftClient.CONFIG.gravitationalLens.renderBlackHoleLensing; + return RenderState.isEnhancedRenderingAvailable() && AnvilCraftClient.CONFIG.gravitationalLens.renderBlackHoleLensing; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/BaseFluidHandlerHolderRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/BaseFluidHandlerHolderRenderer.java index 786e968f76..e0412f0c9c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/BaseFluidHandlerHolderRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/BaseFluidHandlerHolderRenderer.java @@ -84,7 +84,7 @@ public void submit(S state, PoseStack poseStack, SubmitNodeCollector submitNodeC float maxY = minY + (state.getMaxY() - minY) * state.getFill(); submitNodeCollector.submitCustomGeometry( poseStack, - FLUID_RENDER_TYPE, + BaseFluidHandlerHolderRenderer.FLUID_RENDER_TYPE, (pose, buffer) -> FluidRenderHelper.INSTANCE.renderFluidBox( sprite, resource, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ChargeCollectorRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ChargeCollectorRenderer.java index 12f722b8bc..46460548e8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ChargeCollectorRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ChargeCollectorRenderer.java @@ -31,6 +31,6 @@ protected float rotation(ChargeCollectorBlockEntity be, float partialTick) { @Override protected StandaloneModelKey getModel() { - return HEAD; + return ChargeCollectorRenderer.HEAD; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ControlValveBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ControlValveBlockEntityRenderer.java index 63bd1dd3b3..2838c68ee4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ControlValveBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/ControlValveBlockEntityRenderer.java @@ -78,7 +78,7 @@ public void extractRenderState( state.setFacing(be.getFacing()); state.setAxis(blockState.getValue(ControlValveBlock.AXIS)); state.setMaxRate(be.getMaxRate()); - state.setHandwheel(FeatureRendererSupport.initialize(HANDWHEEL, be)); + state.setHandwheel(FeatureRendererSupport.initialize(ControlValveBlockEntityRenderer.HANDWHEEL, be)); FluidStack filter = be.getFilter(0); state.setFilterResource(filter.isEmpty() ? null : FluidResource.of(filter)); @@ -108,7 +108,7 @@ private void submitHandwheel( if (handwheel == null) return; float ratio = (ControlValveBlockEntity.MAX_RATE - state.getMaxRate()) / (float) ControlValveBlockEntity.MAX_RATE; - float spinDeg = BASE_ANGLE_DEG - 90.0f * ratio; + float spinDeg = ControlValveBlockEntityRenderer.BASE_ANGLE_DEG - 90.0f * ratio; Direction facing = state.getFacing(); Direction.Axis axis = state.getAxis(); if (axis == Direction.Axis.Z || (axis == Direction.Axis.Y && facing.getAxis() == Direction.Axis.Z)) { @@ -117,7 +117,7 @@ private void submitHandwheel( poseStack.pushPose(); poseStack.translate(0.5, 0.5, 0.5); - applyUpToFacing(poseStack, facing); + ControlValveBlockEntityRenderer.applyUpToFacing(poseStack, facing); poseStack.mulPose(Axis.YP.rotationDegrees(spinDeg)); poseStack.translate(-0.5, -0.5, -0.5); handwheel.submit( @@ -147,8 +147,8 @@ private void submitFluidIndicators( TextureAtlasSprite sprite = model.stillMaterial().sprite(); int tintColor = tintSource.colorAsStack(resource.toStack(1)); - float h = INDICATOR_HALF; - float y = INDICATOR_DEPTH; + float h = ControlValveBlockEntityRenderer.INDICATOR_HALF; + float y = ControlValveBlockEntityRenderer.INDICATOR_DEPTH; for (Direction side : Direction.values()) { if (side.getAxis() == state.getAxis() || side == state.getFacing()) { continue; @@ -156,10 +156,10 @@ private void submitFluidIndicators( poseStack.pushPose(); poseStack.translate(0.5, 0.5, 0.5); - applyUpToFacing(poseStack, side); + ControlValveBlockEntityRenderer.applyUpToFacing(poseStack, side); submitNodeCollector.submitCustomGeometry( poseStack, - FLUID_RENDER_TYPE, + ControlValveBlockEntityRenderer.FLUID_RENDER_TYPE, (pose, buffer) -> FluidRenderHelper.INSTANCE.renderFluidBox( sprite, resource, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CorruptedBeaconRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CorruptedBeaconRenderer.java index f1e8637c0a..ab9e58502f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CorruptedBeaconRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CorruptedBeaconRenderer.java @@ -54,7 +54,7 @@ public void extractRenderState( state.setLit(lit); int beamTopY = be.getBeamHeight(); int posY = be.getBlockPos().getY(); - state.setBeamHeight((float) (beamTopY - posY) - BEAM_BASE_Y); + state.setBeamHeight((float) (beamTopY - posY) - CorruptedBeaconRenderer.BEAM_BASE_Y); } @Override @@ -70,16 +70,16 @@ public void submit( collector.submitCustomGeometry( pose, ModRenderTypes.CORRUPTED_BEACON_BEAM, - (last, consumer) -> emitBeaconBeam(consumer, last.pose(), beamHeight) + (last, consumer) -> CorruptedBeaconRenderer.emitBeaconBeam(consumer, last.pose(), beamHeight) ); } public static void renderWeaponBeam(VertexConsumer consumer, Matrix4f matrix, float length) { - for (int layer = BEAM_GLOW_LAYERS; layer >= 1; layer--) { - float half = BEAM_INNER_HALF + BEAM_GLOW_HALF_STEP * layer * 0.5F; + for (int layer = CorruptedBeaconRenderer.BEAM_GLOW_LAYERS; layer >= 1; layer--) { + float half = CorruptedBeaconRenderer.BEAM_INNER_HALF + CorruptedBeaconRenderer.BEAM_GLOW_HALF_STEP * layer * 0.5F; float falloff = 1.0F / (layer + 1); float alpha = 0.65F * falloff; - emitBeamPyramid( + CorruptedBeaconRenderer.emitBeamPyramid( consumer, matrix, 0.0F, @@ -87,56 +87,56 @@ public static void renderWeaponBeam(VertexConsumer consumer, Matrix4f matrix, fl 0.0F, half, length, - GLOW_R, - GLOW_G, - GLOW_B, + CorruptedBeaconRenderer.GLOW_R, + CorruptedBeaconRenderer.GLOW_G, + CorruptedBeaconRenderer.GLOW_B, alpha, 0.24F * falloff ); } - emitBeamPyramid( + CorruptedBeaconRenderer.emitBeamPyramid( consumer, matrix, 0.0F, 0.0F, 0.0F, - BEAM_INNER_HALF, + CorruptedBeaconRenderer.BEAM_INNER_HALF, length, - CORE_R, - CORE_G, - CORE_B, + CorruptedBeaconRenderer.CORE_R, + CorruptedBeaconRenderer.CORE_G, + CorruptedBeaconRenderer.CORE_B, 0.94F, 0.22F ); } private static void emitBeaconBeam(VertexConsumer consumer, Matrix4f matrix, float beamHeight) { - float apexY = BEAM_BASE_Y + beamHeight; - for (int layer = BEAM_GLOW_LAYERS; layer >= 1; layer--) { - float half = BEAM_INNER_HALF + BEAM_GLOW_HALF_STEP * layer; + float apexY = CorruptedBeaconRenderer.BEAM_BASE_Y + beamHeight; + for (int layer = CorruptedBeaconRenderer.BEAM_GLOW_LAYERS; layer >= 1; layer--) { + float half = CorruptedBeaconRenderer.BEAM_INNER_HALF + CorruptedBeaconRenderer.BEAM_GLOW_HALF_STEP * layer; float falloff = 1.0f / (layer + 1); float alpha = 0.65f * falloff; float tipFade = 0.24f * falloff; - emitBeamPyramid( + CorruptedBeaconRenderer.emitBeamPyramid( consumer, matrix, half, apexY, - GLOW_R, - GLOW_G, - GLOW_B, + CorruptedBeaconRenderer.GLOW_R, + CorruptedBeaconRenderer.GLOW_G, + CorruptedBeaconRenderer.GLOW_B, alpha, tipFade ); } - emitBeamPyramid( + CorruptedBeaconRenderer.emitBeamPyramid( consumer, matrix, - BEAM_INNER_HALF, + CorruptedBeaconRenderer.BEAM_INNER_HALF, apexY, - CORE_R, - CORE_G, - CORE_B, + CorruptedBeaconRenderer.CORE_R, + CorruptedBeaconRenderer.CORE_G, + CorruptedBeaconRenderer.CORE_B, 0.94f, 0.22f ); @@ -153,11 +153,11 @@ private static void emitBeamPyramid( float alpha, float tipFade ) { - emitBeamPyramid( + CorruptedBeaconRenderer.emitBeamPyramid( vc, matrix, 0.5F, - BEAM_BASE_Y, + CorruptedBeaconRenderer.BEAM_BASE_Y, 0.5F, halfWidth, apexY, @@ -195,9 +195,9 @@ private static void emitBeamPyramid( for (int i = 0; i < 4; i++) { float[] c0 = corners[i]; float[] c1 = corners[(i + 1) % 4]; - beamVertex(vc, matrix, c0[0], baseY, c0[1], red, green, blue, alpha); - beamVertex(vc, matrix, c1[0], baseY, c1[1], red, green, blue, alpha); - beamVertex(vc, matrix, cx, apexY, cz, red, green, blue, tipAlpha); + CorruptedBeaconRenderer.beamVertex(vc, matrix, c0[0], baseY, c0[1], red, green, blue, alpha); + CorruptedBeaconRenderer.beamVertex(vc, matrix, c1[0], baseY, c1[1], red, green, blue, alpha); + CorruptedBeaconRenderer.beamVertex(vc, matrix, cx, apexY, cz, red, green, blue, tipAlpha); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeCrateRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeCrateRenderer.java index b04ecb7698..6152f5124d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeCrateRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeCrateRenderer.java @@ -39,6 +39,7 @@ public void extractRenderState( ) { BlockEntityRenderer.super.extractRenderState(be, state, partialTicks, cameraPosition, breakProgress); ItemStack stack = be.getDisplayStack(); + state.setItem(null); if (!stack.isEmpty()) { ItemClusterRenderState cluster = new ItemClusterRenderState(); cluster.seed = ItemClusterRenderState.getSeedForItemStack(stack); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeFluidTankRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeFluidTankRenderer.java index 4444a3ebf2..3daf6e8de7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeFluidTankRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeFluidTankRenderer.java @@ -26,6 +26,6 @@ protected void updateTankW( Vec3 cameraPosition, ModelFeatureRenderer.@Nullable CrumblingOverlay breakProgress ) { - state.setTankW(TANK_W); + state.setTankW(CreativeFluidTankRenderer.TANK_W); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeGeneratorRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeGeneratorRenderer.java index 447e56ae29..ec54a909e2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeGeneratorRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/CreativeGeneratorRenderer.java @@ -31,6 +31,6 @@ protected float elevation() { @Override protected StandaloneModelKey getModel() { - return HEAD; + return CreativeGeneratorRenderer.HEAD; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DischargerRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DischargerRenderer.java index 43b47240ef..220bc578ae 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DischargerRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DischargerRenderer.java @@ -37,6 +37,7 @@ public void submit( CameraRenderState camera ) { ItemClusterRenderState cluster = state.getDisplayState(); + if (cluster == null) return; ItemStackRenderState item = cluster.item; AABB aabb = item.getModelBoundingBox(); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DrainBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DrainBlockEntityRenderer.java index e7de05ffbd..32ae6fc461 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DrainBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/DrainBlockEntityRenderer.java @@ -38,7 +38,7 @@ protected void updateTankW( Vec3 cameraPosition, ModelFeatureRenderer.@Nullable CrumblingOverlay breakProgress ) { - state.setTankW(TANK_W); + state.setTankW(DrainBlockEntityRenderer.TANK_W); int bottomY = be.getColumnBottomY(); if (bottomY != Integer.MIN_VALUE) { state.setColumnMinY(bottomY - be.getBlockPos().getY()); @@ -66,16 +66,16 @@ public void submit( TextureAtlasSprite flowing = model.flowingMaterial().sprite(); submitNodeCollector.submitCustomGeometry( poseStack, - FLUID_RENDER_TYPE, + BaseFluidHandlerHolderRenderer.FLUID_RENDER_TYPE, (pose, buffer) -> FluidRenderHelper.INSTANCE.renderFluidBox( flowing, resource, - COLUMN_INSET, + DrainBlockEntityRenderer.COLUMN_INSET, minY, - COLUMN_INSET, - 1 - COLUMN_INSET, + DrainBlockEntityRenderer.COLUMN_INSET, + 1 - DrainBlockEntityRenderer.COLUMN_INSET, 0, - 1 - COLUMN_INSET, + 1 - DrainBlockEntityRenderer.COLUMN_INSET, tintColor, buffer, pose, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FeCollectorRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FeCollectorRenderer.java index a1984cd0d0..d534f5d727 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FeCollectorRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FeCollectorRenderer.java @@ -22,7 +22,7 @@ public PowerGeneratorRenderState createRenderState() { @Override protected StandaloneModelKey getModel() { - return MODEL; + return FeCollectorRenderer.MODEL; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FishTankRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FishTankRenderer.java index a03425a5d3..5129bf22a6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FishTankRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FishTankRenderer.java @@ -68,7 +68,7 @@ protected void updateTankW( Vec3 cameraPosition, ModelFeatureRenderer.@Nullable CrumblingOverlay breakProgress ) { - state.setTankW(TANK_W); + state.setTankW(FishTankRenderer.TANK_W); } @Override @@ -93,7 +93,7 @@ public void extractRenderState( if (be.isEmptyOfFish()) return; List fishData = be.getFishes(); - int newDataHash = computeFishDataHash(fishData); + int newDataHash = FishTankRenderer.computeFishDataHash(fishData); long cacheKey = be.getBlockPos().asLong(); // Get or create cache entry @@ -102,7 +102,7 @@ public void extractRenderState( // Rebuild cache if it doesn't exist or data has changed if (cacheEntry == null || cacheEntry.dataHash != newDataHash) { - cachedFishes = createTropicalFishEntities(level, fishData); + cachedFishes = FishTankRenderer.createTropicalFishEntities(level, fishData); this.fishCache.put(cacheKey, new FishCacheEntry(cachedFishes, newDataHash)); } else { cachedFishes = cacheEntry.cachedFishes; @@ -126,7 +126,7 @@ public void submit(FishTankRenderState state, PoseStack pose, SubmitNodeCollecto if (state.getFill() != 0) { pose.translate(0, (state.getMaxY() - state.getMinY()) * (state.getFill() - 1), 0); } else { - pose.translate(0, TANK_W - 1, 0); + pose.translate(0, FishTankRenderer.TANK_W - 1, 0); } state.getFire().submit( pose, @@ -165,11 +165,11 @@ private static void submitItemsInTank( final float randomOffsetDeg = random.nextIntBetweenInclusive(0, 50) - 25; pose.pushPose(); - pose.translate(0.5F, TANK_W, 0.5F); + pose.translate(0.5F, FishTankRenderer.TANK_W, 0.5F); pose.mulPose(Axis.YP.rotationDegrees(randomOffsetDeg)); int itemCount = items.size(); - float y = Mth.clamp(fill - TANK_W - 1 / 8F, TANK_W, 1 - TANK_W - 1 / 8F); + float y = Mth.clamp(fill - FishTankRenderer.TANK_W - 1 / 8F, FishTankRenderer.TANK_W, 1 - FishTankRenderer.TANK_W - 1 / 8F); float partAngleDeg = 360F / itemCount; Vec3 vec = itemCount == 1 ? new Vec3(0, y, 0) : new Vec3(0.125, y, 0); for (Pair entry : items) { @@ -227,7 +227,7 @@ private static void submitFishesInTank( CameraRenderState camera ) { List fishes = state.getFishes(); - float height = 1 - 2 * TANK_W; + float height = 1 - 2 * FishTankRenderer.TANK_W; int count = fishes.size(); for (int i = 0; i < count; i++) { @@ -239,7 +239,7 @@ private static void submitFishesInTank( float x = 0.5F + Mth.cos(angle) * radius; float z = 0.5F + Mth.sin(angle) * radius; - float y = TANK_W + height * (0.5F + Mth.sin(ticks * 0.07F + i) * 0.07F + Mth.sin(ticks * 0.19F + i) * 0.19F); + float y = FishTankRenderer.TANK_W + height * (0.5F + Mth.sin(ticks * 0.07F + i) * 0.07F + Mth.sin(ticks * 0.19F + i) * 0.19F); float yawDeg = -(angle * Mth.RAD_TO_DEG); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FluidTankRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FluidTankRenderer.java index 9977d080f0..56ddc82274 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FluidTankRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/FluidTankRenderer.java @@ -41,6 +41,6 @@ protected void updateTankW( Vec3 cameraPosition, ModelFeatureRenderer.@Nullable CrumblingOverlay breakProgress ) { - state.setTankW(TANK_W); + state.setTankW(FluidTankRenderer.TANK_W); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HasMobBlockRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HasMobBlockRenderer.java index 3023eb80fc..c6b6273468 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HasMobBlockRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HasMobBlockRenderer.java @@ -48,10 +48,19 @@ public void extractRenderState( ModelFeatureRenderer.@Nullable CrumblingOverlay breakProgress ) { BlockEntityRenderer.super.extractRenderState(be, state, partialTicks, cameraPosition, breakProgress); - Entity entity = be.getOrCreateDisplayEntity(be.getLevel()); - if (entity == null) return; - state.setMob(new EntityRenderState()); - this.extractEntityState(entity, state.getMob(), partialTicks); + Level level = be.getLevel(); + if (level == null) { + state.setMob(null); + return; + } + Entity entity = be.getOrCreateDisplayEntity(level); + if (entity == null) { + state.setMob(null); + return; + } + EntityRenderState mob = new EntityRenderState(); + state.setMob(mob); + this.extractEntityState(entity, mob, partialTicks); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeatCollectorRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeatCollectorRenderer.java index 33eb42fc72..e00a040b5b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeatCollectorRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeatCollectorRenderer.java @@ -31,6 +31,6 @@ protected float rotation(HeatCollectorBlockEntity blockEntity, float partialTick @Override protected StandaloneModelKey getModel() { - return HEAD; + return HeatCollectorRenderer.HEAD; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeliostatsRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeliostatsRenderer.java index e9db4b906e..fe84c39969 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeliostatsRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/HeliostatsRenderer.java @@ -75,7 +75,7 @@ private StandaloneModelKey getHeadModel(HeliostatsBlockEntity b .filter(be -> be.getLevel() != null) .map(be -> be.getLevel().getBiome(be.getBlockPos())) .map(biome -> biome.is(Biomes.SUNFLOWER_PLAINS)) - .orElse(false) ? HEAD_SUNFLOWER : HEAD; + .orElse(false) ? HeliostatsRenderer.HEAD_SUNFLOWER : HeliostatsRenderer.HEAD; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/IncandescentBlockRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/IncandescentBlockRenderer.java index 6e20df596e..6f8cd97dfe 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/IncandescentBlockRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/IncandescentBlockRenderer.java @@ -57,7 +57,8 @@ public void submit( state.blockPos.getZ() - camera.pos.z ); bloomPose.translate(0.5F, 0.5F, 0.5F); - bloomPose.scale(BLOOM_SCALE, BLOOM_SCALE, BLOOM_SCALE); + bloomPose.scale( + IncandescentBlockRenderer.BLOOM_SCALE, IncandescentBlockRenderer.BLOOM_SCALE, IncandescentBlockRenderer.BLOOM_SCALE); bloomPose.translate(-0.5F, -0.5F, -0.5F); state.getModel().submit( bloomPose, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/InfiniteCollectorRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/InfiniteCollectorRenderer.java index f7a9312702..d3ab70fc41 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/InfiniteCollectorRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/InfiniteCollectorRenderer.java @@ -21,7 +21,7 @@ public PowerGeneratorRenderState createRenderState() { @Override protected StandaloneModelKey getModel() { - return HEAD; + return InfiniteCollectorRenderer.HEAD; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeCauldronBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeCauldronBlockEntityRenderer.java index afe347e9d1..c0622bc427 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeCauldronBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeCauldronBlockEntityRenderer.java @@ -40,11 +40,11 @@ public class LargeCauldronBlockEntityRenderer () -> "AnvilCraft: Large Cauldron Fire Model" ); private static final float WALL = 0.25F + 0.001F; - private static final float MIN_XZ = -1.0F + WALL; - private static final float MAX_XZ = 2.0F - WALL; + private static final float MIN_XZ = -1.0F + LargeCauldronBlockEntityRenderer.WALL; + private static final float MAX_XZ = 2.0F - LargeCauldronBlockEntityRenderer.WALL; private static final float MIN_Y = -0.5F + 0.001F; private static final float MAX_Y = 1.75F - 0.001F; - private static final float CONTENT_HEIGHT = MAX_Y - MIN_Y; + private static final float CONTENT_HEIGHT = LargeCauldronBlockEntityRenderer.MAX_Y - LargeCauldronBlockEntityRenderer.MIN_Y; private static final float INPUT_CELL_SPACING = 0.68F; private static final float FIRE_MODEL_SURFACE_Y = 1.0F - (1.0F / 16.0F + 0.001F); private static final int[][] SLOT_OFFSETS = { @@ -84,7 +84,10 @@ public void extractRenderState( 1.0F ); state.setFill(fill); - float itemY = Mth.clamp(MIN_Y + CONTENT_HEIGHT * fill - 0.08F, MIN_Y + 0.06F, MAX_Y - 0.12F); + float itemY = Mth.clamp( + LargeCauldronBlockEntityRenderer.MIN_Y + LargeCauldronBlockEntityRenderer.CONTENT_HEIGHT * fill - 0.08F, + LargeCauldronBlockEntityRenderer.MIN_Y + 0.06F, LargeCauldronBlockEntityRenderer.MAX_Y - 0.12F + ); float bob = fill > 0 ? Mth.sin(ClientTickRecorder.getTicks() / 12.0F) * 0.025F : 0.0F; this.extractItems(cauldron, state, itemY + bob); for (int layer = 0; layer < fluids.size(); layer++) { @@ -95,23 +98,23 @@ public void extractRenderState( } } if (cauldron.isIgnited()) { - state.setFire(FeatureRendererSupport.initialize(FIRE, cauldron)); + state.setFire(FeatureRendererSupport.initialize(LargeCauldronBlockEntityRenderer.FIRE, cauldron)); } } private void extractItems(LargeCauldronBlockEntity cauldron, LargeCauldronRenderState state, float itemY) { ResourceHandler inputs = cauldron.getInputHandler(); for (int slot = 0; slot < inputs.size(); slot++) { - ItemStack stack = toStack(inputs, slot); + ItemStack stack = LargeCauldronBlockEntityRenderer.toStack(inputs, slot); if (stack.isEmpty()) continue; - float x = SLOT_OFFSETS[slot][0] * INPUT_CELL_SPACING + 0.5F; - float z = SLOT_OFFSETS[slot][1] * INPUT_CELL_SPACING + 0.5F; + float x = LargeCauldronBlockEntityRenderer.SLOT_OFFSETS[slot][0] * LargeCauldronBlockEntityRenderer.INPUT_CELL_SPACING + 0.5F; + float z = LargeCauldronBlockEntityRenderer.SLOT_OFFSETS[slot][1] * LargeCauldronBlockEntityRenderer.INPUT_CELL_SPACING + 0.5F; state.getItems().add(this.createItemState(stack, x, itemY, z, slot * 37.0F)); } ResourceHandler outputs = cauldron.getOutputHandler(); for (int slot = 0; slot < outputs.size(); slot++) { - ItemStack stack = toStack(outputs, slot); + ItemStack stack = LargeCauldronBlockEntityRenderer.toStack(outputs, slot); if (stack.isEmpty()) continue; float angle = slot * 2.3999631F; float radius = 0.08F + slot % 3 * 0.07F; @@ -157,8 +160,8 @@ public void submit( BlockModelRenderState fire = state.getFire(); if (fire == null) return; poseStack.pushPose(); - float surfaceY = MIN_Y + CONTENT_HEIGHT * state.getFill(); - poseStack.translate(-1.0F, surfaceY - FIRE_MODEL_SURFACE_Y * 3.0F, -1.0F); + float surfaceY = LargeCauldronBlockEntityRenderer.MIN_Y + LargeCauldronBlockEntityRenderer.CONTENT_HEIGHT * state.getFill(); + poseStack.translate(-1.0F, surfaceY - LargeCauldronBlockEntityRenderer.FIRE_MODEL_SURFACE_Y * 3.0F, -1.0F); poseStack.scale(3.0F, 3.0F, 3.0F); fire.submit( poseStack, @@ -175,9 +178,9 @@ private void submitFluids( PoseStack poseStack, SubmitNodeCollector submitNodeCollector ) { - float minY = MIN_Y; + float minY = LargeCauldronBlockEntityRenderer.MIN_Y; for (FluidLayerRenderState layer : state.getFluids()) { - float maxY = minY + CONTENT_HEIGHT * layer.amount() / LargeCauldronFluidHandler.TOTAL_CAPACITY; + float maxY = minY + LargeCauldronBlockEntityRenderer.CONTENT_HEIGHT * layer.amount() / LargeCauldronFluidHandler.TOTAL_CAPACITY; FluidResource resource = layer.resource(); FluidModel model = FluidRenderHelper.getModel( Minecraft.getInstance().getModelManager().getFluidStateModelSet(), @@ -193,12 +196,12 @@ private void submitFluids( (pose, buffer) -> FluidRenderHelper.INSTANCE.renderFluidBox( sprite, resource, - MIN_XZ, + LargeCauldronBlockEntityRenderer.MIN_XZ, layerMinY, - MIN_XZ, - MAX_XZ, + LargeCauldronBlockEntityRenderer.MIN_XZ, + LargeCauldronBlockEntityRenderer.MAX_XZ, maxY, - MAX_XZ, + LargeCauldronBlockEntityRenderer.MAX_XZ, tintColor, buffer, pose, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeFluidTankRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeFluidTankRenderer.java index b660f6b66c..6cb846672a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeFluidTankRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/LargeFluidTankRenderer.java @@ -66,7 +66,7 @@ protected void updateTankW( Vec3 cameraPosition, ModelFeatureRenderer.@Nullable CrumblingOverlay breakProgress ) { - state.setTankW(-1, -1, -1, 2, 2, 2, TANK_W); + state.setTankW(-1, -1, -1, 2, 2, 2, LargeFluidTankRenderer.TANK_W); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/OverseerBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/OverseerBlockEntityRenderer.java index b33a148941..731222498a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/OverseerBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/OverseerBlockEntityRenderer.java @@ -62,7 +62,7 @@ public void extractRenderState( float time = level.getGameTime() + partialTicks; state.setTime(time); - state.setBobOffset(getHeadBobOffset(time)); + state.setBobOffset(OverseerBlockEntityRenderer.getHeadBobOffset(time)); state.setModel(FeatureRendererSupport.initialize(blockState, blockEntity)); this.spawnTrailParticles(blockEntity, level); } @@ -79,7 +79,7 @@ public void submit( poseStack.pushPose(); poseStack.translate(0.5, state.getBobOffset(), 0.5); - poseStack.mulPose(Axis.YP.rotationDegrees(state.getTime() * HEAD_ROTATION_DEGREES_PER_TICK)); + poseStack.mulPose(Axis.YP.rotationDegrees(state.getTime() * OverseerBlockEntityRenderer.HEAD_ROTATION_DEGREES_PER_TICK)); poseStack.translate(-0.5, 0, -0.5); model.submit( poseStack, @@ -92,7 +92,7 @@ public void submit( } private static float getHeadBobOffset(float time) { - return Mth.sin(time * HEAD_BOB_ANGULAR_SPEED) * HEAD_BOB_AMPLITUDE; + return Mth.sin(time * OverseerBlockEntityRenderer.HEAD_BOB_ANGULAR_SPEED) * OverseerBlockEntityRenderer.HEAD_BOB_AMPLITUDE; } private void spawnTrailParticles(OverseerBlockEntity blockEntity, Level level) { @@ -100,13 +100,14 @@ private void spawnTrailParticles(OverseerBlockEntity blockEntity, Level level) { Long previousParticleTick = this.lastParticleTicks.put(blockEntity, gameTime); if (previousParticleTick != null && previousParticleTick == gameTime) return; - float currentBob = getHeadBobOffset(gameTime); - float previousBob = getHeadBobOffset(gameTime - 1.0F); + float currentBob = OverseerBlockEntityRenderer.getHeadBobOffset(gameTime); + float previousBob = OverseerBlockEntityRenderer.getHeadBobOffset(gameTime - 1.0F); float movement = currentBob - previousBob; if (Math.abs(movement) < 0.0001F) return; BlockPos pos = blockEntity.getBlockPos(); - double trailY = pos.getY() + previousBob + (movement > 0 ? HEAD_MIN_Y : HEAD_MAX_Y); + double trailY = + pos.getY() + previousBob + (movement > 0 ? OverseerBlockEntityRenderer.HEAD_MIN_Y : OverseerBlockEntityRenderer.HEAD_MAX_Y); for (int i = 0; i < 2; i++) { double x = pos.getX() + 0.125 + level.getRandom().nextDouble() * 0.75; double z = pos.getZ() + 0.125 + level.getRandom().nextDouble() * 0.75; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PipeCheckValveBERenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PipeCheckValveBERenderer.java index ae15588dba..a6c9147ab9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PipeCheckValveBERenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PipeCheckValveBERenderer.java @@ -46,7 +46,7 @@ public void extractRenderState( BlockEntityRenderer.super.extractRenderState(be, state, partialTicks, cameraPosition, breakProgress); Map flows = be.effectiveFlows(); state.setFlows(flows.isEmpty() ? new EnumMap<>(Direction.class) : new EnumMap<>(flows)); - state.setArm(FeatureRendererSupport.initialize(ARM, be)); + state.setArm(FeatureRendererSupport.initialize(PipeCheckValveBERenderer.ARM, be)); } @Override @@ -65,7 +65,7 @@ public void submit( poseStack.pushPose(); poseStack.translate(0.5, 0.5, 0.5); - applyUpToFacing(poseStack, face); + PipeCheckValveBERenderer.applyUpToFacing(poseStack, face); Direction flowOut = entry.getValue(); if (flowOut == face.getOpposite()) { poseStack.mulPose(Axis.XP.rotationDegrees(180)); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PowerProducerRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PowerProducerRenderer.java index 4756066af0..56677e3e03 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PowerProducerRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PowerProducerRenderer.java @@ -6,12 +6,10 @@ import dev.dubhe.anvilcraft.client.init.ModRenderTypes; import dev.dubhe.anvilcraft.client.renderer.blockentity.state.PowerGeneratorRenderState; import dev.dubhe.anvilcraft.client.support.FeatureRendererSupport; -import net.minecraft.client.renderer.Sheets; import net.minecraft.client.renderer.SubmitNodeCollector; import net.minecraft.client.renderer.block.dispatch.BlockStateModel; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.feature.ModelFeatureRenderer; -import net.minecraft.client.renderer.rendertype.RenderTypes; import net.minecraft.client.renderer.state.level.CameraRenderState; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.world.level.block.entity.BlockEntity; @@ -65,7 +63,7 @@ protected float elevation() { } protected float magic() { - return ROTATION_MAGIC; + return PowerProducerRenderer.ROTATION_MAGIC; } protected abstract StandaloneModelKey getModel(); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PulseGeneratorBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PulseGeneratorBlockEntityRenderer.java index d4bc41fa49..fd4c858507 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PulseGeneratorBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PulseGeneratorBlockEntityRenderer.java @@ -60,7 +60,7 @@ public void extractRenderState( boolean overspeed = blockEntity.isProcessing() && blockEntity.getWaitingTime() + blockEntity.getSignalDuration() <= 3; state.setIndicator(FeatureRendererSupport.initialize( - overspeed ? INDICATOR_OVERSPEED : INDICATOR, + overspeed ? PulseGeneratorBlockEntityRenderer.INDICATOR_OVERSPEED : PulseGeneratorBlockEntityRenderer.INDICATOR, blockEntity )); } @@ -72,41 +72,56 @@ public void submit( SubmitNodeCollector collector, CameraRenderState camera ) { - if (state.getIndicator() == null) return; pose.pushPose(); pose.translate(0.5f, 0.0f, 0.5f); pose.mulPose(Axis.YP.rotationDegrees(-state.getFacing().toYRot())); pose.translate(-0.5f, 0.0f, -0.5f); - float phaseStartAngle = state.isOutputting() ? END_ANGLE : START_ANGLE; - translateOnTable(pose, INDICATOR_OFFSET_Z); - rotateOnTable(pose, phaseStartAngle + (END_ANGLE - START_ANGLE) * state.getPhaseProgress()); + float phaseStartAngle = + state.isOutputting() ? PulseGeneratorBlockEntityRenderer.END_ANGLE : PulseGeneratorBlockEntityRenderer.START_ANGLE; + PulseGeneratorBlockEntityRenderer.translateOnTable(pose); + PulseGeneratorBlockEntityRenderer.rotateOnTable( + pose, phaseStartAngle + (PulseGeneratorBlockEntityRenderer.END_ANGLE - PulseGeneratorBlockEntityRenderer.START_ANGLE) + * state.getPhaseProgress() + ); state.getIndicator().submit(pose, collector, state.lightCoords, OverlayTexture.NO_OVERLAY, 0); pose.popPose(); } - private static void translateOnTable(PoseStack pose, float offsetZ) { - pose.translate(TABLE_ORIGIN_X, TABLE_ORIGIN_Y, TABLE_ORIGIN_Z); - pose.mulPose(Axis.XP.rotationDegrees(TABLE_ANGLE)); - pose.translate(0.0f, 0.0f, offsetZ); - pose.mulPose(Axis.XP.rotationDegrees(-TABLE_ANGLE)); - pose.translate(-TABLE_ORIGIN_X, -TABLE_ORIGIN_Y, -TABLE_ORIGIN_Z); + private static void translateOnTable(PoseStack pose) { + pose.translate( + PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_X, PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Y, + PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Z + ); + pose.mulPose(Axis.XP.rotationDegrees(PulseGeneratorBlockEntityRenderer.TABLE_ANGLE)); + pose.translate(0.0f, 0.0f, PulseGeneratorBlockEntityRenderer.INDICATOR_OFFSET_Z); + pose.mulPose(Axis.XP.rotationDegrees(-PulseGeneratorBlockEntityRenderer.TABLE_ANGLE)); + pose.translate( + -PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_X, -PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Y, + -PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Z + ); } private static void rotateOnTable(PoseStack pose, float angle) { - pose.translate(TABLE_ORIGIN_X, TABLE_ORIGIN_Y, TABLE_ORIGIN_Z); - pose.mulPose(Axis.XP.rotationDegrees(TABLE_ANGLE)); pose.translate( - INDICATOR_PIVOT_X - TABLE_ORIGIN_X, - INDICATOR_PIVOT_Y - TABLE_ORIGIN_Y, - INDICATOR_PIVOT_Z - TABLE_ORIGIN_Z + PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_X, PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Y, + PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Z + ); + pose.mulPose(Axis.XP.rotationDegrees(PulseGeneratorBlockEntityRenderer.TABLE_ANGLE)); + pose.translate( + PulseGeneratorBlockEntityRenderer.INDICATOR_PIVOT_X - PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_X, + PulseGeneratorBlockEntityRenderer.INDICATOR_PIVOT_Y - PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Y, + PulseGeneratorBlockEntityRenderer.INDICATOR_PIVOT_Z - PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Z ); pose.mulPose(Axis.YP.rotationDegrees(angle)); pose.translate( - TABLE_ORIGIN_X - INDICATOR_PIVOT_X, - TABLE_ORIGIN_Y - INDICATOR_PIVOT_Y, - TABLE_ORIGIN_Z - INDICATOR_PIVOT_Z + PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_X - PulseGeneratorBlockEntityRenderer.INDICATOR_PIVOT_X, + PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Y - PulseGeneratorBlockEntityRenderer.INDICATOR_PIVOT_Y, + PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Z - PulseGeneratorBlockEntityRenderer.INDICATOR_PIVOT_Z + ); + pose.mulPose(Axis.XP.rotationDegrees(-PulseGeneratorBlockEntityRenderer.TABLE_ANGLE)); + pose.translate( + -PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_X, -PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Y, + -PulseGeneratorBlockEntityRenderer.TABLE_ORIGIN_Z ); - pose.mulPose(Axis.XP.rotationDegrees(-TABLE_ANGLE)); - pose.translate(-TABLE_ORIGIN_X, -TABLE_ORIGIN_Y, -TABLE_ORIGIN_Z); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PumpBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PumpBlockEntityRenderer.java index 4ae005df50..a0ab6c0c25 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PumpBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/PumpBlockEntityRenderer.java @@ -14,6 +14,7 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.feature.ModelFeatureRenderer; import net.minecraft.client.renderer.state.level.CameraRenderState; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; @@ -56,7 +57,7 @@ public void extractRenderState( if (!(blockState.getBlock() instanceof PumpBlock)) return; if (!be.isWorking()) return; - net.minecraft.world.level.Level level = be.getLevel(); + Level level = be.getLevel(); if (level == null) return; Orientation orientation = blockState.getValue(PumpBlock.ORIENTATION); @@ -67,11 +68,11 @@ public void extractRenderState( float cycle = ((gameTime + partialTicks) * speed) % 20.0f / 20.0f; float angle = cycle * 2.0f * (float) Math.PI; - state.setPiston1Offset((float) Math.sin(angle) * MAX_PISTON_OFFSET); - state.setPiston2Offset((float) Math.cos(angle) * MAX_PISTON_OFFSET); + state.setPiston1Offset((float) Math.sin(angle) * PumpBlockEntityRenderer.MAX_PISTON_OFFSET); + state.setPiston2Offset((float) Math.cos(angle) * PumpBlockEntityRenderer.MAX_PISTON_OFFSET); - state.setPiston1(FeatureRendererSupport.initialize(PUMP_PISTON_1, be)); - state.setPiston2(FeatureRendererSupport.initialize(PUMP_PISTON_2, be)); + state.setPiston1(FeatureRendererSupport.initialize(PumpBlockEntityRenderer.PUMP_PISTON_1, be)); + state.setPiston2(FeatureRendererSupport.initialize(PumpBlockEntityRenderer.PUMP_PISTON_2, be)); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/SmartBlockPlacerRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/SmartBlockPlacerRenderer.java index f692f4b0e7..9444494f10 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/SmartBlockPlacerRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/SmartBlockPlacerRenderer.java @@ -163,14 +163,14 @@ private float[] calculateTargetAngles( final float baseAngle = (float) Math.toDegrees(Math.atan2(rightDist, forwardDist)); final float horizontalDist = (float) Math.sqrt(forwardDist * forwardDist + rightDist * rightDist); - float targetHeight = (float) dy - BASE_HEIGHT; + float targetHeight = (float) dy - WorkingAnimationScheme.BASE_HEIGHT; if (upsideDown) { - targetHeight = -(float) dy - BASE_HEIGHT; + targetHeight = -(float) dy - WorkingAnimationScheme.BASE_HEIGHT; } final float elevationAngle = (float) Math.toDegrees(Math.atan2(targetHeight, horizontalDist)); final float distToTarget = (float) Math.sqrt(horizontalDist * horizontalDist + targetHeight * targetHeight); - final boolean isOverRange = distToTarget >= UPPER_ARM_LENGTH + FOREARM_LENGTH; + final boolean isOverRange = distToTarget >= WorkingAnimationScheme.UPPER_ARM_LENGTH + WorkingAnimationScheme.FOREARM_LENGTH; float upperArmAngle; float forearmAngle; @@ -180,13 +180,18 @@ private float[] calculateTargetAngles( } else { float clampedDist = Math.max(0.01f, distToTarget); - float cosForearm = (UPPER_ARM_LENGTH * UPPER_ARM_LENGTH + FOREARM_LENGTH * FOREARM_LENGTH - clampedDist * clampedDist) - / (2 * UPPER_ARM_LENGTH * FOREARM_LENGTH); + float cosForearm = (WorkingAnimationScheme.UPPER_ARM_LENGTH * WorkingAnimationScheme.UPPER_ARM_LENGTH + + WorkingAnimationScheme.FOREARM_LENGTH * WorkingAnimationScheme.FOREARM_LENGTH + - clampedDist * clampedDist) + / (2 * WorkingAnimationScheme.UPPER_ARM_LENGTH * WorkingAnimationScheme.FOREARM_LENGTH); cosForearm = Math.clamp(cosForearm, -1.0f, 1.0f); float forearmAngleFromUpper = (float) Math.toDegrees(Math.acos(cosForearm)); - float cosUpperArm = (clampedDist * clampedDist + UPPER_ARM_LENGTH * UPPER_ARM_LENGTH - FOREARM_LENGTH * FOREARM_LENGTH) - / (2 * clampedDist * UPPER_ARM_LENGTH); + float cosUpperArm = + (clampedDist * clampedDist + WorkingAnimationScheme.UPPER_ARM_LENGTH * WorkingAnimationScheme.UPPER_ARM_LENGTH + - WorkingAnimationScheme.FOREARM_LENGTH + * WorkingAnimationScheme.FOREARM_LENGTH) + / (2 * clampedDist * WorkingAnimationScheme.UPPER_ARM_LENGTH); cosUpperArm = Math.clamp(cosUpperArm, -1.0f, 1.0f); float upperArmAngleFromTarget = (float) Math.toDegrees(Math.acos(cosUpperArm)); upperArmAngle = -(180f - upperArmAngleFromTarget - elevationAngle) * 0.6f + 20f; @@ -236,11 +241,11 @@ public void extractRenderState( state.setAnimationDurationTicks(SmartBlockPlacerBlockEntity.getPlacementInterval()); // Initialize models - state.setBaseModel(FeatureRendererSupport.initialize(BASE_MODEL, entity)); - state.setUpperArmModel(FeatureRendererSupport.initialize(UPPERARM_MODEL, entity)); - state.setForearmModel(FeatureRendererSupport.initialize(FOREARM_MODEL, entity)); - state.setClawModel(FeatureRendererSupport.initialize(CLAW_MODEL, entity)); - state.setClawOpenModel(FeatureRendererSupport.initialize(CLAW_OPEN_MODEL, entity)); + state.setBaseModel(FeatureRendererSupport.initialize(SmartBlockPlacerRenderer.BASE_MODEL, entity)); + state.setUpperArmModel(FeatureRendererSupport.initialize(SmartBlockPlacerRenderer.UPPERARM_MODEL, entity)); + state.setForearmModel(FeatureRendererSupport.initialize(SmartBlockPlacerRenderer.FOREARM_MODEL, entity)); + state.setClawModel(FeatureRendererSupport.initialize(SmartBlockPlacerRenderer.CLAW_MODEL, entity)); + state.setClawOpenModel(FeatureRendererSupport.initialize(SmartBlockPlacerRenderer.CLAW_OPEN_MODEL, entity)); BlockState blockState = entity.getBlockState(); if (!(blockState.getBlock() instanceof SmartBlockPlacerBlock)) return; @@ -290,7 +295,7 @@ public void extractRenderState( long elapsedTicks = retractLevel.getGameTime() - animStartTime; float interruptProgress = Math.min(1.0f, (elapsedTicks + partialTick) / (float) state .getAnimationDurationTicks()); - float[] angles = WORKING_ANIMATION_SCHEME.calculateArmAngles( + float[] angles = SmartBlockPlacerRenderer.WORKING_ANIMATION_SCHEME.calculateArmAngles( animTargetPos, entity.getBlockPos(), facing, upsideDown, interruptProgress ); entity.setClientRetractStartAngles(angles); @@ -363,7 +368,7 @@ public void extractRenderState( entity.setClientIsRetracting(true); entity.setClientRetractStartTime(currentTime); - float[] endAngles = WORKING_ANIMATION_SCHEME.calculateArmAngles( + float[] endAngles = SmartBlockPlacerRenderer.WORKING_ANIMATION_SCHEME.calculateArmAngles( animTargetPos, entity.getBlockPos(), facing, upsideDown, 1.0f ); entity.setClientRetractStartAngles(endAngles); @@ -458,7 +463,7 @@ public void extractRenderState( entity.setRetractSoundPlayed(true); } - float[] angles = WORKING_ANIMATION_SCHEME.calculateArmAngles( + float[] angles = SmartBlockPlacerRenderer.WORKING_ANIMATION_SCHEME.calculateArmAngles( animTargetPos, entity.getBlockPos(), facing, upsideDown, animationProgress ); baseSwingAngle = angles[0]; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TeslaTowerRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TeslaTowerRenderer.java index b1011f2e2b..cac826646b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TeslaTowerRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TeslaTowerRenderer.java @@ -79,7 +79,7 @@ public void submit( state.getStart(), state.getEnd(), state.getCamera(), - LIGHTNING_WIDTH, + TeslaTowerRenderer.LIGHTNING_WIDTH, 0.7F ) ); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TradingStationBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TradingStationBlockEntityRenderer.java index 1da7d21307..2e4392123f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TradingStationBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/TradingStationBlockEntityRenderer.java @@ -79,7 +79,7 @@ public void submit( List items = state.getItems(); if (items.isEmpty()) return; if (items.size() == 1) { - renderItem( + TradingStationBlockEntityRenderer.renderItem( pose, collector, items.getFirst(), @@ -91,7 +91,7 @@ public void submit( Direction dir = state.getFacing(); float firstOffset = dir.getAxisDirection() == Direction.AxisDirection.POSITIVE ? 11 / 16F : 5 / 16F; float secondOffset = dir.getAxisDirection() == Direction.AxisDirection.POSITIVE ? 5 / 16F : 11 / 16F; - renderItem( + TradingStationBlockEntityRenderer.renderItem( pose, collector, items.getFirst(), @@ -99,7 +99,7 @@ public void submit( dir.getAxis() == Direction.Axis.Z ? firstOffset : 0.5F, state.getRotation() ); - renderItem( + TradingStationBlockEntityRenderer.renderItem( pose, collector, items.get(1), @@ -126,7 +126,7 @@ private static void renderItem( pose.scale(0.85F, 0.85F, 0.85F); } pose.mulPose(Axis.YP.rotationDegrees(rotation)); - item.submit(pose, collector, ITEM_LIGHT, OverlayTexture.NO_OVERLAY, cluster.outlineColor); + item.submit(pose, collector, TradingStationBlockEntityRenderer.ITEM_LIGHT, OverlayTexture.NO_OVERLAY, cluster.outlineColor); pose.popPose(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/VoidEnergyCollectorRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/VoidEnergyCollectorRenderer.java index a1d618ff70..9bef982f18 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/VoidEnergyCollectorRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/VoidEnergyCollectorRenderer.java @@ -31,6 +31,6 @@ protected float rotation(VoidEnergyCollectorBlockEntity blockEntity, float parti @Override protected StandaloneModelKey getModel() { - return HEAD; + return VoidEnergyCollectorRenderer.HEAD; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/WipBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/WipBlockEntityRenderer.java index bd6fd54f7a..f4ec9981f7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/WipBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/WipBlockEntityRenderer.java @@ -7,6 +7,7 @@ import dev.dubhe.anvilcraft.recipe.anvil.procedural.ProceduralProcessRecipe; import dev.dubhe.anvilcraft.recipe.sync.RecipesRecord; import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.SubmitNodeCollector; import net.minecraft.client.renderer.block.BlockModelRenderState; import net.minecraft.client.renderer.block.dispatch.BlockStateModel; @@ -19,6 +20,7 @@ import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; import net.minecraft.util.RandomSource; +import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; @@ -35,53 +37,57 @@ public class WipBlockEntityRenderer implements BlockEntityRenderer> MODEL_KEYS = new HashMap<>(); - public static final StandaloneModelKey SPACETIME_SUPERCOMPUTER_WIP = registerModel( + public static final StandaloneModelKey SPACETIME_SUPERCOMPUTER_WIP = WipBlockEntityRenderer.registerModel( "block/spacetime_supercomputer_wip" ); - public static final StandaloneModelKey ANCIENT_DEBRIS_WIP = registerModel("block/ancient_debris_wip"); - public static final StandaloneModelKey NETHERITE_BLOCK_WIP = registerModel("block/netherite_block_wip"); - public static final StandaloneModelKey HEAVY_IRON_BLOCK_WIP = registerModel("block/heavy_iron_block_wip"); - public static final StandaloneModelKey ANCIENT_SEA_REEF_WIP = registerModel("block/ancient_sea_reef_wip"); - public static final StandaloneModelKey NESTING_SHULKER_BOX = registerModel( + public static final StandaloneModelKey ANCIENT_DEBRIS_WIP = WipBlockEntityRenderer.registerModel( + "block/ancient_debris_wip"); + public static final StandaloneModelKey NETHERITE_BLOCK_WIP = WipBlockEntityRenderer.registerModel( + "block/netherite_block_wip"); + public static final StandaloneModelKey HEAVY_IRON_BLOCK_WIP = WipBlockEntityRenderer.registerModel( + "block/heavy_iron_block_wip"); + public static final StandaloneModelKey ANCIENT_SEA_REEF_WIP = WipBlockEntityRenderer.registerModel( + "block/ancient_sea_reef_wip"); + public static final StandaloneModelKey NESTING_SHULKER_BOX = WipBlockEntityRenderer.registerModel( "block/nesting_shulker_box" ); - public static final StandaloneModelKey OVER_NESTING_SHULKER_BOX = registerModel( + public static final StandaloneModelKey OVER_NESTING_SHULKER_BOX = WipBlockEntityRenderer.registerModel( "block/over_nesting_shulker_box" ); - public static final StandaloneModelKey SUPERCRITICAL_NESTING_SHULKER_BOX = registerModel( + public static final StandaloneModelKey SUPERCRITICAL_NESTING_SHULKER_BOX = WipBlockEntityRenderer.registerModel( "block/supercritical_nesting_shulker_box" ); - public static final StandaloneModelKey SPACETIME_SUPERCOMPUTER_WIP_2 = registerModel( + public static final StandaloneModelKey SPACETIME_SUPERCOMPUTER_WIP_2 = WipBlockEntityRenderer.registerModel( "block/spacetime_supercomputer_wip_2" ); - public static final StandaloneModelKey SPACETIME_SUPERCOMPUTER_WIP_3 = registerModel( + public static final StandaloneModelKey SPACETIME_SUPERCOMPUTER_WIP_3 = WipBlockEntityRenderer.registerModel( "block/spacetime_supercomputer_wip_3" ); - public static final StandaloneModelKey NETHERITE_BLOCK_WIP_2 = registerModel( + public static final StandaloneModelKey NETHERITE_BLOCK_WIP_2 = WipBlockEntityRenderer.registerModel( "block/netherite_block_wip_2" ); - public static final StandaloneModelKey HEAVY_IRON_BLOCK_WIP_2 = registerModel( + public static final StandaloneModelKey HEAVY_IRON_BLOCK_WIP_2 = WipBlockEntityRenderer.registerModel( "block/heavy_iron_block_wip_2" ); - public static final StandaloneModelKey ANCIENT_SEA_REEF_WIP_2 = registerModel( + public static final StandaloneModelKey ANCIENT_SEA_REEF_WIP_2 = WipBlockEntityRenderer.registerModel( "block/ancient_sea_reef_wip_2" ); - public static final StandaloneModelKey SHULKER_BOX_WIP = registerModel( + public static final StandaloneModelKey SHULKER_BOX_WIP = WipBlockEntityRenderer.registerModel( "block/shulker_box_wip" ); - public static final StandaloneModelKey SHULKER_BOX_WIP_2 = registerModel( + public static final StandaloneModelKey SHULKER_BOX_WIP_2 = WipBlockEntityRenderer.registerModel( "block/shulker_box_wip_2" ); private static StandaloneModelKey registerModel(String path) { Identifier id = AnvilCraft.of(path); StandaloneModelKey key = new StandaloneModelKey<>(() -> "AnvilCraft: WIP " + path); - MODEL_KEYS.put(id, key); + WipBlockEntityRenderer.MODEL_KEYS.put(id, key); return key; } public static @Nullable StandaloneModelKey getModelKey(Identifier id) { - return MODEL_KEYS.get(id); + return WipBlockEntityRenderer.MODEL_KEYS.get(id); } public WipBlockEntityRenderer(BlockEntityRendererProvider.Context context) { @@ -102,14 +108,14 @@ public void extractRenderState( ) { BlockEntityRenderer.super.extractRenderState(be, state, partialTicks, cameraPosition, breakProgress); Minecraft mc = Minecraft.getInstance(); - Level level = be.getLevel(); + ClientLevel level = mc.level; if (level == null) return; BlockStateModel model = this.getDisplayedModel(be, level, mc); BlockModelRenderState blockModelState = new BlockModelRenderState(); if (model != null) { model.collectParts( - mc.level, + level, be.getBlockPos(), be.getBlockState(), RandomSource.create(be.getInitialBlock().getSeed(be.getBlockPos())), @@ -123,7 +129,7 @@ public void extractRenderState( // Try to get standalone model from recipe's displayedModel field Optional displayedModelId = Optional.ofNullable(be.getRecipeId()) .map(recipeId -> { - ResourceKey> key = ResourceKey.create(Registries.RECIPE, recipeId); + ResourceKey> key = ResourceKey.create(Registries.RECIPE, recipeId); RecipeHolder holder = RecipesRecord.getRecipes(level).byKey(key); if (holder != null && holder.value() instanceof ProceduralProcessRecipe ppr) { return ppr.getDisplayedModelForStep(be.getStepCount()).orElse(null); @@ -131,7 +137,7 @@ public void extractRenderState( return null; }); if (displayedModelId.isPresent()) { - StandaloneModelKey modelKey = getModelKey(displayedModelId.get()); + StandaloneModelKey modelKey = WipBlockEntityRenderer.getModelKey(displayedModelId.get()); if (modelKey != null) { BlockStateModel standaloneModel = mc.getModelManager().getStandaloneModel(modelKey); if (standaloneModel != null) { @@ -141,7 +147,7 @@ public void extractRenderState( } // Fallback: render the initial block's model BlockState initialState = be.getInitialBlock(); - if (initialState != null && !initialState.isAir()) { + if (!initialState.isAir()) { return mc.getModelManager().getBlockStateModelSet().get(initialState); } return null; @@ -154,7 +160,6 @@ public void submit( SubmitNodeCollector collector, CameraRenderState camera ) { - if (state.getBlockModel() == null) return; pose.pushPose(); state.getBlockModel().submit(pose, collector, state.lightCoords, OverlayTexture.NO_OVERLAY, 0); pose.popPose(); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyRenderer.java index a060a475c0..13addf7711 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyRenderer.java @@ -101,7 +101,7 @@ public static float[] getStarColor(StarData star) { * (32,16)-(48,32)、(0,16)-(16,32) 和 (16,16)-(32,32)。 */ public static void renderPlanetBody(PoseStack.Pose pose, VertexConsumer vc, int light, int overlay) { - renderPlanetCube(pose, vc, light, overlay, LIGHT_DIR); + CelestialBodyRenderer.renderPlanetCube(pose, vc, light, overlay, CelestialBodyRenderer.LIGHT_DIR); } /** @@ -136,23 +136,23 @@ public static void renderAtmosphereCube( } // 每个面根据观察角度使用独立透明度。 - float alphaUp = computeAtmosphereAlpha(pose, 0, 1, 0, baseAlpha, vx, vy, vz); - tintedFaceUp(pose, vc, x1, x2, z1, z2, y2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaUp); + float alphaUp = CelestialBodyRenderer.computeAtmosphereAlpha(pose, 0, 1, 0, baseAlpha, vx, vy, vz); + CelestialBodyRenderer.tintedFaceUp(pose, vc, x1, x2, z1, z2, y2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaUp); - float alphaDown = computeAtmosphereAlpha(pose, 0, -1, 0, baseAlpha, vx, vy, vz); - tintedFaceDown(pose, vc, x1, x2, z1, z2, y1, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaDown); + float alphaDown = CelestialBodyRenderer.computeAtmosphereAlpha(pose, 0, -1, 0, baseAlpha, vx, vy, vz); + CelestialBodyRenderer.tintedFaceDown(pose, vc, x1, x2, z1, z2, y1, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaDown); - float alphaN = computeAtmosphereAlpha(pose, 0, 0, -1, baseAlpha, vx, vy, vz); - tintedFaceNorth(pose, vc, x1, x2, y1, y2, z1, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaN); + float alphaN = CelestialBodyRenderer.computeAtmosphereAlpha(pose, 0, 0, -1, baseAlpha, vx, vy, vz); + CelestialBodyRenderer.tintedFaceNorth(pose, vc, x1, x2, y1, y2, z1, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaN); - float alphaS = computeAtmosphereAlpha(pose, 0, 0, 1, baseAlpha, vx, vy, vz); - tintedFaceSouth(pose, vc, x1, x2, y1, y2, z2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaS); + float alphaS = CelestialBodyRenderer.computeAtmosphereAlpha(pose, 0, 0, 1, baseAlpha, vx, vy, vz); + CelestialBodyRenderer.tintedFaceSouth(pose, vc, x1, x2, y1, y2, z2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaS); - float alphaE = computeAtmosphereAlpha(pose, 1, 0, 0, baseAlpha, vx, vy, vz); - tintedFaceEast(pose, vc, x2, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaE); + float alphaE = CelestialBodyRenderer.computeAtmosphereAlpha(pose, 1, 0, 0, baseAlpha, vx, vy, vz); + CelestialBodyRenderer.tintedFaceEast(pose, vc, x2, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaE); - float alphaW = computeAtmosphereAlpha(pose, -1, 0, 0, baseAlpha, vx, vy, vz); - tintedFaceWest(pose, vc, x1, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaW); + float alphaW = CelestialBodyRenderer.computeAtmosphereAlpha(pose, -1, 0, 0, baseAlpha, vx, vy, vz); + CelestialBodyRenderer.tintedFaceWest(pose, vc, x1, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, rgb[0], rgb[1], rgb[2], alphaW); } /** 使用多层同心半透明立方体绘制恒星光晕。 */ @@ -169,7 +169,7 @@ public static void renderStarHalo(PoseStack.Pose pose, VertexConsumer vc, StarDa ps.translate(0.5, 0.5, 0.5); ps.scale(scale, scale, scale); ps.translate(-0.5, -0.5, -0.5); - renderAtmosphereCube(ps.last(), vc, rgb, alpha, light, overlay); + CelestialBodyRenderer.renderAtmosphereCube(ps.last(), vc, rgb, alpha, light, overlay); ps.popPose(); } } @@ -193,12 +193,12 @@ public static void renderColorCube( float y2 = 1; float z1 = 0; float z2 = 1; - tintedFaceUp(ps, vc, x1, x2, z1, z2, y2, 0, 0, 1, 1, light, overlay, r, g, b, a); - tintedFaceDown(ps, vc, x1, x2, z1, z2, y1, 0, 0, 1, 1, light, overlay, r, g, b, a); - tintedFaceNorth(ps, vc, x1, x2, y1, y2, z1, 0, 0, 1, 1, light, overlay, r, g, b, a); - tintedFaceSouth(ps, vc, x1, x2, y1, y2, z2, 0, 0, 1, 1, light, overlay, r, g, b, a); - tintedFaceEast(ps, vc, x2, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, r, g, b, a); - tintedFaceWest(ps, vc, x1, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, r, g, b, a); + CelestialBodyRenderer.tintedFaceUp(ps, vc, x1, x2, z1, z2, y2, 0, 0, 1, 1, light, overlay, r, g, b, a); + CelestialBodyRenderer.tintedFaceDown(ps, vc, x1, x2, z1, z2, y1, 0, 0, 1, 1, light, overlay, r, g, b, a); + CelestialBodyRenderer.tintedFaceNorth(ps, vc, x1, x2, y1, y2, z1, 0, 0, 1, 1, light, overlay, r, g, b, a); + CelestialBodyRenderer.tintedFaceSouth(ps, vc, x1, x2, y1, y2, z2, 0, 0, 1, 1, light, overlay, r, g, b, a); + CelestialBodyRenderer.tintedFaceEast(ps, vc, x2, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, r, g, b, a); + CelestialBodyRenderer.tintedFaceWest(ps, vc, x1, y1, y2, z1, z2, 0, 0, 1, 1, light, overlay, r, g, b, a); } /** 在 y=0.5 平面绘制从内半径延伸到外半径的扁平天体环。 */ @@ -269,10 +269,10 @@ private static void renderPlanetCube( boolean lit = lightDir != null; - int upColor = lit ? computeLambertColor(pose, 0, 1, 0, lightDir) : -1; - faceUp(pose, vc, x1, x2, z1, z2, y2, 16f / 64, 0, 32f / 64, 16f / 64, light, overlay, upColor); + int upColor = lit ? CelestialBodyRenderer.computeLambertColor(pose, 0, 1, 0, lightDir) : -1; + CelestialBodyRenderer.faceUp(pose, vc, x1, x2, z1, z2, y2, 16f / 64, 0, 32f / 64, 16f / 64, light, overlay, upColor); - int downColor = lit ? computeLambertColor(pose, 0, -1, 0, lightDir) : -1; + int downColor = lit ? CelestialBodyRenderer.computeLambertColor(pose, 0, -1, 0, lightDir) : -1; vc.addVertex(pose, x1, y1, z1) .setColor(downColor) .setUv(16f / 64, 48f / 64) @@ -298,14 +298,14 @@ private static void renderPlanetCube( .setLight(light) .setNormal(pose, 0, -1, 0); - int colorN = lit ? computeLambertColor(pose, 0, 0, -1, lightDir) : -1; - faceNorth(pose, vc, x1, x2, y1, y2, z1, 48f / 64, 16f / 64, 64f / 64, 32f / 64, light, overlay, colorN); - int colorE = lit ? computeLambertColor(pose, 1, 0, 0, lightDir) : -1; - faceEast(pose, vc, x2, y1, y2, z1, z2, 32f / 64, 16f / 64, 48f / 64, 32f / 64, light, overlay, colorE); - int colorW = lit ? computeLambertColor(pose, -1, 0, 0, lightDir) : -1; - faceWest(pose, vc, x1, y1, y2, z1, z2, 0, 16f / 64, 16f / 64, 32f / 64, light, overlay, colorW); - int colorS = lit ? computeLambertColor(pose, 0, 0, 1, lightDir) : -1; - faceSouth(pose, vc, x1, x2, y1, y2, z2, 16f / 64, 16f / 64, 32f / 64, 32f / 64, light, overlay, colorS); + int colorN = lit ? CelestialBodyRenderer.computeLambertColor(pose, 0, 0, -1, lightDir) : -1; + CelestialBodyRenderer.faceNorth(pose, vc, x1, x2, y1, y2, z1, 48f / 64, 16f / 64, 64f / 64, 32f / 64, light, overlay, colorN); + int colorE = lit ? CelestialBodyRenderer.computeLambertColor(pose, 1, 0, 0, lightDir) : -1; + CelestialBodyRenderer.faceEast(pose, vc, x2, y1, y2, z1, z2, 32f / 64, 16f / 64, 48f / 64, 32f / 64, light, overlay, colorE); + int colorW = lit ? CelestialBodyRenderer.computeLambertColor(pose, -1, 0, 0, lightDir) : -1; + CelestialBodyRenderer.faceWest(pose, vc, x1, y1, y2, z1, z2, 0, 16f / 64, 16f / 64, 32f / 64, light, overlay, colorW); + int colorS = lit ? CelestialBodyRenderer.computeLambertColor(pose, 0, 0, 1, lightDir) : -1; + CelestialBodyRenderer.faceSouth(pose, vc, x1, x2, y1, y2, z2, 16f / 64, 16f / 64, 32f / 64, 32f / 64, light, overlay, colorS); } // ==================== 带贴图面的辅助方法 ==================== @@ -551,7 +551,7 @@ private static void tintedFaceUp( float b, float a ) { - int argb = packColor(r, g, b, a); + int argb = CelestialBodyRenderer.packColor(r, g, b, a); vc.addVertex(pose, x1, y, z2).setColor(argb).setUv(u1, v2).setOverlay(overlay).setLight(light).setNormal( pose, 0, @@ -599,7 +599,7 @@ private static void tintedFaceDown( float a ) { - int argb = packColor(r, g, b, a); + int argb = CelestialBodyRenderer.packColor(r, g, b, a); vc.addVertex(pose, x1, y, z1).setColor(argb).setUv(u1, v2).setOverlay(overlay).setLight(light).setNormal( pose, 0, @@ -646,7 +646,7 @@ private static void tintedFaceNorth( float b, float a ) { - int argb = packColor(r, g, b, a); + int argb = CelestialBodyRenderer.packColor(r, g, b, a); vc.addVertex(pose, x2, y1, z).setColor(argb).setUv(u1, v2).setOverlay(overlay).setLight(light).setNormal( pose, 0, @@ -693,7 +693,7 @@ private static void tintedFaceSouth( float b, float a ) { - int argb = packColor(r, g, b, a); + int argb = CelestialBodyRenderer.packColor(r, g, b, a); vc.addVertex(pose, x1, y1, z).setColor(argb).setUv(u1, v2).setOverlay(overlay).setLight(light).setNormal( pose, 0, @@ -740,7 +740,7 @@ private static void tintedFaceEast( float b, float a ) { - int argb = packColor(r, g, b, a); + int argb = CelestialBodyRenderer.packColor(r, g, b, a); vc.addVertex(pose, x, y1, z2).setColor(argb).setUv(u1, v2).setOverlay(overlay).setLight(light).setNormal( pose, 1, @@ -787,7 +787,7 @@ private static void tintedFaceWest( float b, float a ) { - int argb = packColor(r, g, b, a); + int argb = CelestialBodyRenderer.packColor(r, g, b, a); vc.addVertex(pose, x, y1, z1).setColor(argb).setUv(u1, v2).setOverlay(overlay).setLight(light).setNormal( pose, -1, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyTextureBakery.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyTextureBakery.java index 940517b823..eb1884e5ab 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyTextureBakery.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/CelestialBodyTextureBakery.java @@ -34,7 +34,7 @@ public class CelestialBodyTextureBakery { @Nullable private static NativeImage loadImage(String filename) { - Identifier loc = AnvilCraft.of(TEX_DIR + "/" + filename); + Identifier loc = AnvilCraft.of(CelestialBodyTextureBakery.TEX_DIR + "/" + filename); try { Resource res = Minecraft.getInstance().getResourceManager().getResource(loc).orElse(null); if (res == null) return null; @@ -58,27 +58,29 @@ private static Identifier registerTexture(String key, NativeImage image) { @Nullable public static Identifier getOrBakeBody(CelestialBodyData data) { - return CACHE.computeIfAbsent(cacheKey(data), k -> bakeBody(data, k)); + return CelestialBodyTextureBakery.CACHE.computeIfAbsent( + CelestialBodyTextureBakery.cacheKey(data), k -> CelestialBodyTextureBakery.bakeBody(data, k)); } @Nullable public static Identifier getOrBakeRing(CelestialBodyData data) { if (data.ringType() == RingType.NONE) return null; - return CACHE.computeIfAbsent(ringCacheKey(data), k -> bakeRing(data, k)); + return CelestialBodyTextureBakery.CACHE.computeIfAbsent( + CelestialBodyTextureBakery.ringCacheKey(data), k -> CelestialBodyTextureBakery.bakeRing(data, k)); } private record TexSet(String base, @Nullable String overlay, String palette) { } private static TexSet resolve(CelestialBodyData data) { - if (data instanceof RockyPlanetData rp) return resolveRocky(rp); + if (data instanceof RockyPlanetData rp) return CelestialBodyTextureBakery.resolveRocky(rp); if (data instanceof GiantPlanetData gp) { if (gp.brownDwarf()) return new TexSet( "planet_giant.png", gp.windSpeed() == WindSpeed.VERY_HIGH ? "planet_giant_overlay_1.png" : "planet_giant_overlay_0.png", "planet_mix_color_scorched.png" ); - return resolveGiant(gp); + return CelestialBodyTextureBakery.resolveGiant(gp); } return null; } @@ -154,15 +156,15 @@ private static TexSet resolveGiant(GiantPlanetData gp) { @Nullable private static Identifier bakeBody(CelestialBodyData data, String key) { - if (data instanceof SpecialCelestialBodyData special) return bakeSpecial(key, special); + if (data instanceof SpecialCelestialBodyData special) return CelestialBodyTextureBakery.bakeSpecial(key, special); - TexSet tex = resolve(data); + TexSet tex = CelestialBodyTextureBakery.resolve(data); if (tex == null) return null; - NativeImage baseImg = loadImage(tex.base()); + NativeImage baseImg = CelestialBodyTextureBakery.loadImage(tex.base()); if (baseImg == null) return null; - NativeImage paletteImg = loadImage(tex.palette()); + NativeImage paletteImg = CelestialBodyTextureBakery.loadImage(tex.palette()); if (paletteImg == null) paletteImg = baseImg; int baseRow = data instanceof RockyPlanetData rp ? rp.paletteBaseRow() @@ -170,7 +172,7 @@ private static Identifier bakeBody(CelestialBodyData data, String key) { NativeImage coloredBase = PaletteColorMapper.colorTexture(baseImg, paletteImg, baseRow, true); if (tex.overlay() != null) { - NativeImage overlayImg = loadImage(tex.overlay()); + NativeImage overlayImg = CelestialBodyTextureBakery.loadImage(tex.overlay()); if (overlayImg != null) { int overlayRow = data instanceof RockyPlanetData rp ? rp.paletteOverlayRow() : (data instanceof GiantPlanetData gp ? gp.paletteOverlayRow() : 0); @@ -183,7 +185,7 @@ private static Identifier bakeBody(CelestialBodyData data, String key) { if (paletteImg != baseImg) paletteImg.close(); baseImg.close(); - return registerTexture(key, coloredBase); + return CelestialBodyTextureBakery.registerTexture(key, coloredBase); } public static float[] starColor(StarData star) { @@ -197,9 +199,9 @@ public static float[] starColor(StarData star) { @Nullable private static Identifier bakeSpecial(String key, SpecialCelestialBodyData special) { String filename = special.textureName() + ".png"; - NativeImage img = loadImage(filename); + NativeImage img = CelestialBodyTextureBakery.loadImage(filename); if (img == null) return null; - return registerTexture(key, img); + return CelestialBodyTextureBakery.registerTexture(key, img); } @Nullable @@ -211,17 +213,17 @@ private static Identifier bakeRing(CelestialBodyData data, String key) { }; if (ringFile == null) return null; - NativeImage ringImg = loadImage(ringFile); + NativeImage ringImg = CelestialBodyTextureBakery.loadImage(ringFile); if (ringImg == null) return null; - NativeImage paletteImg = loadImage("planet_giant_ring_color.png"); + NativeImage paletteImg = CelestialBodyTextureBakery.loadImage("planet_giant_ring_color.png"); if (paletteImg != null) { int ringPaletteRow = data instanceof RockyPlanetData rp ? rp.paletteBaseRow() : (data instanceof GiantPlanetData gp ? gp.paletteBaseRow() : 0); NativeImage colored = PaletteColorMapper.colorTexture(ringImg, paletteImg, ringPaletteRow, true); paletteImg.close(); ringImg.close(); - return registerTexture(key, colored); + return CelestialBodyTextureBakery.registerTexture(key, colored); } ringImg.close(); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/PaletteColorMapper.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/PaletteColorMapper.java index 148c241d83..b4a298c07f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/PaletteColorMapper.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/celestial/PaletteColorMapper.java @@ -57,17 +57,27 @@ private static boolean isBlackRow(NativeImage palette, int row) { private static int findSplitRow(NativeImage palette) { for (int row = 1; row < palette.getHeight() - 1; row++) { - if (isBlackRow(palette, row)) continue; + if (PaletteColorMapper.isBlackRow(palette, row)) continue; boolean hasAbove = false, hasBelow = false; - for (int r = 0; r < row; r++) { if (isBlackRow(palette, r)) { hasAbove = true; break; } } - for (int r = row + 1; r < palette.getHeight(); r++) { if (isBlackRow(palette, r)) { hasBelow = true; break; } } + for (int r = 0; r < row; r++) { + if (PaletteColorMapper.isBlackRow(palette, r)) { + hasAbove = true; + break; + } + } + for (int r = row + 1; r < palette.getHeight(); r++) { + if (PaletteColorMapper.isBlackRow(palette, r)) { + hasBelow = true; + break; + } + } if (hasAbove && hasBelow) return row; } return -1; } public static int[] getPaletteColors(NativeImage palette, int rowIndex, boolean isBase) { - int splitRow = findSplitRow(palette); + int splitRow = PaletteColorMapper.findSplitRow(palette); int start, end; // NativeImage 与色板 PNG 均以顶部为第 0 行;保持与 1.21 相同的自上而下行号,不进行 Y 翻转。 if (splitRow > 0) { @@ -78,13 +88,13 @@ public static int[] getPaletteColors(NativeImage palette, int rowIndex, boolean end = palette.getHeight(); } int validCount = 0; - for (int r = start; r < end; r++) { if (isBlackRow(palette, r)) validCount++; } + for (int r = start; r < end; r++) { if (PaletteColorMapper.isBlackRow(palette, r)) validCount++; } if (validCount == 0) return new int[0]; int targetRow = rowIndex % validCount; int found = 0; for (int r = start; r < end; r++) { - if (isBlackRow(palette, r)) { - if (found == targetRow) return extractRowColors(palette, r); + if (PaletteColorMapper.isBlackRow(palette, r)) { + if (found == targetRow) return PaletteColorMapper.extractRowColors(palette, r); found++; } } @@ -95,11 +105,11 @@ public static int[] getPaletteColors(NativeImage palette, int rowIndex, boolean * 使用色板为灰度源贴图着色,读取和写入均采用 ARGB 像素格式。 */ public static NativeImage colorTexture(NativeImage source, NativeImage palette, int paletteRow, boolean isBase) { - int[] paletteColors = getPaletteColors(palette, paletteRow, isBase); - if (paletteColors.length == 0) return copyGrayscale(source); + int[] paletteColors = PaletteColorMapper.getPaletteColors(palette, paletteRow, isBase); + if (paletteColors.length == 0) return PaletteColorMapper.copyGrayscale(source); - int[] refGrays = extractReferenceGrays(source); - if (refGrays.length == 0) return copyGrayscale(source); + int[] refGrays = PaletteColorMapper.extractReferenceGrays(source); + if (refGrays.length == 0) return PaletteColorMapper.copyGrayscale(source); Map grayToIndex = new HashMap<>(); int mapCount = Math.min(refGrays.length, paletteColors.length); @@ -120,9 +130,8 @@ public static NativeImage colorTexture(NativeImage source, NativeImage palette, if (red == 0 && green == 0 && blue == 0) continue; // 使用红色通道作为灰度参考值。 - int gray = red; - Integer idx = grayToIndex.get(gray); - if (idx == null) idx = findClosestGrayIndex(gray, refGrays); + Integer idx = grayToIndex.get(red); + if (idx == null) idx = PaletteColorMapper.findClosestGrayIndex(red, refGrays); idx = Math.clamp(idx, 0, paletteColors.length - 1); int pc = paletteColors[idx]; // 色板像素同样采用 ARGB 格式。 diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/CreativeCrateRenderState.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/CreativeCrateRenderState.java index e6f6e62864..e78a2ded65 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/CreativeCrateRenderState.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/CreativeCrateRenderState.java @@ -4,9 +4,10 @@ import lombok.Setter; import net.minecraft.client.renderer.blockentity.state.BlockEntityRenderState; import net.minecraft.client.renderer.entity.state.ItemClusterRenderState; +import org.jspecify.annotations.Nullable; @Getter @Setter public class CreativeCrateRenderState extends BlockEntityRenderState { - private ItemClusterRenderState item; + private @Nullable ItemClusterRenderState item; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/LaserRenderState.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/LaserRenderState.java index df32bbfb30..4f1430bf96 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/LaserRenderState.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/blockentity/state/LaserRenderState.java @@ -9,12 +9,13 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.resources.Identifier; import org.joml.Quaternionf; +import org.jspecify.annotations.Nullable; public class LaserRenderState extends CachedBlockEntityRenderState { public static final Identifier LASER_TEXTURE = AnvilCraft.of("laser/beam"); public static final Identifier SOLID_TEXTURE = AnvilCraft.of("laser/solid"); - public BaseLaserBlockEntity blockEntity; + public @Nullable BaseLaserBlockEntity blockEntity; public float length; public float offset; public int color; @@ -23,7 +24,15 @@ public class LaserRenderState extends CachedBlockEntityRenderState { public TextureAtlasSprite laserAtlasSprite; public TextureAtlasSprite solidAtlasSprite; + public LaserRenderState() { + TextureAtlas atlas = Minecraft.getInstance().getAtlasManager().getAtlasOrThrow(ModAtlasIds.LASER); + this.rotation = new Quaternionf(); + this.laserAtlasSprite = atlas.getSprite(LaserRenderState.LASER_TEXTURE); + this.solidAtlasSprite = atlas.getSprite(LaserRenderState.SOLID_TEXTURE); + } + public void extract(BaseLaserBlockEntity blockEntity) { + this.blockEntity = null; if (blockEntity.getIrradiateBlockPos() == null) return; float length = (float) (blockEntity .getIrradiateBlockPos() @@ -38,7 +47,7 @@ public void extract(BaseLaserBlockEntity blockEntity) { this.color = blockEntity.getLaserColor(); this.laserLevel = blockEntity.getLaserLevel(); this.rotation = blockEntity.getFacing().getRotation(); - this.laserAtlasSprite = atlas.getSprite(LASER_TEXTURE); - this.solidAtlasSprite = atlas.getSprite(SOLID_TEXTURE); + this.laserAtlasSprite = atlas.getSprite(LaserRenderState.LASER_TEXTURE); + this.solidAtlasSprite = atlas.getSprite(LaserRenderState.SOLID_TEXTURE); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/CauldronOutletRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/CauldronOutletRenderer.java index 0643305110..ece4e44940 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/CauldronOutletRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/CauldronOutletRenderer.java @@ -132,7 +132,7 @@ public void submit( this.model, Unit.INSTANCE, pose, - TEXTURE, + CauldronOutletRenderer.TEXTURE, state.lightCoords, OverlayTexture.NO_OVERLAY, state.outlineColor, @@ -140,4 +140,4 @@ public void submit( ); pose.popPose(); } -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/FluidTankMinecartRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/FluidTankMinecartRenderer.java index 4c8960b378..cca29c8a4c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/FluidTankMinecartRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/FluidTankMinecartRenderer.java @@ -16,7 +16,6 @@ import net.minecraft.util.Mth; import net.neoforged.neoforge.fluids.FluidStack; import net.neoforged.neoforge.transfer.fluid.FluidResource; -import org.jspecify.annotations.Nullable; /// 在储罐矿车上渲染出罐内流体 public class FluidTankMinecartRenderer @@ -67,19 +66,19 @@ protected void submitMinecartContents( var tintSource = model.fluidTintSource(); int tintColor = tintSource != null ? tintSource.colorAsStack(resource.toStack(1)) : -1; TextureAtlasSprite sprite = model.stillMaterial().sprite(); - float maxY = TANK_W + (1 - 2 * TANK_W) * state.getFill(); + float maxY = FluidTankMinecartRenderer.TANK_W + (1 - 2 * FluidTankMinecartRenderer.TANK_W) * state.getFill(); collector.submitCustomGeometry( poseStack, FluidTankItemRenderState.FLUID_RENDER_TYPE, (pose, buffer) -> FluidRenderHelper.INSTANCE.renderFluidBox( sprite, resource, - TANK_W, - TANK_W, - TANK_W, - 1 - TANK_W, + FluidTankMinecartRenderer.TANK_W, + FluidTankMinecartRenderer.TANK_W, + FluidTankMinecartRenderer.TANK_W, + 1 - FluidTankMinecartRenderer.TANK_W, maxY, - 1 - TANK_W, + 1 - FluidTankMinecartRenderer.TANK_W, tintColor, buffer, pose, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/IonocraftRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/IonocraftRenderer.java index e61de11659..6902f964b2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/IonocraftRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/IonocraftRenderer.java @@ -36,7 +36,7 @@ public void submit(IonocraftRenderState state, PoseStack poseStack, SubmitNodeCo this.model, state, poseStack, - TEXTURE, + IonocraftRenderer.TEXTURE, state.lightCoords, OverlayTexture.NO_OVERLAY, state.outlineColor, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/MagnetizedNodeEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/MagnetizedNodeEntityRenderer.java index 911ebbea32..25734c3cc9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/MagnetizedNodeEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/MagnetizedNodeEntityRenderer.java @@ -47,7 +47,7 @@ public void submit( this.model, state, pose, - TEXTURE, + MagnetizedNodeEntityRenderer.TEXTURE, state.lightCoords, OverlayTexture.NO_OVERLAY, state.outlineColor, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SlidingBlockRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SlidingBlockRenderer.java index d69d2ad933..d4b3061139 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SlidingBlockRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SlidingBlockRenderer.java @@ -54,7 +54,13 @@ public void extractRenderState(SlidingBlockEntity entity, SlidingBlockRenderStat .getRenderer(be); if (renderer == null) return; beState = renderer.createRenderState(); - renderer.extractRenderState(be, beState, partialTicks, minecraft.getCameraEntity().position(), null); + renderer.extractRenderState( + be, + beState, + partialTicks, + minecraft.gameRenderer.getMainCamera().position(), + null + ); } state.getPairs().put(info.offset(), new SlidingBlockRenderState.RenderPair(moving, beState)); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SpectralProjectileRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SpectralProjectileRenderer.java index d22116126d..613180e14c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SpectralProjectileRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/SpectralProjectileRenderer.java @@ -30,7 +30,7 @@ public SpectralProjectileRenderer(EntityRendererProvider.Context ctx) { @Override public Identifier getTextureLocation(SpectralProjectileRenderState state) { - return ARROW_LOCATION; + return SpectralProjectileRenderer.ARROW_LOCATION; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/WeaponBeamRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/WeaponBeamRenderer.java index 2c58218a3e..bb65a38032 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/WeaponBeamRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/WeaponBeamRenderer.java @@ -49,13 +49,13 @@ public void extractRenderState(WeaponBeamEntity entity, WeaponBeamRenderState st super.extractRenderState(entity, state, partialTick); state.setVisible(false); state.setCompensateViewBob(false); - if (isObsoleteContinuousBeam(entity) || !isOwnerFiringContinuousBeam(entity)) return; + if (WeaponBeamRenderer.isObsoleteContinuousBeam(entity) || !WeaponBeamRenderer.isOwnerFiringContinuousBeam(entity)) return; Vec3 origin = entity.getPosition(partialTick); Vec3 originOffset = Vec3.ZERO; Vec3 endOffset = entity.getEndOffset(); if (entity.getStyle() == WeaponBeamEntity.CORRUPTED || entity.getStyle() == WeaponBeamEntity.LASER) { - LiveBeam liveBeam = resolveLiveBeam(entity, partialTick); + LiveBeam liveBeam = WeaponBeamRenderer.resolveLiveBeam(entity, partialTick); if (liveBeam != null) { originOffset = liveBeam.start().subtract(origin); endOffset = liveBeam.end().subtract(liveBeam.start()); @@ -75,7 +75,7 @@ public void extractRenderState(WeaponBeamEntity entity, WeaponBeamRenderState st && minecraft.options.bobView().get() ); if (entity.getStyle() == WeaponBeamEntity.LASER) { - state.setLaser(createLaserState(endOffset, entity.getStrength())); + state.setLaser(WeaponBeamRenderer.createLaserState(endOffset, entity.getStrength())); } else { state.setLaser(null); } @@ -103,7 +103,7 @@ public void submit( if (!state.isVisible()) return; final Vec3 end = state.getEndOffset(); ViewBobCompensation compensation = state.isCompensateViewBob() - ? createViewBobCompensation(camera) + ? WeaponBeamRenderer.createViewBobCompensation(camera) : null; pose.pushPose(); @@ -113,7 +113,7 @@ public void submit( } pose.translate(state.getOriginOffset().x, state.getOriginOffset().y, state.getOriginOffset().z); if (state.getStyle() == WeaponBeamEntity.CORRUPTED) { - rotateLocalYTo(end, pose); + WeaponBeamRenderer.rotateLocalYTo(end, pose); pose.scale(0.5F, 1.0F, 0.5F); collector.submitCustomGeometry( pose, @@ -125,10 +125,10 @@ public void submit( ) ); } else if (state.getStyle() == WeaponBeamEntity.LASER) { - rotateLocalYTo(end, pose); + WeaponBeamRenderer.rotateLocalYTo(end, pose); if (state.getLaser() != null) LaserCompiler.submit(pose, state.getLaser(), collector, false); } else { - submitTeslaArc(state, end, pose, collector, camera); + WeaponBeamRenderer.submitTeslaArc(state, end, pose, collector, camera); } pose.popPose(); super.submit(state, pose, collector, camera); @@ -136,7 +136,7 @@ public void submit( private static ViewBobCompensation createViewBobCompensation(CameraRenderState camera) { float phase = camera.entityRenderState.backwardsInterpolatedWalkDistance; - float bob = camera.entityRenderState.bob * VIEW_BOB_COMPENSATION; + float bob = camera.entityRenderState.bob * WeaponBeamRenderer.VIEW_BOB_COMPENSATION; float translateX = Mth.sin(phase * (float) Math.PI) * bob * 0.5F; float translateY = -Math.abs(Mth.cos(phase * (float) Math.PI) * bob); float rotateZ = Mth.sin(phase * (float) Math.PI) * bob * 3.0F; @@ -183,10 +183,10 @@ private static void submitTeslaArc( ModRenderTypes.LIGHTNING, (last, consumer) -> { Matrix4f matrix = last.pose(); - vertex(consumer, matrix, side.reverse(), 0.0F, 0.0F); - vertex(consumer, matrix, end.subtract(side), 1.0F, 0.0F); - vertex(consumer, matrix, end.add(side), 1.0F, 1.0F); - vertex(consumer, matrix, side, 0.0F, 1.0F); + WeaponBeamRenderer.vertex(consumer, matrix, side.reverse(), 0.0F, 0.0F); + WeaponBeamRenderer.vertex(consumer, matrix, end.subtract(side), 1.0F, 0.0F); + WeaponBeamRenderer.vertex(consumer, matrix, end.add(side), 1.0F, 1.0F); + WeaponBeamRenderer.vertex(consumer, matrix, side, 0.0F, 1.0F); } ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/model/MagnetizedNodeModel.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/model/MagnetizedNodeModel.java index 9947ed459f..9a6803e261 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/model/MagnetizedNodeModel.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/entity/model/MagnetizedNodeModel.java @@ -47,7 +47,7 @@ public class MagnetizedNodeModel extends Model { public MagnetizedNodeModel(ModelPart root) { super(root, RenderTypes::entityTranslucent); - this.rotating = ROTATING.bake(root); + this.rotating = MagnetizedNodeModel.ROTATING.bake(root); } public static LayerDefinition createBodyLayer() { diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/BaseFluidTankItemRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/BaseFluidTankItemRenderer.java index 3373616097..649074a451 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/BaseFluidTankItemRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/BaseFluidTankItemRenderer.java @@ -50,7 +50,7 @@ protected void submitShell( BlockAndTintGetter.EMPTY, BlockPos.ZERO, this.shellState, - RandomSource.create(MODEL_SEED), + RandomSource.create(BaseFluidTankItemRenderer.MODEL_SEED), this.shellRenderState.setupModel(new Matrix4f(), false) ); this.shellModel = model; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/CrabClawItemInHandRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/CrabClawItemInHandRenderer.java index dc51e2f983..656cf868f1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/CrabClawItemInHandRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/CrabClawItemInHandRenderer.java @@ -130,7 +130,7 @@ public boolean render( } Minecraft mc = Minecraft.getInstance(); List all = mc.getModelManager() - .getStandaloneModel(isBlockItem ? HOLDING_BLOCK : HOLDING_ITEM) + .getStandaloneModel(isBlockItem ? CrabClawItemInHandRenderer.HOLDING_BLOCK : CrabClawItemInHandRenderer.HOLDING_ITEM) .getAll(); collector.submitItem( poseStack, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ExtraItemDisplayRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ExtraItemDisplayRenderer.java index 80d1a129e8..a0f01a5611 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ExtraItemDisplayRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ExtraItemDisplayRenderer.java @@ -5,7 +5,6 @@ import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.renderer.SubmitNodeCollector; import net.minecraft.client.renderer.item.ItemModelResolver; -import net.minecraft.client.renderer.item.ItemStackRenderState; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.LivingEntity; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/FluidTankItemRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/FluidTankItemRenderer.java index f181fbf368..252c910bd4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/FluidTankItemRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/FluidTankItemRenderer.java @@ -61,19 +61,19 @@ public void submit( var tintSource = model.fluidTintSource(); int tintColor = tintSource != null ? tintSource.colorAsStack(resource.toStack(1)) : -1; TextureAtlasSprite sprite = model.stillMaterial().sprite(); - float maxY = TANK_W + (1 - 2 * TANK_W) * argument.getFill(); + float maxY = FluidTankItemRenderer.TANK_W + (1 - 2 * FluidTankItemRenderer.TANK_W) * argument.getFill(); collector.submitCustomGeometry( poseStack, FluidTankItemRenderState.FLUID_RENDER_TYPE, (pose, buffer) -> FluidRenderHelper.INSTANCE.renderFluidBox( sprite, resource, - TANK_W, - TANK_W, - TANK_W, - 1 - TANK_W, + FluidTankItemRenderer.TANK_W, + FluidTankItemRenderer.TANK_W, + FluidTankItemRenderer.TANK_W, + 1 - FluidTankItemRenderer.TANK_W, maxY, - 1 - TANK_W, + 1 - FluidTankItemRenderer.TANK_W, tintColor, buffer, pose, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ItemUseAnimationTransform.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ItemUseAnimationTransform.java index 00eb00599b..f2d8c7eca0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ItemUseAnimationTransform.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/ItemUseAnimationTransform.java @@ -21,11 +21,11 @@ public static boolean applyCrossbowCharge( float equipProgress, int chargeTicks ) { - if (!isUsingArm(player, arm)) return false; + if (!ItemUseAnimationTransform.isUsingArm(player, arm)) return false; int direction = arm == HumanoidArm.RIGHT ? 1 : -1; // 1.21.1 只对原版弩应用装填矩阵,此处为普通物品复用同一套变换。 - applyItemArmTransform(poseStack, direction, equipProgress); + ItemUseAnimationTransform.applyItemArmTransform(poseStack, direction, equipProgress); poseStack.translate(direction * -0.4785682F, -0.094387F, 0.05731531F); poseStack.mulPose(Axis.XP.rotationDegrees(-11.935F)); poseStack.mulPose(Axis.YP.rotationDegrees(direction * 65.3F)); @@ -51,11 +51,11 @@ public static boolean applySwordBlock( HumanoidArm arm, float equipProgress ) { - if (!isUsingArm(player, arm)) return false; + if (!ItemUseAnimationTransform.isUsingArm(player, arm)) return false; int direction = arm == HumanoidArm.RIGHT ? 1 : -1; // 复用旧版举剑格挡的第一人称矩阵。 - applyItemArmTransform(poseStack, direction, equipProgress); + ItemUseAnimationTransform.applyItemArmTransform(poseStack, direction, equipProgress); poseStack.translate(direction * -0.14142136F, 0.08F, 0.14142136F); poseStack.mulPose(Axis.XP.rotationDegrees(-102.25F)); poseStack.mulPose(Axis.YP.rotationDegrees(direction * 13.365F)); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/LargeFluidTankItemRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/LargeFluidTankItemRenderer.java index d274c78d66..e3db00c828 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/LargeFluidTankItemRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/LargeFluidTankItemRenderer.java @@ -84,7 +84,7 @@ public void submit( ) { this.submitShell(poseStack, collector, lightCoords, overlayCoords, outlineColor); if (argument == null) return; - float height = 3 - 2 * TANK_W; + float height = 3 - 2 * LargeFluidTankItemRenderer.TANK_W; for (FluidTankItemRenderState.Layer layer : argument.getLayers()) { FluidResource resource = layer.resource(); FluidModel model = FluidRenderHelper.getModel( @@ -94,20 +94,20 @@ public void submit( var tintSource = model.fluidTintSource(); int tintColor = tintSource != null ? tintSource.colorAsStack(resource.toStack(1)) : -1; TextureAtlasSprite sprite = model.stillMaterial().sprite(); - float minY = TANK_W - 1 + layer.bottom() * height; - float maxY = TANK_W - 1 + layer.top() * height; + float minY = LargeFluidTankItemRenderer.TANK_W - 1 + layer.bottom() * height; + float maxY = LargeFluidTankItemRenderer.TANK_W - 1 + layer.top() * height; collector.submitCustomGeometry( poseStack, FluidTankItemRenderState.FLUID_RENDER_TYPE, (pose, buffer) -> FluidRenderHelper.INSTANCE.renderFluidBox( sprite, resource, - TANK_W - 1, + LargeFluidTankItemRenderer.TANK_W - 1, minY, - TANK_W - 1, - 2 - TANK_W, + LargeFluidTankItemRenderer.TANK_W - 1, + 2 - LargeFluidTankItemRenderer.TANK_W, maxY, - 2 - TANK_W, + 2 - LargeFluidTankItemRenderer.TANK_W, tintColor, buffer, pose, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralSlingshotRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralSlingshotRenderer.java index 439ef2b43f..3fbc0684bd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralSlingshotRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralSlingshotRenderer.java @@ -12,6 +12,7 @@ import net.minecraft.client.renderer.special.SpecialModelRenderer; import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ChargedProjectiles; import org.joml.Vector3fc; import org.jspecify.annotations.Nullable; @@ -27,11 +28,12 @@ public SpectralSlingshotRenderer(ItemModelResolver resolver) { @Override public @Nullable SpectralRenderState extractArgument(ItemStack stack) { if (!stack.is(ModItems.SPECTRAL_WEAPON_LAUNCHER)) return null; - if (!stack.has(DataComponents.CHARGED_PROJECTILES)) return null; + ChargedProjectiles chargedProjectiles = stack.get(DataComponents.CHARGED_PROJECTILES); + if (chargedProjectiles == null || chargedProjectiles.itemCopies().isEmpty()) return null; SpectralRenderState state = new SpectralRenderState(); state.setSelf(FeatureRendererSupport.initialize(stack, this.resolver)); state.setAmmo(FeatureRendererSupport.initialize( - stack.get(DataComponents.CHARGED_PROJECTILES).itemCopies().getFirst(), + chargedProjectiles.itemCopies().getFirst(), this.resolver )); return state; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralWeaponLauncherRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralWeaponLauncherRenderer.java index 78c3ffab3f..a7c0f46665 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralWeaponLauncherRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/item/SpectralWeaponLauncherRenderer.java @@ -12,6 +12,7 @@ import net.minecraft.client.renderer.special.SpecialModelRenderer; import net.minecraft.core.component.DataComponents; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.ChargedProjectiles; import org.joml.Vector3fc; import org.jspecify.annotations.Nullable; @@ -27,11 +28,12 @@ public SpectralWeaponLauncherRenderer(ItemModelResolver resolver) { @Override public @Nullable SpectralRenderState extractArgument(ItemStack stack) { if (!stack.is(ModItems.SPECTRAL_WEAPON_LAUNCHER)) return null; - if (!stack.has(DataComponents.CHARGED_PROJECTILES)) return null; + ChargedProjectiles chargedProjectiles = stack.get(DataComponents.CHARGED_PROJECTILES); + if (chargedProjectiles == null || chargedProjectiles.itemCopies().isEmpty()) return null; SpectralRenderState state = new SpectralRenderState(); state.setSelf(FeatureRendererSupport.initialize(stack, this.resolver)); state.setAmmo(FeatureRendererSupport.initialize( - stack.get(DataComponents.CHARGED_PROJECTILES).itemCopies().getFirst(), + chargedProjectiles.itemCopies().getFirst(), this.resolver )); return state; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/CachedLaserBlockEntityRenderer.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/CachedLaserBlockEntityRenderer.java index 0d9d26e9c7..f078b757cf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/CachedLaserBlockEntityRenderer.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/CachedLaserBlockEntityRenderer.java @@ -2,7 +2,6 @@ import com.mojang.blaze3d.vertex.PoseStack; import dev.anvilcraft.lib.v2.rendering.cachedber.renderer.CachedBlockEntityRenderer; -import dev.dubhe.anvilcraft.AnvilCraft; import dev.dubhe.anvilcraft.block.entity.BaseLaserBlockEntity; import dev.dubhe.anvilcraft.client.AnvilCraftClient; import dev.dubhe.anvilcraft.client.renderer.RenderState; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/LaserCompiler.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/LaserCompiler.java index ffaa259320..1e60e8fc35 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/LaserCompiler.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/laser/LaserCompiler.java @@ -11,18 +11,18 @@ public class LaserCompiler { public static final float[] LASER_WIDTH; public static final float PIXEL = 1 / 16F; - public static final float HALF_PIXEL = PIXEL / 2F; + public static final float HALF_PIXEL = LaserCompiler.PIXEL / 2F; static { float[] array = new float[65]; for (int i = 1; i <= 64; i++) { - array[i] = (float) Math.sqrt(i) / 2F * PIXEL; + array[i] = (float) Math.sqrt(i) / 2F * LaserCompiler.PIXEL; } LASER_WIDTH = array; } public static float laserWidth(LaserRenderState state) { - return LASER_WIDTH[Math.clamp(state.laserLevel, 1, 64)] + 0.001F; + return LaserCompiler.LASER_WIDTH[Math.clamp(state.laserLevel, 1, 64)] + 0.001F; } public static void submit( @@ -32,11 +32,11 @@ public static void submit( boolean bloomed ) { if (state.laserLevel <= 0) return; - float width = laserWidth(state); + float width = LaserCompiler.laserWidth(state); nodeCollector.submitCustomGeometry( poseStack, ModRenderTypes.LASER_SOLID, - (pose, buffer) -> renderBox( + (pose, buffer) -> LaserCompiler.renderBox( buffer, pose, -width, @@ -54,15 +54,15 @@ public static void submit( poseStack, bloomed ? ModRenderTypes.LASER_TRANSLUCENT_BLOOM : ModRenderTypes.LASER_TRANSLUCENT, ((pose, buffer) -> { - float outerWidth = width + HALF_PIXEL; - renderBox( + float outerWidth = width + LaserCompiler.HALF_PIXEL; + LaserCompiler.renderBox( buffer, pose, -outerWidth, -state.offset, -outerWidth, outerWidth, - state.length + 0.5F + HALF_PIXEL, + state.length + 0.5F + LaserCompiler.HALF_PIXEL, outerWidth, ARGB.color(0.6f, state.color), state.laserAtlasSprite, @@ -84,12 +84,12 @@ private static void renderBox( TextureAtlasSprite sprite, TextureAtlasSprite endSprite ) { - renderQuadX(consumer, pose, maxX, maxX, minY, minZ, maxY, maxZ, color, sprite); - renderQuadX(consumer, pose, minX, minX, minY, maxZ, maxY, minZ, color, sprite); - renderQuadY(consumer, pose, maxY, maxY, minX, minZ, maxX, maxZ, ARGB.color(0.35f, color), endSprite); + LaserCompiler.renderQuadX(consumer, pose, maxX, maxX, minY, minZ, maxY, maxZ, color, sprite); + LaserCompiler.renderQuadX(consumer, pose, minX, minX, minY, maxZ, maxY, minZ, color, sprite); + LaserCompiler.renderQuadY(consumer, pose, maxY, maxY, minX, minZ, maxX, maxZ, ARGB.color(0.35f, color), endSprite); // renderQuadY(consumer, pose, minY, minY, maxX, minZ, minX, maxZ, color, endSprite); - renderQuadZ(consumer, pose, maxZ, maxZ, minX, maxY, maxX, minY, color, sprite); - renderQuadZ(consumer, pose, minZ, minZ, minX, minY, maxX, maxY, color, sprite); + LaserCompiler.renderQuadZ(consumer, pose, maxZ, maxZ, minX, maxY, maxX, minY, color, sprite); + LaserCompiler.renderQuadZ(consumer, pose, minZ, minZ, minX, minY, maxX, maxY, color, sprite); } private static void renderQuadX( @@ -104,10 +104,10 @@ private static void renderQuadX( int color, TextureAtlasSprite sprite ) { - addVertex(consumer, pose, minX, maxY, minZ, sprite.getU1(), sprite.getV1(), color); - addVertex(consumer, pose, minX, maxY, maxZ, sprite.getU0(), sprite.getV1(), color); - addVertex(consumer, pose, maxX, minY, maxZ, sprite.getU0(), sprite.getV0(), color); - addVertex(consumer, pose, maxX, minY, minZ, sprite.getU1(), sprite.getV0(), color); + LaserCompiler.addVertex(consumer, pose, minX, maxY, minZ, sprite.getU1(), sprite.getV1(), color); + LaserCompiler.addVertex(consumer, pose, minX, maxY, maxZ, sprite.getU0(), sprite.getV1(), color); + LaserCompiler.addVertex(consumer, pose, maxX, minY, maxZ, sprite.getU0(), sprite.getV0(), color); + LaserCompiler.addVertex(consumer, pose, maxX, minY, minZ, sprite.getU1(), sprite.getV0(), color); } private static void renderQuadY( @@ -122,10 +122,10 @@ private static void renderQuadY( int color, TextureAtlasSprite sprite ) { - addVertex(consumer, pose, minX, minY, minZ, sprite.getU1(), sprite.getV1(), color); - addVertex(consumer, pose, minX, minY, maxZ, sprite.getU0(), sprite.getV1(), color); - addVertex(consumer, pose, maxX, maxY, maxZ, sprite.getU0(), sprite.getV0(), color); - addVertex(consumer, pose, maxX, maxY, minZ, sprite.getU1(), sprite.getV0(), color); + LaserCompiler.addVertex(consumer, pose, minX, minY, minZ, sprite.getU1(), sprite.getV1(), color); + LaserCompiler.addVertex(consumer, pose, minX, minY, maxZ, sprite.getU0(), sprite.getV1(), color); + LaserCompiler.addVertex(consumer, pose, maxX, maxY, maxZ, sprite.getU0(), sprite.getV0(), color); + LaserCompiler.addVertex(consumer, pose, maxX, maxY, minZ, sprite.getU1(), sprite.getV0(), color); } private static void renderQuadZ( @@ -140,10 +140,10 @@ private static void renderQuadZ( int color, TextureAtlasSprite sprite ) { - addVertex(consumer, pose, minX, maxY, minZ, sprite.getU1(), sprite.getV1(), color); - addVertex(consumer, pose, maxX, maxY, minZ, sprite.getU0(), sprite.getV1(), color); - addVertex(consumer, pose, maxX, minY, maxZ, sprite.getU0(), sprite.getV0(), color); - addVertex(consumer, pose, minX, minY, maxZ, sprite.getU1(), sprite.getV0(), color); + LaserCompiler.addVertex(consumer, pose, minX, maxY, minZ, sprite.getU1(), sprite.getV1(), color); + LaserCompiler.addVertex(consumer, pose, maxX, maxY, minZ, sprite.getU0(), sprite.getV1(), color); + LaserCompiler.addVertex(consumer, pose, maxX, minY, maxZ, sprite.getU0(), sprite.getV0(), color); + LaserCompiler.addVertex(consumer, pose, minX, minY, maxZ, sprite.getU1(), sprite.getV0(), color); } private static void addVertex( diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/GravitationalLensPostEffect.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/GravitationalLensPostEffect.java index bf9df1d628..eedbe9b12d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/GravitationalLensPostEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/GravitationalLensPostEffect.java @@ -38,7 +38,9 @@ public class GravitationalLensPostEffect { private static final int BLACK_HOLES_LENS_PARAMS_OFFSET = 0; private static final int BLACK_HOLES_ARRAY_OFFSET = 16; private static final int BLACK_HOLE_STRIDE = 16; - private static final int BLACK_HOLES_SIZE = BLACK_HOLES_ARRAY_OFFSET + MAX_HOLES * BLACK_HOLE_STRIDE; + private static final int BLACK_HOLES_SIZE = + GravitationalLensPostEffect.BLACK_HOLES_ARRAY_OFFSET + + GravitationalLensPostEffect.MAX_HOLES * GravitationalLensPostEffect.BLACK_HOLE_STRIDE; @Getter private final RenderTarget lensOutputTarget = new TextureTarget("Gravitational Lens Result", 854, 480, false); @@ -46,19 +48,19 @@ public class GravitationalLensPostEffect { private final GpuBuffer transformUBO = this.device.createBuffer( () -> "GravitationalLensPostEffect TransformUBO", GpuBuffer.USAGE_COPY_DST | GpuBuffer.USAGE_UNIFORM, - UNIFORM_TRANSFORM_SIZE + GravitationalLensPostEffect.UNIFORM_TRANSFORM_SIZE ); @Getter private final GpuBuffer samplerInfoUBO = this.device.createBuffer( () -> "GravitationalLensPostEffect SamplerInfoUBO", GpuBuffer.USAGE_COPY_DST | GpuBuffer.USAGE_UNIFORM, - SAMPLER_INFO_SIZE + GravitationalLensPostEffect.SAMPLER_INFO_SIZE ); @Getter private final GpuBuffer blackHolesUBO = this.device.createBuffer( () -> "GravitationalLensPostEffect BlackHolesUBO", GpuBuffer.USAGE_COPY_DST | GpuBuffer.USAGE_UNIFORM, - BLACK_HOLES_SIZE + GravitationalLensPostEffect.BLACK_HOLES_SIZE ); private final GpuBuffer vertexBuffer = this.device.createBuffer( () -> "GravitationalLensPostEffect VertexBuffer", @@ -110,18 +112,18 @@ public void uploadBlackHoles( float eventHorizonRadius, float perspectiveScale ) { - int clampedCount = Math.min(Math.min(count, holes.size()), MAX_HOLES); + int clampedCount = Math.min(Math.min(count, holes.size()), GravitationalLensPostEffect.MAX_HOLES); try (MemoryStack stack = MemoryStack.stackPush()) { - ByteBuffer buffer = stack.calloc(BLACK_HOLES_SIZE); + ByteBuffer buffer = stack.calloc(GravitationalLensPostEffect.BLACK_HOLES_SIZE); - buffer.putFloat(BLACK_HOLES_LENS_PARAMS_OFFSET, clampedCount); - buffer.putFloat(BLACK_HOLES_LENS_PARAMS_OFFSET + 4, lensStrength); - buffer.putFloat(BLACK_HOLES_LENS_PARAMS_OFFSET + 8, eventHorizonRadius); - buffer.putFloat(BLACK_HOLES_LENS_PARAMS_OFFSET + 12, perspectiveScale); + buffer.putFloat(GravitationalLensPostEffect.BLACK_HOLES_LENS_PARAMS_OFFSET, clampedCount); + buffer.putFloat(GravitationalLensPostEffect.BLACK_HOLES_LENS_PARAMS_OFFSET + 4, lensStrength); + buffer.putFloat(GravitationalLensPostEffect.BLACK_HOLES_LENS_PARAMS_OFFSET + 8, eventHorizonRadius); + buffer.putFloat(GravitationalLensPostEffect.BLACK_HOLES_LENS_PARAMS_OFFSET + 12, perspectiveScale); for (int i = 0; i < clampedCount; i++) { HoleProjection hole = holes.get(i); - int offset = BLACK_HOLES_ARRAY_OFFSET + i * BLACK_HOLE_STRIDE; + int offset = GravitationalLensPostEffect.BLACK_HOLES_ARRAY_OFFSET + i * GravitationalLensPostEffect.BLACK_HOLE_STRIDE; buffer.putFloat(offset, hole.centerU); buffer.putFloat(offset + 4, hole.centerV); buffer.putFloat(offset + 8, hole.cameraDistance); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/SamplerInfoUbo.java b/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/SamplerInfoUbo.java index 7fb24339dc..0f6aac02ac 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/SamplerInfoUbo.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/renderer/post/SamplerInfoUbo.java @@ -25,7 +25,7 @@ class SamplerInfoUbo extends BufferObject { @Override protected BufferObjectLayoutDefinition getDefinition() { - return DEFINITION; + return SamplerInfoUbo.DEFINITION; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/rpc/StorageClientStub.java b/src/main/java/dev/dubhe/anvilcraft/client/rpc/StorageClientStub.java index 01c186496d..e367366639 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/rpc/StorageClientStub.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/rpc/StorageClientStub.java @@ -21,7 +21,7 @@ public static CompletableFuture loadMetadata(BlockPo return RPC.invoke( RpcTarget.server(), StorageServerStub::load, - playerId(), + StorageClientStub.playerId(), sourcePos.asLong() ); } @@ -30,7 +30,7 @@ public static void setOpen(BlockPos sourcePos, boolean opened) { RPC.call( RpcTarget.server(), StorageServerStub::setOpen, - playerId(), + StorageClientStub.playerId(), sourcePos.asLong(), opened ); @@ -40,7 +40,7 @@ public static CompletableFuture reorder(BlockPos sourcePos) { return RPC.invoke( RpcTarget.server(), StorageServerStub::reorder, - playerId(), + StorageClientStub.playerId(), sourcePos.asLong() ); } @@ -52,7 +52,7 @@ public static CompletableFuture sync( return RPC.invoke( RpcTarget.server(), StorageServerStub::sync, - playerId(), + StorageClientStub.playerId(), sourcePos.asLong(), slots ); @@ -67,7 +67,7 @@ public static CompletableFuture interact( return RPC.invoke( RpcTarget.server(), StorageServerStub::interact, - playerId(), + StorageClientStub.playerId(), sourcePos.asLong(), slot, button, @@ -79,7 +79,7 @@ public static CompletableFuture deposit(BlockPo return RPC.invoke( RpcTarget.server(), StorageServerStub::deposit, - playerId(), + StorageClientStub.playerId(), sourcePos.asLong(), all ); @@ -89,7 +89,7 @@ public static CompletableFuture take(BlockPos s return RPC.invoke( RpcTarget.server(), StorageServerStub::take, - playerId(), + StorageClientStub.playerId(), sourcePos.asLong() ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/AmuletSelectorSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/AmuletSelectorSupport.java index a154b2dcca..8349e4d18d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/AmuletSelectorSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/AmuletSelectorSupport.java @@ -25,36 +25,36 @@ public class AmuletSelectorSupport { private static @Nullable BoxContents contents = null; public static void render(GuiGraphicsExtractor graphics, int x, int y) { - int left = x - BACKGROUND_WIDTH / 2; - int top = y - BACKGROUND_HEIGHT - 5; + int left = x - AmuletSelectorSupport.BACKGROUND_WIDTH / 2; + int top = y - AmuletSelectorSupport.BACKGROUND_HEIGHT - 5; graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + AmuletSelectorSupport.BACKGROUND, left, top, 0, 0, - BACKGROUND_WIDTH, - BACKGROUND_HEIGHT, - BACKGROUND_WIDTH, - BACKGROUND_HEIGHT + AmuletSelectorSupport.BACKGROUND_WIDTH, + AmuletSelectorSupport.BACKGROUND_HEIGHT, + AmuletSelectorSupport.BACKGROUND_WIDTH, + AmuletSelectorSupport.BACKGROUND_HEIGHT ); - if (layout != null && contents != null) { - layout.extract(graphics, left, top, contents); + if (AmuletSelectorSupport.layout != null && AmuletSelectorSupport.contents != null) { + AmuletSelectorSupport.layout.extract(graphics, left, top, AmuletSelectorSupport.contents); } } public static boolean hasHoveringItem() { - return !currentHoveringItemStack.isEmpty(); + return !AmuletSelectorSupport.currentHoveringItemStack.isEmpty(); } public static void setCurrentHoveringItemStack(ItemStack itemStack) { - if (ItemStack.isSameItemSameComponents(currentHoveringItemStack, itemStack)) return; + if (ItemStack.isSameItemSameComponents(AmuletSelectorSupport.currentHoveringItemStack, itemStack)) return; AmuletSelectorSupport.currentHoveringItemStack = itemStack; if (itemStack.isEmpty()) { AmuletSelectorSupport.contents = null; AmuletSelectorSupport.layout = null; - maxSelection = -1; + AmuletSelectorSupport.maxSelection = -1; return; } @@ -63,58 +63,58 @@ public static void setCurrentHoveringItemStack(ItemStack itemStack) { AmuletSelectorSupport.contents = contents; if (contents.isEmpty()) { AmuletSelectorSupport.layout = Layout.EMPTY; - maxSelection = -1; - setCurrentSelectedIndex(-1); + AmuletSelectorSupport.maxSelection = -1; + AmuletSelectorSupport.setCurrentSelectedIndex(-1); } else { AmuletSelectorSupport.layout = Layout.layout(contents); - maxSelection = contents.getMaxSelection(); - setCurrentSelectedIndex(contents.selection()); + AmuletSelectorSupport.maxSelection = contents.getMaxSelection(); + AmuletSelectorSupport.setCurrentSelectedIndex(contents.selection()); } } public static void mouseScrolled(int amount) { - if (getCurrentSelectedIndex() == -1) return; + if (AmuletSelectorSupport.getCurrentSelectedIndex() == -1) return; if (amount > 0) { - next(); + AmuletSelectorSupport.next(); } else { if (amount < 0) { - previous(); + AmuletSelectorSupport.previous(); } } } public static void previous() { - selectDelta(-1); + AmuletSelectorSupport.selectDelta(-1); } public static void next() { - selectDelta(1); + AmuletSelectorSupport.selectDelta(1); } public static void selectDelta(int delta) { - int index = getCurrentSelectedIndex() + delta; + int index = AmuletSelectorSupport.getCurrentSelectedIndex() + delta; if (index < 0) { - index = maxSelection - 1; - } else if (index > maxSelection - 1) { + index = AmuletSelectorSupport.maxSelection - 1; + } else if (index > AmuletSelectorSupport.maxSelection - 1) { index = 0; } - setCurrentSelectedIndex(index); + AmuletSelectorSupport.setCurrentSelectedIndex(index); } private static int getCurrentSelectedIndex() { - if (contents == null) return -1; - return contents.selection(); + if (AmuletSelectorSupport.contents == null) return -1; + return AmuletSelectorSupport.contents.selection(); } private static void setCurrentSelectedIndex(int selection) { - if (!hasHoveringItem() || contents == null) return; - if (maxSelection <= 0) return; - selection = Math.clamp(selection, 0, Math.max(0, maxSelection - 1)); - if (contents.selection() == selection) return; - BoxContents.Mutable mutable = contents.mutable(); + if (!AmuletSelectorSupport.hasHoveringItem() || AmuletSelectorSupport.contents == null) return; + if (AmuletSelectorSupport.maxSelection <= 0) return; + selection = Math.clamp(selection, 0, Math.max(0, AmuletSelectorSupport.maxSelection - 1)); + if (AmuletSelectorSupport.contents.selection() == selection) return; + BoxContents.Mutable mutable = AmuletSelectorSupport.contents.mutable(); mutable.select(selection); - contents = mutable.immutable(); - currentHoveringItemStack.set(ModComponents.BOX_CONTENTS, contents); + AmuletSelectorSupport.contents = mutable.immutable(); + AmuletSelectorSupport.currentHoveringItemStack.set(ModComponents.BOX_CONTENTS, AmuletSelectorSupport.contents); } public enum Layout { @@ -157,10 +157,10 @@ public void extract(GuiGraphicsExtractor graphics, int x, int y, BoxContents con Matrix3x2fStack pose = graphics.pose(); pose.pushMatrix(); pose.translate(0, 0); - graphics.fill(x + 3, y + 3, x + 3 + 53, y + 3 + 53, COLOR_FIRST); + graphics.fill(x + 3, y + 3, x + 3 + 53, y + 3 + 53, Layout.COLOR_FIRST); this.extractTotem(graphics, x + 3, y + 3, content); - if (getCurrentSelectedIndex() == 0) { + if (AmuletSelectorSupport.getCurrentSelectedIndex() == 0) { this.renderSelectionBox(graphics, x + 3, y + 3, x + 3 + 53, y + 3 + 53); } pose.popMatrix(); @@ -188,10 +188,10 @@ public void extract(GuiGraphicsExtractor graphics, int x, int y, BoxContents con Matrix3x2fStack pose = graphics.pose(); pose.pushMatrix(); pose.translate(0, 0); - graphics.fill(x + 3, y + 3, x + 3 + 35, y + 3 + 53, COLOR_FIRST); + graphics.fill(x + 3, y + 3, x + 3 + 35, y + 3 + 53, Layout.COLOR_FIRST); this.extractTotem(graphics, x + 3, y + 3, content); - if (getCurrentSelectedIndex() == 0) { + if (AmuletSelectorSupport.getCurrentSelectedIndex() == 0) { this.renderSelectionBox(graphics, x + 3, y + 3, x + 3 + 35, y + 3 + 53); } pose.popMatrix(); @@ -219,11 +219,11 @@ public void extract(GuiGraphicsExtractor graphics, int x, int y, BoxContents con Matrix3x2fStack pose = graphics.pose(); pose.pushMatrix(); pose.translate(0, 0); - graphics.fill(x + 3, y + 3, x + 3 + 35, y + 3 + 53, COLOR_FIRST); - graphics.fill(x + 39, y + 3, x + 39 + 35, y + 3 + 53, COLOR_SECOND); + graphics.fill(x + 3, y + 3, x + 3 + 35, y + 3 + 53, Layout.COLOR_FIRST); + graphics.fill(x + 39, y + 3, x + 39 + 35, y + 3 + 53, Layout.COLOR_SECOND); this.extractTotem(graphics, x + 3, y + 3, content); - switch (getCurrentSelectedIndex()) { + switch (AmuletSelectorSupport.getCurrentSelectedIndex()) { case 0 -> this.renderSelectionBox(graphics, x + 3, y + 3, x + 3 + 35, y + 3 + 53); case 1 -> this.renderSelectionBox(graphics, x + 39, y + 3, x + 39 + 35, y + 3 + 53); default -> { @@ -272,11 +272,11 @@ void extractTotem(GuiGraphicsExtractor graphics, int x, int y, BoxContents conte ItemStack totem = totems.get(index++); int minX = x + i % 4 * 18; int minY = y + i / 4 * 18; - graphics.fill(minX, minY, minX + 17, minY + 17, COLOR_TOTEM); + graphics.fill(minX, minY, minX + 17, minY + 17, Layout.COLOR_TOTEM); graphics.fakeItem(totem, minX + 1, minY + 1); graphics.itemDecorations(Minecraft.getInstance().font, totem, minX + 1, minY + 1); - if (index + this.alreadyUsedIndexes - 1 != getCurrentSelectedIndex()) continue; + if (index + this.alreadyUsedIndexes - 1 != AmuletSelectorSupport.getCurrentSelectedIndex()) continue; this.renderSelectionBox(graphics, minX, minY, minX + 18, minY + 18); } } @@ -295,16 +295,16 @@ void renderSelectionBox(GuiGraphicsExtractor graphics, int minX, int minY, int m if (widthU != 0) { minX += 9; maxY += 9; - graphics.fill(minX, minY, minX + widthU, minY + 1, COLOR_SELECTION_BOX_FRAME); - graphics.fill(minX, maxY - 1, minX + widthU, maxY, COLOR_SELECTION_BOX_FRAME); + graphics.fill(minX, minY, minX + widthU, minY + 1, Layout.COLOR_SELECTION_BOX_FRAME); + graphics.fill(minX, maxY - 1, minX + widthU, maxY, Layout.COLOR_SELECTION_BOX_FRAME); minX -= 9; maxY -= 9; } if (heightV != 0) { minY += 9; maxX += 9; - graphics.fill(minX, minY, minX + 1, minY + heightV, COLOR_SELECTION_BOX_FRAME); - graphics.fill(maxX - 1, minY, maxX, minY + heightV, COLOR_SELECTION_BOX_FRAME); + graphics.fill(minX, minY, minX + 1, minY + heightV, Layout.COLOR_SELECTION_BOX_FRAME); + graphics.fill(maxX - 1, minY, maxX, minY + heightV, Layout.COLOR_SELECTION_BOX_FRAME); minY -= 9; maxX -= 9; } @@ -314,24 +314,24 @@ void renderSelectionBox(GuiGraphicsExtractor graphics, int minX, int minY, int m public static Layout layout(BoxContents content) { if (content.isEmpty()) { - return EMPTY; + return Layout.EMPTY; } if (content.isAmuletEmpty()) { - return NO_AMULET; + return Layout.NO_AMULET; } List amulets = content.amulets(); - boolean firstBigAmulet = amulets.getFirst().has(ModComponents.AMULET) - && amulets.getFirst().get(ModComponents.AMULET).getWeight() > 6; - boolean firstSmallAmulet = amulets.getFirst().has(ModComponents.AMULET) - && amulets.getFirst().get(ModComponents.AMULET).getWeight() <= 6; + var firstAmulet = amulets.getFirst().get(ModComponents.AMULET); + if (firstAmulet == null) return Layout.EMPTY; + boolean firstBigAmulet = firstAmulet.getWeight() > 6; + boolean firstSmallAmulet = firstAmulet.getWeight() <= 6; if (firstBigAmulet) { - return BIG_AMULET_1; + return Layout.BIG_AMULET_1; } if (firstSmallAmulet) { if (amulets.size() == 1) { - return SMALL_AMULET_1; + return Layout.SMALL_AMULET_1; } - return SMALL_AMULET_2; + return Layout.SMALL_AMULET_2; } return Layout.EMPTY; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/FeatureRendererSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/FeatureRendererSupport.java index d16be3065e..aeac000638 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/FeatureRendererSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/FeatureRendererSupport.java @@ -25,7 +25,7 @@ public static BlockStateModelTessellateState createTessellation( StandaloneModelKey key, boolean lighting ) { - return createTessellation( + return FeatureRendererSupport.createTessellation( key, false, lighting @@ -41,14 +41,16 @@ public static BlockStateModelTessellateState createTessellation( } public static BlockModelRenderState initialize(StandaloneModelKey standalone, BlockEntity be) { - return initialize(standalone, be, false); + return FeatureRendererSupport.initialize(standalone, be, false); } public static BlockModelRenderState initialize(BlockState blockState, BlockEntity be) { BlockModelRenderState state = new BlockModelRenderState(); Minecraft mc = Minecraft.getInstance(); + var level = mc.level; + if (level == null) return state; mc.getModelManager().getBlockStateModelSet().get(blockState).collectParts( - mc.level, + level, be.getBlockPos(), blockState, RandomSource.create(), @@ -67,13 +69,15 @@ public static BlockModelRenderState initialize( ) { BlockModelRenderState state = new BlockModelRenderState(); Minecraft mc = Minecraft.getInstance(); + var level = mc.level; + if (level == null) return state; BlockStateModel model = mc.getModelManager().getStandaloneModel(standalone); if (model == null) { - LOGGER.warn("Standalone model '{}' is null, returning empty render state", standalone); + FeatureRendererSupport.LOGGER.warn("Standalone model '{}' is null, returning empty render state", standalone); return state; } model.collectParts( - mc.level, + level, be.getBlockPos(), be.getBlockState(), RandomSource.create(), diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/FilterSelectorSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/FilterSelectorSupport.java index c74104b8a6..b235631361 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/FilterSelectorSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/FilterSelectorSupport.java @@ -13,49 +13,49 @@ public class FilterSelectorSupport { private static final int COLS = 6; private static final int SLOT_SIZE = 18; private static final int PADDING = 3; - private static final int BG_WIDTH = COLS * SLOT_SIZE + PADDING * 2; - private static final int BG_HEIGHT = 3 * SLOT_SIZE + PADDING * 2 + 2; + private static final int BG_WIDTH = FilterSelectorSupport.COLS * FilterSelectorSupport.SLOT_SIZE + FilterSelectorSupport.PADDING * 2; + private static final int BG_HEIGHT = 3 * FilterSelectorSupport.SLOT_SIZE + FilterSelectorSupport.PADDING * 2 + 2; private static ItemStack currentFilter = ItemStack.EMPTY; @Nullable private static FilterContent content = null; public static void setCurrentFilterStack(ItemStack filter) { - if (ItemStack.isSameItemSameComponents(currentFilter, filter)) return; - currentFilter = filter; + if (ItemStack.isSameItemSameComponents(FilterSelectorSupport.currentFilter, filter)) return; + FilterSelectorSupport.currentFilter = filter; if (filter.isEmpty()) { - content = null; + FilterSelectorSupport.content = null; return; } - content = filter.getOrDefault(ModComponents.FILTER_CONTENT, new FilterContent()); + FilterSelectorSupport.content = filter.getOrDefault(ModComponents.FILTER_CONTENT, new FilterContent()); } private static final int CROP_U = 58; private static final int CROP_V = 14; - private static final int SLOT_OFFSET_X = 62 - CROP_U; - private static final int SLOT_OFFSET_Y = 17 - CROP_V + 1; + private static final int SLOT_OFFSET_X = 62 - FilterSelectorSupport.CROP_U; + private static final int SLOT_OFFSET_Y = 17 - FilterSelectorSupport.CROP_V + 1; public static void render(GuiGraphicsExtractor graphics, int x, int y) { - if (content == null) return; - int left = x - BG_WIDTH / 2; - int top = y - BG_HEIGHT - 3; + if (FilterSelectorSupport.content == null) return; + int left = x - FilterSelectorSupport.BG_WIDTH / 2; + int top = y - FilterSelectorSupport.BG_HEIGHT - 3; graphics.blit( RenderPipelines.GUI_TEXTURED, SharedTextures.bg("misc", "filter"), left, top, - CROP_U, CROP_V, - BG_WIDTH, BG_HEIGHT, - BG_WIDTH, BG_HEIGHT, + FilterSelectorSupport.CROP_U, FilterSelectorSupport.CROP_V, + FilterSelectorSupport.BG_WIDTH, FilterSelectorSupport.BG_HEIGHT, + FilterSelectorSupport.BG_WIDTH, FilterSelectorSupport.BG_HEIGHT, 256, 256 ); - for (int i = 0; i < content.list().size(); i++) { - ItemStack stack = content.list().get(i); - int row = i / COLS; - int col = i % COLS; - int itemX = left + SLOT_OFFSET_X + col * SLOT_SIZE; - int itemY = top + SLOT_OFFSET_Y + row * SLOT_SIZE; + for (int i = 0; i < FilterSelectorSupport.content.list().size(); i++) { + ItemStack stack = FilterSelectorSupport.content.list().get(i); + int row = i / FilterSelectorSupport.COLS; + int col = i % FilterSelectorSupport.COLS; + int itemX = left + FilterSelectorSupport.SLOT_OFFSET_X + col * FilterSelectorSupport.SLOT_SIZE; + int itemY = top + FilterSelectorSupport.SLOT_OFFSET_Y + row * FilterSelectorSupport.SLOT_SIZE; if (!stack.isEmpty()) { graphics.fakeItem(stack, itemX, itemY); diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/FluidRenderHelper.java b/src/main/java/dev/dubhe/anvilcraft/client/support/FluidRenderHelper.java index 8675fa3c61..bd04aa4300 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/FluidRenderHelper.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/FluidRenderHelper.java @@ -77,18 +77,18 @@ public void renderFluidBox( boolean positive = side.getAxisDirection() == Direction.AxisDirection.POSITIVE; if (side.getAxis().isHorizontal()) { if (side.getAxis() == Direction.Axis.X) { - renderStillTiledFace( + FluidRenderHelper.renderStillTiledFace( side, minZ, minY, maxZ, maxY, positive ? maxX : minX, builder, pose, light, layerColor, sprite ); } else { - renderStillTiledFace( + FluidRenderHelper.renderStillTiledFace( side, minX, minY, maxX, maxY, positive ? maxZ : minZ, builder, pose, light, layerColor, sprite ); } } else { - renderStillTiledFace( + FluidRenderHelper.renderStillTiledFace( side, minX, minZ, maxX, maxZ, positive ? maxY : minY, builder, pose, light, layerColor, sprite ); @@ -101,7 +101,7 @@ public static void renderStillTiledFace( Direction dir, float left, float down, float right, float up, float depth, VertexConsumer builder, PoseStack.Pose pose, int light, int color, TextureAtlasSprite texture ) { - renderTiledFace(dir, left, down, right, up, depth, builder, pose, light, color, texture, 1); + FluidRenderHelper.renderTiledFace(dir, left, down, right, up, depth, builder, pose, light, color, texture, 1); } public static void renderTiledFace( @@ -164,21 +164,21 @@ public static void renderTiledFace( if (horizontal) { if (x) { - putVertex(builder, pose, depth, y2, positive ? x2 : x1, color, u1, v1, dir, light); - putVertex(builder, pose, depth, y1, positive ? x2 : x1, color, u1, v2, dir, light); - putVertex(builder, pose, depth, y1, positive ? x1 : x2, color, u2, v2, dir, light); - putVertex(builder, pose, depth, y2, positive ? x1 : x2, color, u2, v1, dir, light); + FluidRenderHelper.putVertex(builder, pose, depth, y2, positive ? x2 : x1, color, u1, v1, dir, light); + FluidRenderHelper.putVertex(builder, pose, depth, y1, positive ? x2 : x1, color, u1, v2, dir, light); + FluidRenderHelper.putVertex(builder, pose, depth, y1, positive ? x1 : x2, color, u2, v2, dir, light); + FluidRenderHelper.putVertex(builder, pose, depth, y2, positive ? x1 : x2, color, u2, v1, dir, light); } else { - putVertex(builder, pose, positive ? x1 : x2, y2, depth, color, u1, v1, dir, light); - putVertex(builder, pose, positive ? x1 : x2, y1, depth, color, u1, v2, dir, light); - putVertex(builder, pose, positive ? x2 : x1, y1, depth, color, u2, v2, dir, light); - putVertex(builder, pose, positive ? x2 : x1, y2, depth, color, u2, v1, dir, light); + FluidRenderHelper.putVertex(builder, pose, positive ? x1 : x2, y2, depth, color, u1, v1, dir, light); + FluidRenderHelper.putVertex(builder, pose, positive ? x1 : x2, y1, depth, color, u1, v2, dir, light); + FluidRenderHelper.putVertex(builder, pose, positive ? x2 : x1, y1, depth, color, u2, v2, dir, light); + FluidRenderHelper.putVertex(builder, pose, positive ? x2 : x1, y2, depth, color, u2, v1, dir, light); } } else { - putVertex(builder, pose, x1, depth, positive ? y1 : y2, color, u1, v1, dir, light); - putVertex(builder, pose, x1, depth, positive ? y2 : y1, color, u1, v2, dir, light); - putVertex(builder, pose, x2, depth, positive ? y2 : y1, color, u2, v2, dir, light); - putVertex(builder, pose, x2, depth, positive ? y1 : y2, color, u2, v1, dir, light); + FluidRenderHelper.putVertex(builder, pose, x1, depth, positive ? y1 : y2, color, u1, v1, dir, light); + FluidRenderHelper.putVertex(builder, pose, x1, depth, positive ? y2 : y1, color, u1, v2, dir, light); + FluidRenderHelper.putVertex(builder, pose, x2, depth, positive ? y2 : y1, color, u2, v2, dir, light); + FluidRenderHelper.putVertex(builder, pose, x2, depth, positive ? y1 : y2, color, u2, v1, dir, light); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/GravitationalLensSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/GravitationalLensSupport.java index 8869006567..2673b06fe6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/GravitationalLensSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/GravitationalLensSupport.java @@ -27,19 +27,19 @@ public class GravitationalLensSupport { public static final Set CLIENT_WHITE_HOLE_POSITIONS = Collections.newSetFromMap(new ConcurrentHashMap<>()); public static void register(BlockPos pos) { - CLIENT_BLACK_HOLE_POSITIONS.add(pos.immutable()); + GravitationalLensSupport.CLIENT_BLACK_HOLE_POSITIONS.add(pos.immutable()); } public static void unregister(BlockPos pos) { - CLIENT_BLACK_HOLE_POSITIONS.remove(pos); + GravitationalLensSupport.CLIENT_BLACK_HOLE_POSITIONS.remove(pos); } public static void registerWhiteHole(BlockPos pos) { - CLIENT_WHITE_HOLE_POSITIONS.add(pos.immutable()); + GravitationalLensSupport.CLIENT_WHITE_HOLE_POSITIONS.add(pos.immutable()); } public static void unregisterWhiteHole(BlockPos pos) { - CLIENT_WHITE_HOLE_POSITIONS.remove(pos); + GravitationalLensSupport.CLIENT_WHITE_HOLE_POSITIONS.remove(pos); } private static Matrix4f buildViewProj(CameraRenderState cameraState, Matrix4fc projectionMatrix) { @@ -97,11 +97,13 @@ public static List collectVisibleHoles( ) { List result = new ArrayList<>(); - Matrix4f viewProj = buildViewProj(cameraState, projectionMatrix); + Matrix4f viewProj = GravitationalLensSupport.buildViewProj(cameraState, projectionMatrix); Vector3f cameraPos = cameraState.pos.toVector3f(); - collectFromSet(CLIENT_BLACK_HOLE_POSITIONS, cameraPos, viewProj, blackHoleDir, result); - collectFromSet(CLIENT_WHITE_HOLE_POSITIONS, cameraPos, viewProj, whiteHoleDir, result); + GravitationalLensSupport.collectFromSet( + GravitationalLensSupport.CLIENT_BLACK_HOLE_POSITIONS, cameraPos, viewProj, blackHoleDir, result); + GravitationalLensSupport.collectFromSet( + GravitationalLensSupport.CLIENT_WHITE_HOLE_POSITIONS, cameraPos, viewProj, whiteHoleDir, result); // Sort nearest first, then take the closest maxCount result.sort((a, b) -> Float.compare(a.cameraDistance, b.cameraDistance)); @@ -119,7 +121,7 @@ public static boolean uploadBlackHoles( float dir = (float) AnvilCraftClient.CONFIG.gravitationalLens.lensDirection; int maxCount = AnvilCraftClient.CONFIG.gravitationalLens.maxHoleCount; CameraRenderState cameraState = levelRenderState.cameraRenderState; - List holes = collectVisibleHoles( + List holes = GravitationalLensSupport.collectVisibleHoles( cameraState, cameraState.projectionMatrix, maxCount, @@ -153,9 +155,9 @@ private static void collectFromSet( double dy = pos.getY() + 0.5 - cameraPos.y; double dz = pos.getZ() + 0.5 - cameraPos.z; double distanceSqr = dx * dx + dy * dy + dz * dz; - if (distanceSqr > MAX_SEARCH_DISTANCE_SQR) continue; + if (distanceSqr > GravitationalLensSupport.MAX_SEARCH_DISTANCE_SQR) continue; - Vector2f centerUV = worldToScreenUV( + Vector2f centerUV = GravitationalLensSupport.worldToScreenUV( pos.getX() + 0.5f, pos.getY() + 0.5f, pos.getZ() + 0.5f, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/InspectionSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/InspectionSupport.java index 8299bc8475..3457afc8e3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/InspectionSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/InspectionSupport.java @@ -34,9 +34,11 @@ public class InspectionSupport { private final Object2BooleanMap inspectionState = new Object2BooleanAVLTreeMap<>(); public static void initializeClient() { - INSTANCE.registerActionClient(AnvilCraft.of("silencer"), (p, r, c, d) -> { + InspectionSupport.INSTANCE.registerActionClient(AnvilCraft.of("silencer"), (p, r, c, d) -> { Map, List> map = SoundHelper.INSTANCE.getEventListeners(); - List listeners = map.get(Minecraft.getInstance().level.dimension()); + var level = Minecraft.getInstance().level; + if (level == null) return; + List listeners = map.get(level.dimension()); List snapshottedBoxes = listeners.stream().filter(it -> it instanceof IHasAffectRange) .map(it -> ((IHasAffectRange) it).shape()).filter(Objects::nonNull) .toList(); @@ -76,7 +78,7 @@ public void registerActionClient(Identifier id, InspectionAction action) { } public void changeStateClient(Identifier id, boolean state) { - log.info("{} inspection {}.", state ? "Disabling" : "Enabling", id); + InspectionSupport.log.info("{} inspection {}.", state ? "Disabling" : "Enabling", id); this.inspectionState.put(id, state); } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/PillSelectorSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/PillSelectorSupport.java index 783ad2a404..eccf9aaa07 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/PillSelectorSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/PillSelectorSupport.java @@ -53,7 +53,7 @@ public void render(GuiGraphicsExtractor graphics, int x, int y) { final int top = y - 44 - 5; graphics.blit( RenderPipelines.GUI_TEXTURED, - BACKGROUND, + PillSelectorSupport.BACKGROUND, left, top, 0, 0, 78, 44, diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/PowerGridSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/PowerGridSupport.java index 9966a15400..780c3210ec 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/PowerGridSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/PowerGridSupport.java @@ -102,9 +102,9 @@ public static void submitTransmitterLine(PoseStack poseStack, SubmitNodeCollecto public static void clearAllGrid() { SimplePowerGrid.recreateExecutorLimitedParallelism(); - for (SimplePowerGrid value : GRID_MAP.values()) { + for (SimplePowerGrid value : PowerGridSupport.GRID_MAP.values()) { value.destroy(); } - GRID_MAP.clear(); + PowerGridSupport.GRID_MAP.clear(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/RenderSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/RenderSupport.java index a014671d45..915e802e37 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/RenderSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/RenderSupport.java @@ -16,6 +16,7 @@ import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; +import org.jspecify.annotations.Nullable; import java.util.LinkedHashMap; import java.util.Optional; @@ -31,13 +32,12 @@ public class RenderSupport { // public static final Vector3f L1 = new Vector3f(0.4F, 0.0F, 1.0F).normalize(); // public static final Vector3f L2 = new Vector3f(-0.4F, 1.0F, -0.2F).normalize(); private static final PoseStack.Pose BLOCK_DISPLAY_POSE; - private static ClientLevel currentClientLevel = null; - private static LevelLike.AirLevelLike airLevelLike = null; + private static @Nullable ClientLevel currentClientLevel; static { BLOCK_DISPLAY_POSE = new PoseStack.Pose(); - BLOCK_DISPLAY_POSE.rotate(Axis.XP.rotationDegrees(30)); - BLOCK_DISPLAY_POSE.rotate(Axis.YP.rotationDegrees(45)); + RenderSupport.BLOCK_DISPLAY_POSE.rotate(Axis.XP.rotationDegrees(30)); + RenderSupport.BLOCK_DISPLAY_POSE.rotate(Axis.YP.rotationDegrees(45)); } public static void renderBlock(GuiGraphicsExtractor graphics, BlockState block, float x, float y, float size) { @@ -52,7 +52,7 @@ public static void renderBlock(GuiGraphicsExtractor graphics, BlockState block, y + size, -1, true, - BLOCK_DISPLAY_POSE.copy() + RenderSupport.BLOCK_DISPLAY_POSE.copy() ); } @@ -66,18 +66,18 @@ public static void renderWipBlock( ) { ClientLevel level = Minecraft.getInstance().level; if (level == null) { - renderBlock(graphics, ModBlocks.WIP_BLOCK.get().defaultBlockState(), x, y, size); + RenderSupport.renderBlock(graphics, ModBlocks.WIP_BLOCK.get().defaultBlockState(), x, y, size); return; } - if (currentClientLevel != level) { - currentClientLevel = level; - WIP_LEVEL_CACHE.clear(); + if (RenderSupport.currentClientLevel != level) { + RenderSupport.currentClientLevel = level; + RenderSupport.WIP_LEVEL_CACHE.clear(); } WipPreviewKey key = new WipPreviewKey(recipeId, stepCount); - if (!WIP_LEVEL_CACHE.containsKey(key) && WIP_LEVEL_CACHE.size() >= MAX_CACHE_SIZE) { - WIP_LEVEL_CACHE.pollFirstEntry(); + if (!RenderSupport.WIP_LEVEL_CACHE.containsKey(key) && RenderSupport.WIP_LEVEL_CACHE.size() >= RenderSupport.MAX_CACHE_SIZE) { + RenderSupport.WIP_LEVEL_CACHE.pollFirstEntry(); } - LevelLike preview = WIP_LEVEL_CACHE.computeIfAbsent(key, previewKey -> { + LevelLike preview = RenderSupport.WIP_LEVEL_CACHE.computeIfAbsent(key, previewKey -> { LevelLike result = new LevelLike(level); result.setBlockState(BlockPos.ZERO, ModBlocks.WIP_BLOCK.get().defaultBlockState()); if (result.getBlockEntity(BlockPos.ZERO) instanceof WipBlockEntity wip) { @@ -87,7 +87,7 @@ public static void renderWipBlock( return result; }); PoseStack poseStack = new PoseStack(); - poseStack.last().set(BLOCK_DISPLAY_POSE); + poseStack.last().set(RenderSupport.BLOCK_DISPLAY_POSE); GuiRenderExtras.submitStructure( graphics, preview, @@ -97,7 +97,7 @@ public static void renderWipBlock( y, x + size, y + size, - size * WIP_PREVIEW_SCALE, + size * RenderSupport.WIP_PREVIEW_SCALE, true, false, poseStack @@ -118,9 +118,11 @@ public static void renderLevelLike( Optional maxPos = level.getMaxPos(); if (minPos.isEmpty() || maxPos.isEmpty()) return; PoseStack poseStack = new PoseStack(); - poseStack.last().set(BLOCK_DISPLAY_POSE); + poseStack.last().set(RenderSupport.BLOCK_DISPLAY_POSE); Minecraft minecraft = Minecraft.getInstance(); - float gameTime = (minecraft.level.getGameTime() + minecraft.getDeltaTracker().getGameTimeDeltaPartialTick(true)); + ClientLevel currentLevel = minecraft.level; + if (currentLevel == null) return; + float gameTime = currentLevel.getGameTime() + minecraft.getDeltaTracker().getGameTimeDeltaPartialTick(true); poseStack.mulPose(Axis.YP.rotationDegrees(gameTime * rotationSpeed)); GuiRenderExtras.submitStructure( graphics, @@ -140,14 +142,14 @@ public static void renderLevelLike( private static Optional getCachedBlockEntity(BlockState state) { if (!state.hasBlockEntity()) return Optional.empty(); - if (BLOCK_ENTITY_CACHE.containsKey(state)) return Optional.of(BLOCK_ENTITY_CACHE.get(state)); + if (RenderSupport.BLOCK_ENTITY_CACHE.containsKey(state)) return Optional.of(RenderSupport.BLOCK_ENTITY_CACHE.get(state)); Optional opt = Optional.of(state.getBlock()) .filter(b -> b instanceof EntityBlock) .map(b -> ((EntityBlock) b).newBlockEntity(BlockPos.ZERO, state)); opt.ifPresent(be -> { - BLOCK_ENTITY_CACHE.put(state, be); - if (BLOCK_ENTITY_CACHE.size() > MAX_CACHE_SIZE) { - BLOCK_ENTITY_CACHE.pollFirstEntry(); + RenderSupport.BLOCK_ENTITY_CACHE.put(state, be); + if (RenderSupport.BLOCK_ENTITY_CACHE.size() > RenderSupport.MAX_CACHE_SIZE) { + RenderSupport.BLOCK_ENTITY_CACHE.pollFirstEntry(); } }); return opt; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/ScreenShakeManager.java b/src/main/java/dev/dubhe/anvilcraft/client/support/ScreenShakeManager.java index 530f28de00..a0d57bbefb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/ScreenShakeManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/ScreenShakeManager.java @@ -6,6 +6,7 @@ import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; +import org.jspecify.annotations.Nullable; /// 屏幕(摄像机)震动管理器 —— 纯客户端。 /// 通过 ViewportEvent.ComputeCameraAngles 往 yaw/pitch/roll 上叠加噪声实现, @@ -16,7 +17,7 @@ public class ScreenShakeManager { private static final ScreenShakeManager INSTANCE = new ScreenShakeManager(); public static ScreenShakeManager getInstance() { - return INSTANCE; + return ScreenShakeManager.INSTANCE; } /// 触发时的强度(0 表示未激活)。剩余刻数随客户端 tick 递减。 @@ -70,7 +71,7 @@ private float currentFalloff(float partialTick) { /// 计算当前帧应叠加到摄像机的 yaw/pitch/roll 偏移(度)。 /// 使用多个不同频率的正弦叠加,产生不规则的快速颤动而非规则摆动。 - public float[] computeAngleOffsets(float partialTick) { + public float @Nullable [] computeAngleOffsets(float partialTick) { if (!this.isActive()) return null; float falloff = this.currentFalloff(partialTick); if (falloff <= 0.01f) return null; diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/SeismicBounceManager.java b/src/main/java/dev/dubhe/anvilcraft/client/support/SeismicBounceManager.java index 9515cd3819..52d9016aef 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/SeismicBounceManager.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/SeismicBounceManager.java @@ -63,7 +63,7 @@ private SeismicBounceManager() { } public static SeismicBounceManager getInstance() { - return INSTANCE; + return SeismicBounceManager.INSTANCE; } public void triggerShock(BlockPos center, int radius) { @@ -72,7 +72,10 @@ public void triggerShock(BlockPos center, int radius) { for (int dx = -radius; dx <= radius; dx++) { for (int dz = -radius; dz <= radius; dz++) { - if (Math.abs(dx) <= CENTER_EXCLUSION_RADIUS && Math.abs(dz) <= CENTER_EXCLUSION_RADIUS) continue; + if (Math.abs(dx) <= SeismicBounceManager.CENTER_EXCLUSION_RADIUS + && Math.abs(dz) <= SeismicBounceManager.CENTER_EXCLUSION_RADIUS) { + continue; + } int dist = Math.max(Math.abs(dx), Math.abs(dz)); BlockPos pos = center.offset(dx, 0, dz); @@ -82,9 +85,9 @@ public void triggerShock(BlockPos center, int radius) { && state.getRenderShape() == RenderShape.MODEL && level.isEmptyBlock(pos.above()) && level.getBlockEntity(pos) == null - && !isAttachmentBlock(state)) { - float amplitude = MAX_AMPLITUDE * (1.0f - (float) dist / radius) - * (0.8f + this.tesselateRandom.nextFloat() * 0.4f); + && !SeismicBounceManager.isAttachmentBlock(state)) { + float amplitude = SeismicBounceManager.MAX_AMPLITUDE * (1.0f - (float) dist / radius) + * (0.8f + this.tesselateRandom.nextFloat() * 0.4f); amplitude = Math.max(amplitude, 0.15f); int delay = (dist - 2) + this.tesselateRandom.nextInt(3) - 1; this.startBounce(pos, amplitude, Math.max(delay, 0)); @@ -144,9 +147,9 @@ public static class BounceData implements RenderOffset { } void reset(float newAmplitude, int newStartDelay) { - this.totalTicks = BOUNCE_DURATION_TICKS; + this.totalTicks = SeismicBounceManager.BOUNCE_DURATION_TICKS; this.startDelay = newStartDelay; - this.remainingTicks = BOUNCE_DURATION_TICKS + newStartDelay; + this.remainingTicks = SeismicBounceManager.BOUNCE_DURATION_TICKS + newStartDelay; this.amplitude = newAmplitude; } diff --git a/src/main/java/dev/dubhe/anvilcraft/client/support/StructureDiskPreviewSupport.java b/src/main/java/dev/dubhe/anvilcraft/client/support/StructureDiskPreviewSupport.java index ac4a564cb9..f31fa3b8ee 100644 --- a/src/main/java/dev/dubhe/anvilcraft/client/support/StructureDiskPreviewSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/client/support/StructureDiskPreviewSupport.java @@ -21,6 +21,7 @@ import org.jspecify.annotations.Nullable; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -92,11 +93,11 @@ public static void renderPreviewAt(GuiGraphicsExtractor graphics, ItemStack disk Minecraft minecraft = Minecraft.getInstance(); if (minecraft.level == null) return; - PreviewCache cache = getOrCreateCache(diskStack, minecraft.level); + PreviewCache cache = StructureDiskPreviewSupport.getOrCreateCache(diskStack, minecraft.level); if (cache == null || cache.structureData.isEmpty()) return; - int previewX = mouseX - PREVIEW_SIZE / 2; - int previewY = mouseY - PREVIEW_SIZE - 16; + int previewX = mouseX - StructureDiskPreviewSupport.PREVIEW_SIZE / 2; + int previewY = mouseY - StructureDiskPreviewSupport.PREVIEW_SIZE - 16; int screenWidth = minecraft.getWindow().getGuiScaledWidth(); @@ -104,28 +105,43 @@ public static void renderPreviewAt(GuiGraphicsExtractor graphics, ItemStack disk previewY = mouseY + 30; } - if (previewX + PREVIEW_SIZE > screenWidth) { - previewX = screenWidth - PREVIEW_SIZE - 5; + if (previewX + StructureDiskPreviewSupport.PREVIEW_SIZE > screenWidth) { + previewX = screenWidth - StructureDiskPreviewSupport.PREVIEW_SIZE - 5; } if (previewX < 0) { previewX = 5; } - graphics.fill(previewX - 2, previewY - 2, previewX + PREVIEW_SIZE + 2, previewY + PREVIEW_SIZE + 2, 0xF0100010); + graphics.fill( + previewX - 2, previewY - 2, previewX + StructureDiskPreviewSupport.PREVIEW_SIZE + 2, + previewY + StructureDiskPreviewSupport.PREVIEW_SIZE + 2, 0xF0100010 + ); - graphics.fill(previewX - 2, previewY - 2, previewX + PREVIEW_SIZE + 2, previewY - 1, 0x505000ff); - graphics.fill(previewX - 2, previewY + PREVIEW_SIZE + 2, previewX + PREVIEW_SIZE + 2, previewY + PREVIEW_SIZE + 3, 0x505000ff); - graphics.fill(previewX - 2, previewY - 1, previewX - 1, previewY + PREVIEW_SIZE + 3, 0x505000ff); - graphics.fill(previewX + PREVIEW_SIZE + 1, previewY - 1, previewX + PREVIEW_SIZE + 2, previewY + PREVIEW_SIZE + 3, 0x505000ff); + graphics.fill(previewX - 2, previewY - 2, previewX + StructureDiskPreviewSupport.PREVIEW_SIZE + 2, previewY - 1, 0x505000ff); + graphics.fill( + previewX - 2, previewY + StructureDiskPreviewSupport.PREVIEW_SIZE + 2, previewX + StructureDiskPreviewSupport.PREVIEW_SIZE + 2, + previewY + StructureDiskPreviewSupport.PREVIEW_SIZE + + 3, 0x505000ff + ); + graphics.fill(previewX - 2, previewY - 1, previewX - 1, previewY + StructureDiskPreviewSupport.PREVIEW_SIZE + 3, 0x505000ff); + graphics.fill( + previewX + StructureDiskPreviewSupport.PREVIEW_SIZE + 1, previewY - 1, previewX + StructureDiskPreviewSupport.PREVIEW_SIZE + 2, + previewY + StructureDiskPreviewSupport.PREVIEW_SIZE + + 3, 0x505000ff + ); - int maxDim = Math.max(cache.structureData.diskData.sizeX(), - Math.max(cache.structureData.diskData.sizeY(), - cache.structureData.diskData.sizeZ())); + int maxDim = Math.max( + cache.structureData.diskData.sizeX(), + Math.max( + cache.structureData.diskData.sizeY(), + cache.structureData.diskData.sizeZ() + ) + ); int scale = Math.max(1, 30 / maxDim); RenderSupport.renderLevelLike( cache.levelLike, graphics, previewX, previewY, - PREVIEW_SIZE, scale, 2.0f, false + StructureDiskPreviewSupport.PREVIEW_SIZE, scale, 2.0f, false ); } @@ -134,9 +150,9 @@ public static void renderPreviewAt(GuiGraphicsExtractor graphics, ItemStack disk * 存储原始数据,待 tooltip 渲染时再解析为 LevelLike。 */ public static void receiveStructureData(UUID structureUuid, CompoundTag structureData) { - PENDING_PREVIEW_DATA.put(structureUuid, structureData); - PENDING_REQUESTS.remove(structureUuid); - REQUEST_TIMESTAMPS.remove(structureUuid); + StructureDiskPreviewSupport.PENDING_PREVIEW_DATA.put(structureUuid, structureData); + StructureDiskPreviewSupport.PENDING_REQUESTS.remove(structureUuid); + StructureDiskPreviewSupport.REQUEST_TIMESTAMPS.remove(structureUuid); } /** @@ -150,46 +166,47 @@ private static PreviewCache getOrCreateCache(ItemStack diskStack, ClientLevel le UUID uuid = diskData.uuid(); // 1. 命中完整缓存 — 直接返回,永不过期 - PreviewCache cache = PREVIEW_CACHE.get(uuid); + PreviewCache cache = StructureDiskPreviewSupport.PREVIEW_CACHE.get(uuid); if (cache != null) { return cache; } // 2. 检查是否有服务端返回的 NBT 待处理数据 - CompoundTag pendingData = PENDING_PREVIEW_DATA.get(uuid); + CompoundTag pendingData = StructureDiskPreviewSupport.PENDING_PREVIEW_DATA.get(uuid); if (pendingData != null) { - StructureLoadUtil.StructureData data = parsePreviewNbt(pendingData, diskData, level.registryAccess()); + StructureLoadUtil.StructureData data = StructureDiskPreviewSupport.parsePreviewNbt( + pendingData, diskData, level.registryAccess()); if (data != null && !data.isEmpty()) { - LevelLike levelLike = buildLevelLike(data); + LevelLike levelLike = StructureDiskPreviewSupport.buildLevelLike(data); if (levelLike != null) { cache = new PreviewCache(data, levelLike); - PREVIEW_CACHE.put(uuid, cache); - PENDING_PREVIEW_DATA.remove(uuid); - evictIfNeeded(); + StructureDiskPreviewSupport.PREVIEW_CACHE.put(uuid, cache); + StructureDiskPreviewSupport.PENDING_PREVIEW_DATA.remove(uuid); + StructureDiskPreviewSupport.evictIfNeeded(); return cache; } } // 解析失败,清理待处理数据,后续会重新请求 - PENDING_PREVIEW_DATA.remove(uuid); + StructureDiskPreviewSupport.PENDING_PREVIEW_DATA.remove(uuid); return null; } // 3. 回退:尝试从本地文件加载(单人模式有效) StructureLoadUtil.StructureData localData = StructureLoadUtil.loadStructureFromDiskForPreview(level, diskStack); if (localData != null && !localData.isEmpty()) { - LevelLike levelLike = buildLevelLike(localData); + LevelLike levelLike = StructureDiskPreviewSupport.buildLevelLike(localData); if (levelLike != null) { cache = new PreviewCache(localData, levelLike); - PREVIEW_CACHE.put(uuid, cache); - evictIfNeeded(); + StructureDiskPreviewSupport.PREVIEW_CACHE.put(uuid, cache); + StructureDiskPreviewSupport.evictIfNeeded(); return cache; } } // 4. 未缓存且未请求 → 向服务端发送请求 - if (shouldSendRequest(uuid)) { - PENDING_REQUESTS.add(uuid); - REQUEST_TIMESTAMPS.put(uuid, System.currentTimeMillis()); + if (StructureDiskPreviewSupport.shouldSendRequest(uuid)) { + StructureDiskPreviewSupport.PENDING_REQUESTS.add(uuid); + StructureDiskPreviewSupport.REQUEST_TIMESTAMPS.put(uuid, System.currentTimeMillis()); ClientPacketDistributor.sendToServer(new StructurePreviewRequestPacket(uuid, diskData.file())); } @@ -200,10 +217,10 @@ private static PreviewCache getOrCreateCache(ItemStack diskStack, ClientLevel le * 检查是否应该发送请求(未被请求或已超时) */ private static boolean shouldSendRequest(UUID uuid) { - if (!PENDING_REQUESTS.contains(uuid)) return true; - Long timestamp = REQUEST_TIMESTAMPS.get(uuid); + if (!StructureDiskPreviewSupport.PENDING_REQUESTS.contains(uuid)) return true; + Long timestamp = StructureDiskPreviewSupport.REQUEST_TIMESTAMPS.get(uuid); if (timestamp == null) return true; - return System.currentTimeMillis() - timestamp > REQUEST_TIMEOUT_MS; + return System.currentTimeMillis() - timestamp > StructureDiskPreviewSupport.REQUEST_TIMEOUT_MS; } /** @@ -285,12 +302,12 @@ private static LevelLike buildLevelLike(StructureLoadUtil.StructureData data) { * 缓存超过上限时淘汰最旧条目 */ private static void evictIfNeeded() { - if (PREVIEW_CACHE.size() <= MAX_CACHE_SIZE) return; + if (StructureDiskPreviewSupport.PREVIEW_CACHE.size() <= StructureDiskPreviewSupport.MAX_CACHE_SIZE) return; - PREVIEW_CACHE.entrySet() + StructureDiskPreviewSupport.PREVIEW_CACHE.entrySet() .stream() - .sorted(java.util.Comparator.comparingLong(e -> e.getValue().creationTime)) - .limit(PREVIEW_CACHE.size() - MAX_CACHE_SIZE) - .forEach(e -> PREVIEW_CACHE.remove(e.getKey())); + .sorted(Comparator.comparingLong(e -> e.getValue().creationTime)) + .limit(StructureDiskPreviewSupport.PREVIEW_CACHE.size() - StructureDiskPreviewSupport.MAX_CACHE_SIZE) + .forEach(e -> StructureDiskPreviewSupport.PREVIEW_CACHE.remove(e.getKey())); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/command/MultiphaseCommand.java b/src/main/java/dev/dubhe/anvilcraft/command/MultiphaseCommand.java index 587fdda6f3..24f811bf49 100644 --- a/src/main/java/dev/dubhe/anvilcraft/command/MultiphaseCommand.java +++ b/src/main/java/dev/dubhe/anvilcraft/command/MultiphaseCommand.java @@ -16,6 +16,8 @@ import net.minecraft.server.permissions.Permissions; import net.minecraft.world.item.ItemStack; +import java.util.Objects; + public class MultiphaseCommand { private static final SimpleCommandExceptionType ERROR_NO_MULTIPHASE = new SimpleCommandExceptionType( Component.translatable("command.anvilcraft.multiphase.no_item") @@ -32,10 +34,10 @@ public static void registerCommand(LiteralArgumentBuilder pa .then(Commands.literal("info").executes(MultiphaseCommand::showInfo)) .then( Commands.literal("add") - .executes(context -> addPhases(context, 1)) + .executes(context -> MultiphaseCommand.addPhases(context, 1)) .then( Commands.argument("count", IntegerArgumentType.integer(1, Multiphase.MAX_PHASE_COUNT)) - .executes(context -> addPhases( + .executes(context -> MultiphaseCommand.addPhases( context, IntegerArgumentType.getInteger(context, "count") )) @@ -45,8 +47,8 @@ public static void registerCommand(LiteralArgumentBuilder pa } private static int showInfo(CommandContext context) throws CommandSyntaxException { - ItemStack stack = getMultiphaseStack(context.getSource()); - Multiphase multiphase = stack.get(ModComponents.MULTIPHASE).capture(stack); + ItemStack stack = MultiphaseCommand.getMultiphaseStack(context.getSource()); + Multiphase multiphase = Objects.requireNonNull(stack.get(ModComponents.MULTIPHASE)).capture(stack); stack.set(ModComponents.MULTIPHASE, multiphase); MutableComponent message = Component.translatable( @@ -68,15 +70,15 @@ private static int showInfo(CommandContext context) throws C } private static int addPhases(CommandContext context, int requested) throws CommandSyntaxException { - ItemStack stack = getMultiphaseStack(context.getSource()); + ItemStack stack = MultiphaseCommand.getMultiphaseStack(context.getSource()); int added = 0; for (int i = 0; i < requested; i++) { Multiphase multiphase = stack.get(ModComponents.MULTIPHASE); if (multiphase == null || !multiphase.addPhase(stack)) break; added++; } - if (added == 0) throw ERROR_MAX_PHASES.create(); - int phaseCount = stack.get(ModComponents.MULTIPHASE).phases().size(); + if (added == 0) throw MultiphaseCommand.ERROR_MAX_PHASES.create(); + int phaseCount = Objects.requireNonNull(stack.get(ModComponents.MULTIPHASE)).phases().size(); return CommandUtil.sendSuccess( context.getSource(), "command.anvilcraft.multiphase.add.success", @@ -87,7 +89,7 @@ private static int addPhases(CommandContext context, int req private static ItemStack getMultiphaseStack(CommandSourceStack source) throws CommandSyntaxException { ItemStack stack = source.getPlayerOrException().getMainHandItem(); - if (!stack.has(ModComponents.MULTIPHASE)) throw ERROR_NO_MULTIPHASE.create(); + if (!stack.has(ModComponents.MULTIPHASE)) throw MultiphaseCommand.ERROR_NO_MULTIPHASE.create(); return stack; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/command/PowerGridCommand.java b/src/main/java/dev/dubhe/anvilcraft/command/PowerGridCommand.java index 71e7ab579a..a7a157d84c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/command/PowerGridCommand.java +++ b/src/main/java/dev/dubhe/anvilcraft/command/PowerGridCommand.java @@ -53,12 +53,12 @@ private static int showInfo(CommandContext ctx) { .append(Component.translatable("command.anvilcraft.powergrid.info.components").withStyle(ChatFormatting.WHITE)) .append(Component.literal("\n")); p.getGrid().getComponents().stream() - .limit(SHOW_INFO_LIMIT) + .limit(PowerGridCommand.SHOW_INFO_LIMIT) .map(IPowerComponent::getCommandDiscription) .map(component -> component.append("\n")) .forEach(message::append); p.getGrid().getDynamicComponents().stream() - .limit(SHOW_INFO_LIMIT) + .limit(PowerGridCommand.SHOW_INFO_LIMIT) .map(DynamicPowerComponent::getCommandDescription) .map(component -> component.append("\n")) .forEach(message::append); diff --git a/src/main/java/dev/dubhe/anvilcraft/command/TickSprintVoteCommand.java b/src/main/java/dev/dubhe/anvilcraft/command/TickSprintVoteCommand.java index e582ccdbb5..e0168e7d68 100644 --- a/src/main/java/dev/dubhe/anvilcraft/command/TickSprintVoteCommand.java +++ b/src/main/java/dev/dubhe/anvilcraft/command/TickSprintVoteCommand.java @@ -23,8 +23,8 @@ public static void registerCommand(LiteralArgumentBuilder pa .then(Commands.argument("dimension", DimensionArgument.dimension()) .then(Commands.argument("pos", BlockPosArgument.blockPos()) .then(Commands.argument("voteId", UuidArgument.uuid()) - .then(Commands.literal("accept").executes(context -> submitVote(context, true))) - .then(Commands.literal("reject").executes(context -> submitVote(context, false))))))); + .then(Commands.literal("accept").executes(context -> TickSprintVoteCommand.submitVote(context, true))) + .then(Commands.literal("reject").executes(context -> TickSprintVoteCommand.submitVote(context, false))))))); } private static int submitVote(CommandContext context, boolean accepted) diff --git a/src/main/java/dev/dubhe/anvilcraft/constant/SharedTextures.java b/src/main/java/dev/dubhe/anvilcraft/constant/SharedTextures.java index 3f9f6f2a2d..0df83d00da 100644 --- a/src/main/java/dev/dubhe/anvilcraft/constant/SharedTextures.java +++ b/src/main/java/dev/dubhe/anvilcraft/constant/SharedTextures.java @@ -5,56 +5,58 @@ public class SharedTextures { // CRAFTING - public static final Identifier ERROR_SPRITE = textureGui("crafting/error"); - public static final Identifier SWITCH_TABLE_BUTTON = textureGui("crafting/switch_table_button"); - public static final Identifier SWITCH_TABLE_SLIDER = textureGui("crafting/switch_table_slider"); - public static final Identifier TEXT_FIELD = textureGui("crafting/text_field"); - public static final Identifier TEXT_FIELD_DISABLE = textureGui("crafting/text_field_disabled"); + public static final Identifier ERROR_SPRITE = SharedTextures.textureGui("crafting/error"); + public static final Identifier SWITCH_TABLE_BUTTON = SharedTextures.textureGui("crafting/switch_table_button"); + public static final Identifier SWITCH_TABLE_SLIDER = SharedTextures.textureGui("crafting/switch_table_slider"); + public static final Identifier TEXT_FIELD = SharedTextures.textureGui("crafting/text_field"); + public static final Identifier TEXT_FIELD_DISABLE = SharedTextures.textureGui("crafting/text_field_disabled"); // MACHINE - public static final Identifier BUTTON_ALL = textureGui("machine/button_all"); - public static final Identifier BUTTON_ANY = textureGui("machine/button_any"); - public static final Identifier BUTTON_U = textureGui("machine/button_u"); - public static final Identifier BUTTON_D = textureGui("machine/button_d"); - public static final Identifier BUTTON_N = textureGui("machine/button_n"); - public static final Identifier BUTTON_S = textureGui("machine/button_s"); - public static final Identifier BUTTON_E = textureGui("machine/button_e"); - public static final Identifier BUTTON_W = textureGui("machine/button_w"); - public static final Identifier BUTTON_RISING_EDGE = textureGui("machine/button_rising_edge"); - public static final Identifier BUTTON_FALLING_EDGE = textureGui("machine/button_falling_edge"); - public static final Identifier BUTTON_LOOP = textureGui("machine/button_loop"); - public static final Identifier BUTTON_HYSTERESIS = textureGui("machine/button_hysteresis"); - public static final Identifier BUTTON_WINDOW = textureGui("machine/button_window"); - public static final Identifier BUTTON_YES = textureGui("machine/button_yes"); - public static final Identifier BUTTON_NO = textureGui("machine/button_no"); - public static final Identifier BUTTON_REDSTONE_CONTROL_ON = textureGui("machine/button_redstone_control_on"); - public static final Identifier BUTTON_REDSTONE_CONTROL_OFF = textureGui("machine/button_redstone_control_off"); - public static final Identifier BUTTON_REVERSE_ON = textureGui("machine/button_reverse_on"); - public static final Identifier BUTTON_REVERSE_OFF = textureGui("machine/button_reverse_off"); - public static final Identifier CONFIRM = textureGui("machine/confirm"); - public static final Identifier REDO = textureGui("machine/redo"); - public static final Identifier STOP = textureGui("machine/stop"); - public static final Identifier STRUCTURE_TOOL_LOCKED = textureGui("machine/structure_tool_locked"); - public static final Identifier DISABLED_SLOT = textureGui("machine/disabled_slot"); - public static final Identifier SMALL_MACHINE_SLIDER = textureGui("machine/slider"); + public static final Identifier BUTTON_ALL = SharedTextures.textureGui("machine/button_all"); + public static final Identifier BUTTON_ANY = SharedTextures.textureGui("machine/button_any"); + public static final Identifier BUTTON_U = SharedTextures.textureGui("machine/button_u"); + public static final Identifier BUTTON_D = SharedTextures.textureGui("machine/button_d"); + public static final Identifier BUTTON_N = SharedTextures.textureGui("machine/button_n"); + public static final Identifier BUTTON_S = SharedTextures.textureGui("machine/button_s"); + public static final Identifier BUTTON_E = SharedTextures.textureGui("machine/button_e"); + public static final Identifier BUTTON_W = SharedTextures.textureGui("machine/button_w"); + public static final Identifier BUTTON_RISING_EDGE = SharedTextures.textureGui("machine/button_rising_edge"); + public static final Identifier BUTTON_FALLING_EDGE = SharedTextures.textureGui("machine/button_falling_edge"); + public static final Identifier BUTTON_LOOP = SharedTextures.textureGui("machine/button_loop"); + public static final Identifier BUTTON_HYSTERESIS = SharedTextures.textureGui("machine/button_hysteresis"); + public static final Identifier BUTTON_WINDOW = SharedTextures.textureGui("machine/button_window"); + public static final Identifier BUTTON_YES = SharedTextures.textureGui("machine/button_yes"); + public static final Identifier BUTTON_NO = SharedTextures.textureGui("machine/button_no"); + public static final Identifier BUTTON_REDSTONE_CONTROL_ON = SharedTextures.textureGui("machine/button_redstone_control_on"); + public static final Identifier BUTTON_REDSTONE_CONTROL_OFF = SharedTextures.textureGui("machine/button_redstone_control_off"); + public static final Identifier BUTTON_REVERSE_ON = SharedTextures.textureGui("machine/button_reverse_on"); + public static final Identifier BUTTON_REVERSE_OFF = SharedTextures.textureGui("machine/button_reverse_off"); + public static final Identifier CONFIRM = SharedTextures.textureGui("machine/confirm"); + public static final Identifier REDO = SharedTextures.textureGui("machine/redo"); + public static final Identifier STOP = SharedTextures.textureGui("machine/stop"); + public static final Identifier STRUCTURE_TOOL_LOCKED = SharedTextures.textureGui("machine/structure_tool_locked"); + public static final Identifier DISABLED_SLOT = SharedTextures.textureGui("machine/disabled_slot"); + public static final Identifier SMALL_MACHINE_SLIDER = SharedTextures.textureGui("machine/slider"); // 智能放置器 - public static final Identifier SMART_BLOCK_PLACER_LAYER_1 = textureGui("machine/smart_block_placer/layer_1"); - public static final Identifier SMART_BLOCK_PLACER_LAYER_2 = textureGui("machine/smart_block_placer/layer_2"); - public static final Identifier SMART_BLOCK_PLACER_LAYER_3 = textureGui("machine/smart_block_placer/layer_3"); - public static final Identifier SMART_BLOCK_PLACER_LAYER_4 = textureGui("machine/smart_block_placer/layer_4"); - public static final Identifier SMART_BLOCK_PLACER_LAYER_5 = textureGui("machine/smart_block_placer/layer_5"); - public static final Identifier SMART_BLOCK_PLACER_POSITION_SELECT = textureGui("machine/smart_block_placer/position_select"); - public static final Identifier SMART_BLOCK_PLACER_LAYER_ALL = textureGui("machine/smart_block_placer/layer_all"); - public static final Identifier SMART_BLOCK_PLACER_LAYER_SINGLE = textureGui("machine/smart_block_placer/layer_single"); - public static final Identifier SMART_BLOCK_PLACER_PICKUP_MODE = textureGui("machine/smart_block_placer/pickup_mode"); - public static final Identifier SMART_BLOCK_PLACER_MOVE_MODE = textureGui("machine/smart_block_placer/move_mode"); - public static final Identifier SMART_BLOCK_PLACER_BLUEPRINT_MODE = textureGui("machine/smart_block_placer/blueprint_mode"); - public static final Identifier SMART_BLOCK_PLACER_SKIP_MISSING = textureGui("machine/smart_block_placer/skip_missing"); - public static final Identifier SMART_BLOCK_PLACER_STOP_MISSING = textureGui("machine/smart_block_placer/stop_missing"); + public static final Identifier SMART_BLOCK_PLACER_LAYER_1 = SharedTextures.textureGui("machine/smart_block_placer/layer_1"); + public static final Identifier SMART_BLOCK_PLACER_LAYER_2 = SharedTextures.textureGui("machine/smart_block_placer/layer_2"); + public static final Identifier SMART_BLOCK_PLACER_LAYER_3 = SharedTextures.textureGui("machine/smart_block_placer/layer_3"); + public static final Identifier SMART_BLOCK_PLACER_LAYER_4 = SharedTextures.textureGui("machine/smart_block_placer/layer_4"); + public static final Identifier SMART_BLOCK_PLACER_LAYER_5 = SharedTextures.textureGui("machine/smart_block_placer/layer_5"); + public static final Identifier SMART_BLOCK_PLACER_POSITION_SELECT = SharedTextures.textureGui( + "machine/smart_block_placer/position_select"); + public static final Identifier SMART_BLOCK_PLACER_LAYER_ALL = SharedTextures.textureGui("machine/smart_block_placer/layer_all"); + public static final Identifier SMART_BLOCK_PLACER_LAYER_SINGLE = SharedTextures.textureGui("machine/smart_block_placer/layer_single"); + public static final Identifier SMART_BLOCK_PLACER_PICKUP_MODE = SharedTextures.textureGui("machine/smart_block_placer/pickup_mode"); + public static final Identifier SMART_BLOCK_PLACER_MOVE_MODE = SharedTextures.textureGui("machine/smart_block_placer/move_mode"); + public static final Identifier SMART_BLOCK_PLACER_BLUEPRINT_MODE = SharedTextures.textureGui( + "machine/smart_block_placer/blueprint_mode"); + public static final Identifier SMART_BLOCK_PLACER_SKIP_MISSING = SharedTextures.textureGui("machine/smart_block_placer/skip_missing"); + public static final Identifier SMART_BLOCK_PLACER_STOP_MISSING = SharedTextures.textureGui("machine/smart_block_placer/stop_missing"); // MISC - public static final Identifier BOX_SELECTION = textureGui("misc/box_selection"); + public static final Identifier BOX_SELECTION = SharedTextures.textureGui("misc/box_selection"); public static Identifier texture(String path) { return AnvilCraft.of("textures/" + path + ".png"); diff --git a/src/main/java/dev/dubhe/anvilcraft/data/advancement/ModAdvancementsHandler.java b/src/main/java/dev/dubhe/anvilcraft/data/advancement/ModAdvancementsHandler.java index e3bf812eb6..e7441faa46 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/advancement/ModAdvancementsHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/advancement/ModAdvancementsHandler.java @@ -24,11 +24,12 @@ import net.minecraft.world.level.block.Blocks; import java.util.List; +import java.util.Objects; public class ModAdvancementsHandler { @SuppressWarnings("unused") public static void init(RegistrumAdvancementProvider provider) { - HolderLookup.Provider registries = provider.getProvider(); + HolderLookup.Provider registries = Objects.requireNonNull(provider.getProvider()); HolderGetter itemLookup = registries.lookupOrThrow(Registries.ITEM); HolderGetter blockLookup = registries.lookupOrThrow(Registries.BLOCK); HolderGetter> entityTypeLookup = registries.lookupOrThrow(Registries.ENTITY_TYPE); diff --git a/src/main/java/dev/dubhe/anvilcraft/data/generator/RedstoneWireBlockStateGenerator.java b/src/main/java/dev/dubhe/anvilcraft/data/generator/RedstoneWireBlockStateGenerator.java index a3b966af2c..ad93ce421b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/generator/RedstoneWireBlockStateGenerator.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/generator/RedstoneWireBlockStateGenerator.java @@ -33,8 +33,8 @@ public static void generate( ) { MultiPartGenerator multipart = MultiPartGenerator.multiPart(context.get()); for (Direction attachment : Direction.values()) { - Identifier dot = dotModel(provider, attachment) - .build(modelLocation(provider, attachment, "dot")); + Identifier dot = RedstoneWireBlockStateGenerator.dotModel(provider, attachment) + .build(RedstoneWireBlockStateGenerator.modelLocation(provider, attachment, "dot")); multipart.with( BlockModelGenerators.condition() .term(RedstoneWireBlock.ATTACHMENT, attachment) @@ -43,10 +43,10 @@ public static void generate( ); for (int index = 0; index < 4; index++) { - Identifier side = sideModel(provider, attachment, index) - .build(modelLocation(provider, attachment, "side_" + index)); - Identifier up = upModel(provider, attachment, index) - .build(modelLocation(provider, attachment, "up_" + index)); + Identifier side = RedstoneWireBlockStateGenerator.sideModel(provider, attachment, index) + .build(RedstoneWireBlockStateGenerator.modelLocation(provider, attachment, "side_" + index)); + Identifier up = RedstoneWireBlockStateGenerator.upModel(provider, attachment, index) + .build(RedstoneWireBlockStateGenerator.modelLocation(provider, attachment, "up_" + index)); var property = RedstoneWireBlock.CONNECTION_PROPERTIES.get(index); multipart.with( BlockModelGenerators.condition() @@ -56,8 +56,8 @@ public static void generate( ); if (attachment.getAxis().isHorizontal()) { // 只有墙面导线绕支撑块边缘时需要向模型边界外延伸;地面和天花板没有这种显示形态。 - Identifier sideCorner = sideCornerModel(provider, attachment, index) - .build(modelLocation(provider, attachment, "side_corner_" + index)); + Identifier sideCorner = RedstoneWireBlockStateGenerator.sideCornerModel(provider, attachment, index) + .build(RedstoneWireBlockStateGenerator.modelLocation(provider, attachment, "side_corner_" + index)); multipart.with( BlockModelGenerators.condition() .term(RedstoneWireBlock.ATTACHMENT, attachment) @@ -65,8 +65,8 @@ public static void generate( BlockModelGenerators.plainVariant(sideCorner) ); if (RedstoneWireBlock.getLocalDirection(attachment, index) == Direction.UP) { - Identifier sideCornerSp = sideCornerSpModel(provider, attachment, index) - .build(modelLocation(provider, attachment, "side_corner_sp_" + index)); + Identifier sideCornerSp = RedstoneWireBlockStateGenerator.sideCornerSpModel(provider, attachment, index) + .build(RedstoneWireBlockStateGenerator.modelLocation(provider, attachment, "side_corner_sp_" + index)); multipart.with( BlockModelGenerators.condition() .term(RedstoneWireBlock.ATTACHMENT, attachment) @@ -89,29 +89,29 @@ public static void generate( /** 生成分叉或转角处用于覆盖线段接缝的中心点模型。 */ private static RegistrumLegacyBlockModelBuilder dotModel(RegistrumBlockModelGenerator provider, Direction attachment) { Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, 0); - RegistrumLegacyBlockModelBuilder model = model(provider, attachment, "dot") - .texture(BASE, AnvilCraft.of("block/redstone_wire_dot")) - .texture(OVERLAY, AnvilCraft.of("block/redstone_wire_dot_overlay")) + RegistrumLegacyBlockModelBuilder model = RedstoneWireBlockStateGenerator.model(provider, attachment, "dot") + .texture(RedstoneWireBlockStateGenerator.BASE, AnvilCraft.of("block/redstone_wire_dot")) + .texture(RedstoneWireBlockStateGenerator.OVERLAY, AnvilCraft.of("block/redstone_wire_dot_overlay")) .texture(TextureSlot.PARTICLE, AnvilCraft.of("block/redstone_wire_dot")); // 底层提供固定材质边缘,上层使用 tintindex 0 随 POWER 改变颜色,与原版红石粉视觉一致。 - addBox(model, attachment, tangent, 4.0, -0.5, 4.0, 12.0, 1.5, 12.0, List.of( - face(Direction.NORTH, "#0", 4, 4, 12, 6), - transformedUvFace(attachment.getAxis().isHorizontal(), Direction.EAST, "#0", 4, 4, 12, 6), - face(Direction.SOUTH, "#0", 4, 4, 12, 6), - transformedUvFace(attachment.getAxis().isHorizontal(), Direction.WEST, "#0", 4, 4, 12, 6), - face(Direction.UP, "#0", 4, 4, 12, 12), - face(Direction.DOWN, "#0", 4, 4, 12, 12, 0, false, Direction.DOWN) + RedstoneWireBlockStateGenerator.addBox(model, attachment, tangent, 4.0, -0.5, 4.0, 12.0, 1.5, 12.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#0", 4, 4, 12, 6), + RedstoneWireBlockStateGenerator.transformedUvFace(attachment.getAxis().isHorizontal(), Direction.EAST, "#0", 4, 4, 12, 6), + RedstoneWireBlockStateGenerator.face(Direction.SOUTH, "#0", 4, 4, 12, 6), + RedstoneWireBlockStateGenerator.transformedUvFace(attachment.getAxis().isHorizontal(), Direction.WEST, "#0", 4, 4, 12, 6), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#0", 4, 4, 12, 12), + RedstoneWireBlockStateGenerator.face(Direction.DOWN, "#0", 4, 4, 12, 12, 0, false, Direction.DOWN) )); - addBox(model, attachment, tangent, 5.0, 1.5, 5.0, 11.0, 2.5, 11.0, List.of( - face(Direction.NORTH, "#1", 5, 5, 11, 6, 0, true, null), - transformedUvFace( + RedstoneWireBlockStateGenerator.addBox(model, attachment, tangent, 5.0, 1.5, 5.0, 11.0, 2.5, 11.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#1", 5, 5, 11, 6, 0, true, null), + RedstoneWireBlockStateGenerator.transformedUvFace( attachment.getAxis().isHorizontal(), Direction.EAST, "#1", 5, 5, 11, 6, 0, true, null ), - face(Direction.SOUTH, "#1", 5, 5, 11, 6, 0, true, null), - transformedUvFace( + RedstoneWireBlockStateGenerator.face(Direction.SOUTH, "#1", 5, 5, 11, 6, 0, true, null), + RedstoneWireBlockStateGenerator.transformedUvFace( attachment.getAxis().isHorizontal(), Direction.WEST, "#1", 5, 5, 11, 6, 0, true, null ), - face(Direction.UP, "#1", 5, 5, 11, 11, 0, true, null) + RedstoneWireBlockStateGenerator.face(Direction.UP, "#1", 5, 5, 11, 11, 0, true, null) )); return model; } @@ -121,23 +121,23 @@ private static RegistrumLegacyBlockModelBuilder sideModel( RegistrumBlockModelGenerator provider, Direction attachment, int index ) { Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); - RegistrumLegacyBlockModelBuilder model = model(provider, attachment, "side_" + index) - .texture(BASE, AnvilCraft.of("block/redstone_wire_line")) - .texture(OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) + RegistrumLegacyBlockModelBuilder model = RedstoneWireBlockStateGenerator.model(provider, attachment, "side_" + index) + .texture(RedstoneWireBlockStateGenerator.BASE, AnvilCraft.of("block/redstone_wire_line")) + .texture(RedstoneWireBlockStateGenerator.OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) .texture(TextureSlot.PARTICLE, AnvilCraft.of("block/redstone_wire_line")); // 线段会旋转到不同表面,侧面 UV 也要随局部基旋转,否则同一纹理会在部分朝向上镜像或倒置。 - addBoxWithRotatedUvs(model, attachment, tangent, 5.0, 0.0, 0.0, 11.0, 1.0, 8.0, List.of( - face(Direction.NORTH, "#0", 5, 0, 11, 1, 0, false, Direction.NORTH), - face(Direction.EAST, "#0", 10, 0, 11, 8, 90, false, null), - face(Direction.WEST, "#0", 5, 8, 6, 0, 90, false, null), - face(Direction.UP, "#0", 5, 0, 11, 8), - face(Direction.DOWN, "#0", 11, 0, 5, 8, 0, false, Direction.DOWN) + RedstoneWireBlockStateGenerator.addBoxWithRotatedUvs(model, attachment, tangent, 5.0, 0.0, 0.0, 11.0, 1.0, 8.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#0", 5, 0, 11, 1, 0, false, Direction.NORTH), + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#0", 10, 0, 11, 8, 90, false, null), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#0", 5, 8, 6, 0, 90, false, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#0", 5, 0, 11, 8), + RedstoneWireBlockStateGenerator.face(Direction.DOWN, "#0", 11, 0, 5, 8, 0, false, Direction.DOWN) )); - addBoxWithRotatedUvs(model, attachment, tangent, 6.0, 1.0, 0.0, 10.0, 2.0, 8.0, List.of( - face(Direction.NORTH, "#1", 6, 0, 10, 1, 0, true, Direction.NORTH), - face(Direction.EAST, "#1", 6, 0, 7, 8, 90, true, null), - face(Direction.WEST, "#1", 6, 0, 7, 8, 90, true, null), - face(Direction.UP, "#1", 6, 0, 10, 8, 0, true, null) + RedstoneWireBlockStateGenerator.addBoxWithRotatedUvs(model, attachment, tangent, 6.0, 1.0, 0.0, 10.0, 2.0, 8.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#1", 6, 0, 10, 1, 0, true, Direction.NORTH), + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#1", 6, 0, 7, 8, 90, true, null), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#1", 6, 0, 7, 8, 90, true, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#1", 6, 0, 10, 8, 0, true, null) )); return model; } @@ -147,23 +147,23 @@ private static RegistrumLegacyBlockModelBuilder sideCornerModel( RegistrumBlockModelGenerator provider, Direction attachment, int index ) { Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); - RegistrumLegacyBlockModelBuilder model = model(provider, attachment, "side_corner_" + index) - .texture(BASE, AnvilCraft.of("block/redstone_wire_line")) - .texture(OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) + RegistrumLegacyBlockModelBuilder model = RedstoneWireBlockStateGenerator.model(provider, attachment, "side_corner_" + index) + .texture(RedstoneWireBlockStateGenerator.BASE, AnvilCraft.of("block/redstone_wire_line")) + .texture(RedstoneWireBlockStateGenerator.OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) .texture(TextureSlot.PARTICLE, AnvilCraft.of("block/redstone_wire_line")); // 负局部 Z 部分越过当前方块边界,用来遮住两个不同附着面模型在实体边缘留下的缝隙。 - addBoxWithRotatedUvs(model, attachment, tangent, 5.0, 0.0, -1.0, 11.0, 1.0, 8.0, List.of( - face(Direction.NORTH, "#0", 5, 0, 11, 1, 0, false, Direction.NORTH), - face(Direction.EAST, "#0", 10, 0, 11, 9, 90, false, null), - face(Direction.WEST, "#0", 5, 9, 6, 0, 90, false, null), - face(Direction.UP, "#0", 5, 0, 11, 9), - face(Direction.DOWN, "#0", 11, 0, 5, 9, 0, false, Direction.DOWN) + RedstoneWireBlockStateGenerator.addBoxWithRotatedUvs(model, attachment, tangent, 5.0, 0.0, -1.0, 11.0, 1.0, 8.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#0", 5, 0, 11, 1, 0, false, Direction.NORTH), + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#0", 10, 0, 11, 9, 90, false, null), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#0", 5, 9, 6, 0, 90, false, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#0", 5, 0, 11, 9), + RedstoneWireBlockStateGenerator.face(Direction.DOWN, "#0", 11, 0, 5, 9, 0, false, Direction.DOWN) )); - addBoxWithRotatedUvs(model, attachment, tangent, 6.0, 0.0, -2.0, 10.0, 2.0, 8.0, List.of( - face(Direction.NORTH, "#1", 6, 0, 10, 1, 0, true, Direction.NORTH), - face(Direction.EAST, "#1", 6, 0, 7, 10, 90, true, null), - face(Direction.WEST, "#1", 6, 0, 7, 10, 90, true, null), - face(Direction.UP, "#1", 6, 0, 10, 10, 0, true, null) + RedstoneWireBlockStateGenerator.addBoxWithRotatedUvs(model, attachment, tangent, 6.0, 0.0, -2.0, 10.0, 2.0, 8.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#1", 6, 0, 10, 1, 0, true, Direction.NORTH), + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#1", 6, 0, 7, 10, 90, true, null), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#1", 6, 0, 7, 10, 90, true, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#1", 6, 0, 10, 10, 0, true, null) )); return model; } @@ -173,23 +173,23 @@ private static RegistrumLegacyBlockModelBuilder sideCornerSpModel( RegistrumBlockModelGenerator provider, Direction attachment, int index ) { Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); - RegistrumLegacyBlockModelBuilder model = model(provider, attachment, "side_corner_sp_" + index) - .texture(BASE, AnvilCraft.of("block/redstone_wire_line")) - .texture(OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) + RegistrumLegacyBlockModelBuilder model = RedstoneWireBlockStateGenerator.model(provider, attachment, "side_corner_sp_" + index) + .texture(RedstoneWireBlockStateGenerator.BASE, AnvilCraft.of("block/redstone_wire_line")) + .texture(RedstoneWireBlockStateGenerator.OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) .texture(TextureSlot.PARTICLE, AnvilCraft.of("block/redstone_wire_line")); - addBoxWithRotatedUvs(model, attachment, tangent, 5.0, 0.0, 0.0, 11.0, 1.0, 8.0, List.of( - face(Direction.NORTH, "#0", 5, 0, 11, 1, 0, false, Direction.NORTH), - face(Direction.EAST, "#0", 10, 0, 11, 8, 90, false, null), - face(Direction.WEST, "#0", 5, 8, 6, 0, 90, false, null), - face(Direction.UP, "#0", 5, 0, 11, 8), - face(Direction.DOWN, "#0", 11, 0, 5, 8, 0, false, Direction.DOWN) + RedstoneWireBlockStateGenerator.addBoxWithRotatedUvs(model, attachment, tangent, 5.0, 0.0, 0.0, 11.0, 1.0, 8.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#0", 5, 0, 11, 1, 0, false, Direction.NORTH), + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#0", 10, 0, 11, 8, 90, false, null), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#0", 5, 8, 6, 0, 90, false, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#0", 5, 0, 11, 8), + RedstoneWireBlockStateGenerator.face(Direction.DOWN, "#0", 11, 0, 5, 8, 0, false, Direction.DOWN) )); - addBoxWithRotatedUvs(model, attachment, tangent, 6.0, 0.01, -1.0, 10.0, 2.0, 8.0, List.of( - face(Direction.NORTH, "#1", 6, 0, 10, 1, 0, true, Direction.NORTH), - face(Direction.EAST, "#1", 6, 0, 7, 9, 90, true, null), - face(Direction.WEST, "#1", 6, 0, 7, 9, 90, true, null), - face(Direction.UP, "#1", 6, 0, 10, 9, 0, true, null), - face(Direction.DOWN, "#1", 6, 0, 10, 9, 0, true, null) + RedstoneWireBlockStateGenerator.addBoxWithRotatedUvs(model, attachment, tangent, 6.0, 0.01, -1.0, 10.0, 2.0, 8.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#1", 6, 0, 10, 1, 0, true, Direction.NORTH), + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#1", 6, 0, 7, 9, 90, true, null), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#1", 6, 0, 7, 9, 90, true, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#1", 6, 0, 10, 9, 0, true, null), + RedstoneWireBlockStateGenerator.face(Direction.DOWN, "#1", 6, 0, 10, 9, 0, true, null) )); return model; } @@ -199,25 +199,25 @@ private static RegistrumLegacyBlockModelBuilder upModel( RegistrumBlockModelGenerator provider, Direction attachment, int index ) { Direction tangent = RedstoneWireBlock.getLocalDirection(attachment, index); - RegistrumLegacyBlockModelBuilder model = model(provider, attachment, "up_" + index) - .texture(BASE, AnvilCraft.of("block/redstone_wire_line")) - .texture(OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) + RegistrumLegacyBlockModelBuilder model = RedstoneWireBlockStateGenerator.model(provider, attachment, "up_" + index) + .texture(RedstoneWireBlockStateGenerator.BASE, AnvilCraft.of("block/redstone_wire_line")) + .texture(RedstoneWireBlockStateGenerator.OVERLAY, AnvilCraft.of("block/redstone_wire_line_overlay")) .texture(TextureSlot.PARTICLE, AnvilCraft.of("block/redstone_wire_line")); // 爬升段跨满 16 像素高度,并与基础 side 模型叠加,形成从当前表面到高一格表面的连续导线。 - addBox(model, attachment, tangent, 5.0, 1.0, -0.1, 11.0, 17.0, 1.0, List.of( - face(Direction.NORTH, "#0", 11, 0, 5, 16, 180, false, Direction.NORTH), - face(Direction.EAST, "#0", 10, 0, 11, 16), - face(Direction.SOUTH, "#0", 5, 0, 11, 16), - face(Direction.WEST, "#0", 5, 16, 6, 0, 180, false, null), - face(Direction.UP, "#0", 5, 0, 11, 1, 180, false, Direction.UP), - face(Direction.DOWN, "#0", 5, 15, 11, 16) + RedstoneWireBlockStateGenerator.addBox(model, attachment, tangent, 5.0, 1.0, -0.1, 11.0, 17.0, 1.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.NORTH, "#0", 11, 0, 5, 16, 180, false, Direction.NORTH), + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#0", 10, 0, 11, 16), + RedstoneWireBlockStateGenerator.face(Direction.SOUTH, "#0", 5, 0, 11, 16), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#0", 5, 16, 6, 0, 180, false, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#0", 5, 0, 11, 1, 180, false, Direction.UP), + RedstoneWireBlockStateGenerator.face(Direction.DOWN, "#0", 5, 15, 11, 16) ), attachment.getAxis().isHorizontal()); - addBox(model, attachment, tangent, 6.0, 2.0, 0.0, 10.0, 18.0, 2.0, List.of( - face(Direction.EAST, "#1", 6, 0, 8, 16, 0, true, null), - face(Direction.SOUTH, "#1", 6, 0, 10, 16, 0, true, null), - face(Direction.WEST, "#1", 6, 0, 8, 16, 180, true, null), - face(Direction.UP, "#1", 6, 0, 10, 1, 180, true, Direction.UP), - face(Direction.DOWN, "#1", 6, 15, 10, 16) + RedstoneWireBlockStateGenerator.addBox(model, attachment, tangent, 6.0, 2.0, 0.0, 10.0, 18.0, 2.0, List.of( + RedstoneWireBlockStateGenerator.face(Direction.EAST, "#1", 6, 0, 8, 16, 0, true, null), + RedstoneWireBlockStateGenerator.face(Direction.SOUTH, "#1", 6, 0, 10, 16, 0, true, null), + RedstoneWireBlockStateGenerator.face(Direction.WEST, "#1", 6, 0, 8, 16, 180, true, null), + RedstoneWireBlockStateGenerator.face(Direction.UP, "#1", 6, 0, 10, 1, 180, true, Direction.UP), + RedstoneWireBlockStateGenerator.face(Direction.DOWN, "#1", 6, 15, 10, 16) ), attachment.getAxis().isHorizontal()); return model; } @@ -250,7 +250,7 @@ private static void addBox( double maxZ, List faces ) { - addBox(model, attachment, tangent, minX, minY, minZ, maxX, maxY, maxZ, faces, false); + RedstoneWireBlockStateGenerator.addBox(model, attachment, tangent, minX, minY, minZ, maxX, maxY, maxZ, faces, false); } /** 将局部坐标盒及其各面规格转换为实际世界朝向后写入模型。 */ @@ -277,10 +277,10 @@ private static void addBox( attachment, tangent, spec.direction() ); element.face(worldFace, face -> { - face.texture(textureSlot(spec.texture())) + face.texture(RedstoneWireBlockStateGenerator.textureSlot(spec.texture())) .uvs(spec.u1(), spec.v1(), spec.u2(), spec.v2()) - .rotation(rotation(rotateUvs || spec.transformUv() - ? transformedFaceRotation( + .rotation(RedstoneWireBlockStateGenerator.rotation(rotateUvs || spec.transformUv() + ? RedstoneWireBlockStateGenerator.transformedFaceRotation( attachment, tangent, spec.direction(), spec.rotation() ) : spec.rotation())); @@ -310,7 +310,7 @@ private static void addBoxWithRotatedUvs( double maxZ, List faces ) { - addBox(model, attachment, tangent, minX, minY, minZ, maxX, maxY, maxZ, faces, true); + RedstoneWireBlockStateGenerator.addBox(model, attachment, tangent, minX, minY, minZ, maxX, maxY, maxZ, faces, true); } /** 计算一个局部模型面变换到世界方向后,为保持纹理顶点朝向所需的 UV 旋转。 */ @@ -319,8 +319,8 @@ private static int transformedFaceRotation( ) { Direction worldFace = RedstoneWireBlock.transformDirection(attachment, tangent, localFace); // 用目标面的第一个标准顶点作为锚点,查找局部面哪个顶点在基变换后落到该位置。 - int[] targetVertex = faceVertices(worldFace)[0]; - int[][] localVertices = faceVertices(localFace); + int[] targetVertex = RedstoneWireBlockStateGenerator.faceVertices(worldFace)[0]; + int[][] localVertices = RedstoneWireBlockStateGenerator.faceVertices(localFace); Direction worldX = RedstoneWireBlock.transformDirection(attachment, tangent, Direction.EAST); Direction worldY = RedstoneWireBlock.transformDirection(attachment, tangent, Direction.UP); Direction worldZ = RedstoneWireBlock.transformDirection(attachment, tangent, Direction.SOUTH); @@ -361,7 +361,7 @@ private static int[][] faceVertices(Direction direction) { private static FaceSpec face( Direction direction, String texture, float u1, float v1, float u2, float v2 ) { - return face(direction, texture, u1, v1, u2, v2, 0, false, null); + return RedstoneWireBlockStateGenerator.face(direction, texture, u1, v1, u2, v2, 0, false, null); } /** 创建具有完整渲染参数的模型面规格。 */ @@ -383,7 +383,7 @@ private static FaceSpec face( private static FaceSpec transformedUvFace( boolean transformUv, Direction direction, String texture, float u1, float v1, float u2, float v2 ) { - return transformedUvFace(transformUv, direction, texture, u1, v1, u2, v2, 0, false, null); + return RedstoneWireBlockStateGenerator.transformedUvFace(transformUv, direction, texture, u1, v1, u2, v2, 0, false, null); } /** 创建一个可按条件启用坐标变换后 UV 修正的完整模型面规格。 */ @@ -413,8 +413,8 @@ private static Quadrant rotation(int degrees) { private static TextureSlot textureSlot(String texture) { return switch (texture) { - case "#0" -> BASE; - case "#1" -> OVERLAY; + case "#0" -> RedstoneWireBlockStateGenerator.BASE; + case "#1" -> RedstoneWireBlockStateGenerator.OVERLAY; default -> throw new IllegalArgumentException("Unknown texture slot: " + texture); }; } diff --git a/src/main/java/dev/dubhe/anvilcraft/data/lang/ConfigScreenLang.java b/src/main/java/dev/dubhe/anvilcraft/data/lang/ConfigScreenLang.java index 140162466b..b362184501 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/lang/ConfigScreenLang.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/lang/ConfigScreenLang.java @@ -10,129 +10,129 @@ public class ConfigScreenLang { /// /// @param provider 提供器 public static void init(RegistrumLangProvider provider) { - addOverrides(provider); + ConfigScreenLang.addOverrides(provider); ConfigData.readConfigClass(provider, AnvilCraftServerConfig.class); ConfigData.readConfigClass(provider, AnvilCraftClientConfig.class); } @SuppressWarnings("checkstyle:LineLength") private static void addOverrides(RegistrumLangProvider provider) { - addOverride(provider, "anvilcraft.configuration.anvil_collision_craft_speed", "Anvil Collision Explosion Speed Threshold"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.anvil_collision_craft_speed", "Anvil Collision Explosion Speed Threshold"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.anvil_collision_craft_speed.tooltip", "Minimum collision speed at which anvils explode instead of merely stopping (blocks/tick)" ); - addOverride(provider, "anvilcraft.configuration.render_bloom_effect", "Render Power Transmission Line Bloom"); - addOverride(provider, "anvilcraft.configuration.ground_heave_particles_enabled", "Show Ground Heave Particles"); - addOverride(provider, "anvilcraft.configuration.ground_heave_particle_chance", "Ground Heave Particle Spawn Chance"); - addOverride(provider, "anvilcraft.configuration.load_monitor", "Load Monitor Cooldown"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.render_bloom_effect", "Render Power Transmission Line Bloom"); + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.ground_heave_particles_enabled", "Show Ground Heave Particles"); + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.ground_heave_particle_chance", "Ground Heave Particle Spawn Chance"); + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.load_monitor", "Load Monitor Cooldown"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.load_monitor.tooltip", "Working interval of the Load Monitor in seconds" ); - addOverride(provider, "anvilcraft.configuration.gravitational_lens", "Render Gravitational Lensing Effects"); - addOverride(provider, "anvilcraft.configuration.gravitational_lens.button", "Expand Submenu"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.gravitational_lens", "Render Gravitational Lensing Effects"); + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.gravitational_lens.button", "Expand Submenu"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.tooltip", "Renders gravitational lensing effects for black holes and white holes" ); - addOverride( + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.render_black_hole_lensing", "Render Gravitational Lensing Effects" ); - addOverride( + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.render_black_hole_lensing.tooltip", "Enables the gravitational lensing post-processing effect near black holes and white holes" ); - addOverride(provider, "anvilcraft.configuration.gravitational_lens.max_hole_count", "Maximum Render Count"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.gravitational_lens.max_hole_count", "Maximum Render Count"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.max_hole_count.tooltip", "Maximum number of black hole and white hole lensing effects to render (2-256). Higher values render more effects; lower values improve performance." ); - addOverride(provider, "anvilcraft.configuration.gravitational_lens.lens_strength", "Gravitational Lensing Strength"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.gravitational_lens.lens_strength", "Gravitational Lensing Strength"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.lens_strength.tooltip", "Strength of the lensing distortion around black holes and white holes (higher values bend light more strongly; default: 0.002)" ); - addOverride(provider, "anvilcraft.configuration.gravitational_lens.event_horizon_radius", "Event Horizon Radius"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.gravitational_lens.event_horizon_radius", "Event Horizon Radius"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.event_horizon_radius.tooltip", "Core event horizon radius of black holes and white holes in screen UV units (default: 0.083)" ); - addOverride( + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.lens_perspective_scale", "Gravitational Lensing Perspective Scale" ); - addOverride( + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.lens_perspective_scale.tooltip", "Reference distance for perspective scaling. At this distance the effect matches the configured size; it appears larger at shorter distances." ); - addOverride(provider, "anvilcraft.configuration.gravitational_lens.lens_direction", "Gravitational Lensing Direction"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.gravitational_lens.lens_direction", "Gravitational Lensing Direction"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.gravitational_lens.lens_direction.tooltip", "Positive values create a convex lens that pulls toward the center; negative values create a concave lens that pushes outward. The absolute value determines the curvature." ); - addOverride( + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.iono_craft_backpack_exhaust_particles_enabled", "Show Ionocraft Backpack Exhaust Particles" ); - addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud", "Ionocraft Backpack HUD"); - addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.button", "Expand Submenu"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud", "Ionocraft Backpack HUD"); + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.button", "Expand Submenu"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.iono_craft_backpack_hud.tooltip", "HUD shown while the Ionocraft Backpack is equipped, including its remaining power" ); - addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.enabled", "Enable Ionocraft Backpack HUD"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.enabled", "Enable Ionocraft Backpack HUD"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.iono_craft_backpack_hud.enabled.tooltip", "Shows the Ionocraft Backpack's current power on the HUD when enabled" ); - addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_scale", "HUD Scale"); - addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_scale.tooltip", "HUD scale multiplier"); - addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_x", "HUD X Coordinate"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_scale", "HUD Scale"); + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_scale.tooltip", "HUD scale multiplier"); + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_x", "HUD X Coordinate"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_x.tooltip", "HUD X coordinate (0 at the top-left of the game window; the window width at the bottom-right)" ); - addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_y", "HUD Y Coordinate"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_y", "HUD Y Coordinate"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.iono_craft_backpack_hud.hud_y.tooltip", "HUD Y coordinate (0 at the top-left of the game window; the window height at the bottom-right)" ); - addOverride( + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.iono_craft_backpack_hud.capacitor_count_enabled", "Show Capacitor Count" ); - addOverride( + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.iono_craft_backpack_hud.capacitor_count_enabled.tooltip", "Shows the current number of Capacitors and Super Capacitors in the inventory on the HUD when enabled" ); - addOverride(provider, "anvilcraft.configuration.anvil_hammer_radial_menu_scale", "Anvil Hammer Radial Menu Scale"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.anvil_hammer_radial_menu_scale", "Anvil Hammer Radial Menu Scale"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.anvil_hammer_radial_menu_scale.tooltip", "Adjusts the scale of the Anvil Hammer radial menu" ); - addOverride(provider, "anvilcraft.configuration.laser_ore_cluster_max_size", "Laser Gun Mining Chain Limit"); - addOverride( + ConfigScreenLang.addOverride(provider, "anvilcraft.configuration.laser_ore_cluster_max_size", "Laser Gun Mining Chain Limit"); + ConfigScreenLang.addOverride( provider, "anvilcraft.configuration.laser_ore_cluster_max_size.tooltip", "Maximum ore vein size searched while mining with a laser gun; ore beyond this limit is not chain-mined (default: 64)" diff --git a/src/main/java/dev/dubhe/anvilcraft/data/provider/ModFurnaceFuelProvider.java b/src/main/java/dev/dubhe/anvilcraft/data/provider/ModFurnaceFuelProvider.java index 7d18dc0e26..5a0e2c3998 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/provider/ModFurnaceFuelProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/provider/ModFurnaceFuelProvider.java @@ -17,7 +17,7 @@ public ModFurnaceFuelProvider(PackOutput packOutput, CompletableFuture holder : provider.getRegistries().lookupOrThrow(Registries.BLOCK).listElements().toList()) { HoneycombItem.getWaxed(holder.value().defaultBlockState()) - .ifPresent(state -> blockSmear(provider, Blocks.HONEYCOMB_BLOCK, holder.value(), state.getBlock())); + .ifPresent(state -> BlockSmearRecipeLoader.blockSmear(provider, Blocks.HONEYCOMB_BLOCK, holder.value(), state.getBlock())); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/ConcreteRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/ConcreteRecipeLoader.java index cb689139dd..69218ecf84 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/ConcreteRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/ConcreteRecipeLoader.java @@ -34,9 +34,9 @@ public class ConcreteRecipeLoader { ); public static void init(RegistrumRecipeProvider provider) { - initConcrete(provider); - initCementStaining(provider); - initCementDyeing(provider); + ConcreteRecipeLoader.initConcrete(provider); + ConcreteRecipeLoader.initCementStaining(provider); + ConcreteRecipeLoader.initCementDyeing(provider); } private static void initConcrete(RegistrumRecipeProvider provider) { @@ -83,7 +83,7 @@ private static void initCementDyeing(RegistrumRecipeProvider provider) { for (Color color : Color.values()) { String colorName = color.getSerializedName(); CementCauldronBlock cauldron = ModBlocks.CEMENT_CAULDRONS.get(color).get(); - for (DyeableFamily family : DYEABLE_FAMILIES) { + for (DyeableFamily family : ConcreteRecipeLoader.DYEABLE_FAMILIES) { Item result = BuiltInRegistries.ITEM.getValue( Identifier.withDefaultNamespace("%s_%s".formatted(colorName, family.resultSuffix())) ); diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/ItemCrushRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/ItemCrushRecipeLoader.java index 7a9111b6fc..e47e3786a5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/ItemCrushRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/ItemCrushRecipeLoader.java @@ -66,92 +66,92 @@ public static void init(RegistrumRecipeProvider provider) { .result(Items.BONE_MEAL, 64) .save(provider, AnvilCraft.of("item_crush/bone_meal_from_skeleton_skull")); - armor(provider, Items.CHAINMAIL_HELMET, Items.IRON_CHAIN); - armor(provider, Items.CHAINMAIL_CHESTPLATE, Items.IRON_CHAIN); - armor(provider, Items.CHAINMAIL_LEGGINGS, Items.IRON_CHAIN); - armor(provider, Items.CHAINMAIL_BOOTS, Items.IRON_CHAIN); - - armor(provider, Items.LEATHER_HELMET, Items.LEATHER); - armor(provider, Items.LEATHER_CHESTPLATE, Items.LEATHER); - armor(provider, Items.LEATHER_LEGGINGS, Items.LEATHER); - armor(provider, Items.LEATHER_BOOTS, Items.LEATHER); - armor(provider, Items.LEATHER_HORSE_ARMOR, Items.LEATHER); - - tool(provider, Items.IRON_SWORD, Items.IRON_INGOT); - tool(provider, Items.IRON_PICKAXE, Items.IRON_INGOT); - tool(provider, Items.IRON_AXE, Items.IRON_INGOT); - tool(provider, Items.IRON_HOE, Items.IRON_INGOT); - tool(provider, Items.IRON_SHOVEL, Items.IRON_INGOT); - armor(provider, Items.IRON_HELMET, Items.IRON_INGOT); - armor(provider, Items.IRON_CHESTPLATE, Items.IRON_INGOT); - armor(provider, Items.IRON_LEGGINGS, Items.IRON_INGOT); - armor(provider, Items.IRON_BOOTS, Items.IRON_INGOT); - armor(provider, Items.IRON_HORSE_ARMOR, Items.IRON_INGOT); - - tool(provider, Items.GOLDEN_SWORD, Items.GOLD_INGOT); - tool(provider, Items.GOLDEN_PICKAXE, Items.GOLD_INGOT); - tool(provider, Items.GOLDEN_AXE, Items.GOLD_INGOT); - tool(provider, Items.GOLDEN_HOE, Items.GOLD_INGOT); - tool(provider, Items.GOLDEN_SHOVEL, Items.GOLD_INGOT); - armor(provider, Items.GOLDEN_HELMET, Items.GOLD_INGOT); - armor(provider, Items.GOLDEN_CHESTPLATE, Items.GOLD_INGOT); - armor(provider, Items.GOLDEN_LEGGINGS, Items.GOLD_INGOT); - armor(provider, Items.GOLDEN_BOOTS, Items.GOLD_INGOT); - armor(provider, Items.GOLDEN_HORSE_ARMOR, Items.GOLD_INGOT); - - tool(provider, Items.DIAMOND_SWORD, Items.DIAMOND); - tool(provider, Items.DIAMOND_PICKAXE, Items.DIAMOND); - tool(provider, Items.DIAMOND_AXE, Items.DIAMOND); - tool(provider, Items.DIAMOND_HOE, Items.DIAMOND); - tool(provider, Items.DIAMOND_SHOVEL, Items.DIAMOND); - armor(provider, Items.DIAMOND_HELMET, Items.DIAMOND); - armor(provider, Items.DIAMOND_CHESTPLATE, Items.DIAMOND); - armor(provider, Items.DIAMOND_LEGGINGS, Items.DIAMOND); - armor(provider, Items.DIAMOND_BOOTS, Items.DIAMOND); - armor(provider, Items.DIAMOND_HORSE_ARMOR, Items.DIAMOND); - - blockCrush(provider, Items.STONE, Items.COBBLESTONE); - blockCrush(provider, Items.COBBLESTONE, Items.GRAVEL); - blockCrush(provider, Items.GRAVEL, Items.SAND); - blockCrush(provider, Items.POLISHED_GRANITE, Items.GRANITE); - blockCrush(provider, Items.GRANITE, Items.RED_SAND); - blockCrush(provider, Items.POLISHED_ANDESITE, Items.ANDESITE); - blockCrush(provider, Items.ANDESITE, ModBlocks.CINERITE.get()); - blockCrush(provider, Items.POLISHED_DIORITE, Items.DIORITE); - blockCrush(provider, Items.DIORITE, ModBlocks.QUARTZ_SAND.get()); - blockCrush(provider, Items.STONE_BRICKS, Items.CRACKED_STONE_BRICKS); - blockCrush(provider, Items.DEEPSLATE_BRICKS, Items.CRACKED_DEEPSLATE_BRICKS); - blockCrush(provider, Items.NETHER_BRICKS, Items.CRACKED_NETHER_BRICKS); - blockCrush(provider, Items.DEEPSLATE_TILES, Items.CRACKED_DEEPSLATE_TILES); - blockCrush(provider, Items.POLISHED_BLACKSTONE_BRICKS, Items.CRACKED_POLISHED_BLACKSTONE_BRICKS); - blockCrush(provider, Items.SOUL_SOIL, Items.SOUL_SAND); - blockCrush(provider, Items.NETHERRACK, ModBlocks.NETHER_DUST.get()); - blockCrush(provider, Items.END_STONE, ModBlocks.END_DUST.get()); - - flower(provider, Items.LILY_OF_THE_VALLEY, Items.WHITE_DYE); - flower(provider, Items.AZURE_BLUET, Items.LIGHT_GRAY_DYE); - flower(provider, Items.OXEYE_DAISY, Items.LIGHT_GRAY_DYE); - flower(provider, Items.WHITE_TULIP, Items.LIGHT_GRAY_DYE); - flower(provider, Items.WITHER_ROSE, Items.BLACK_DYE); - flower(provider, Items.POPPY, Items.RED_DYE); - flower(provider, Items.ROSE_BUSH, Items.RED_DYE, 4); - flower(provider, Items.RED_TULIP, Items.RED_DYE); - flower(provider, Items.ORANGE_TULIP, Items.ORANGE_DYE); - flower(provider, Items.TORCHFLOWER, Items.ORANGE_DYE); - flower(provider, Items.DANDELION, Items.YELLOW_DYE); - flower(provider, Items.SUNFLOWER, Items.YELLOW_DYE, 4); - flower(provider, Items.PITCHER_PLANT, Items.CYAN_DYE, 4); - flower(provider, Items.BLUE_ORCHID, Items.LIGHT_BLUE_DYE); - flower(provider, Items.CORNFLOWER, Items.BLUE_DYE); - flower(provider, Items.ALLIUM, Items.MAGENTA_DYE); - flower(provider, Items.LILAC, Items.MAGENTA_DYE, 4); - flower(provider, Items.PEONY, Items.PINK_DYE, 4); - flower(provider, Items.PINK_PETALS, Items.PINK_DYE); - flower(provider, Items.PINK_TULIP, Items.PINK_DYE); - flower(provider, Items.BONE_MEAL, Items.WHITE_DYE); - flower(provider, Items.INK_SAC, Items.BLACK_DYE); - flower(provider, Items.COCOA_BEANS, Items.BROWN_DYE); - flower(provider, Items.LAPIS_LAZULI, Items.BLUE_DYE); + ItemCrushRecipeLoader.armor(provider, Items.CHAINMAIL_HELMET, Items.IRON_CHAIN); + ItemCrushRecipeLoader.armor(provider, Items.CHAINMAIL_CHESTPLATE, Items.IRON_CHAIN); + ItemCrushRecipeLoader.armor(provider, Items.CHAINMAIL_LEGGINGS, Items.IRON_CHAIN); + ItemCrushRecipeLoader.armor(provider, Items.CHAINMAIL_BOOTS, Items.IRON_CHAIN); + + ItemCrushRecipeLoader.armor(provider, Items.LEATHER_HELMET, Items.LEATHER); + ItemCrushRecipeLoader.armor(provider, Items.LEATHER_CHESTPLATE, Items.LEATHER); + ItemCrushRecipeLoader.armor(provider, Items.LEATHER_LEGGINGS, Items.LEATHER); + ItemCrushRecipeLoader.armor(provider, Items.LEATHER_BOOTS, Items.LEATHER); + ItemCrushRecipeLoader.armor(provider, Items.LEATHER_HORSE_ARMOR, Items.LEATHER); + + ItemCrushRecipeLoader.tool(provider, Items.IRON_SWORD, Items.IRON_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.IRON_PICKAXE, Items.IRON_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.IRON_AXE, Items.IRON_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.IRON_HOE, Items.IRON_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.IRON_SHOVEL, Items.IRON_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.IRON_HELMET, Items.IRON_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.IRON_CHESTPLATE, Items.IRON_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.IRON_LEGGINGS, Items.IRON_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.IRON_BOOTS, Items.IRON_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.IRON_HORSE_ARMOR, Items.IRON_INGOT); + + ItemCrushRecipeLoader.tool(provider, Items.GOLDEN_SWORD, Items.GOLD_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.GOLDEN_PICKAXE, Items.GOLD_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.GOLDEN_AXE, Items.GOLD_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.GOLDEN_HOE, Items.GOLD_INGOT); + ItemCrushRecipeLoader.tool(provider, Items.GOLDEN_SHOVEL, Items.GOLD_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.GOLDEN_HELMET, Items.GOLD_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.GOLDEN_CHESTPLATE, Items.GOLD_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.GOLDEN_LEGGINGS, Items.GOLD_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.GOLDEN_BOOTS, Items.GOLD_INGOT); + ItemCrushRecipeLoader.armor(provider, Items.GOLDEN_HORSE_ARMOR, Items.GOLD_INGOT); + + ItemCrushRecipeLoader.tool(provider, Items.DIAMOND_SWORD, Items.DIAMOND); + ItemCrushRecipeLoader.tool(provider, Items.DIAMOND_PICKAXE, Items.DIAMOND); + ItemCrushRecipeLoader.tool(provider, Items.DIAMOND_AXE, Items.DIAMOND); + ItemCrushRecipeLoader.tool(provider, Items.DIAMOND_HOE, Items.DIAMOND); + ItemCrushRecipeLoader.tool(provider, Items.DIAMOND_SHOVEL, Items.DIAMOND); + ItemCrushRecipeLoader.armor(provider, Items.DIAMOND_HELMET, Items.DIAMOND); + ItemCrushRecipeLoader.armor(provider, Items.DIAMOND_CHESTPLATE, Items.DIAMOND); + ItemCrushRecipeLoader.armor(provider, Items.DIAMOND_LEGGINGS, Items.DIAMOND); + ItemCrushRecipeLoader.armor(provider, Items.DIAMOND_BOOTS, Items.DIAMOND); + ItemCrushRecipeLoader.armor(provider, Items.DIAMOND_HORSE_ARMOR, Items.DIAMOND); + + ItemCrushRecipeLoader.blockCrush(provider, Items.STONE, Items.COBBLESTONE); + ItemCrushRecipeLoader.blockCrush(provider, Items.COBBLESTONE, Items.GRAVEL); + ItemCrushRecipeLoader.blockCrush(provider, Items.GRAVEL, Items.SAND); + ItemCrushRecipeLoader.blockCrush(provider, Items.POLISHED_GRANITE, Items.GRANITE); + ItemCrushRecipeLoader.blockCrush(provider, Items.GRANITE, Items.RED_SAND); + ItemCrushRecipeLoader.blockCrush(provider, Items.POLISHED_ANDESITE, Items.ANDESITE); + ItemCrushRecipeLoader.blockCrush(provider, Items.ANDESITE, ModBlocks.CINERITE.get()); + ItemCrushRecipeLoader.blockCrush(provider, Items.POLISHED_DIORITE, Items.DIORITE); + ItemCrushRecipeLoader.blockCrush(provider, Items.DIORITE, ModBlocks.QUARTZ_SAND.get()); + ItemCrushRecipeLoader.blockCrush(provider, Items.STONE_BRICKS, Items.CRACKED_STONE_BRICKS); + ItemCrushRecipeLoader.blockCrush(provider, Items.DEEPSLATE_BRICKS, Items.CRACKED_DEEPSLATE_BRICKS); + ItemCrushRecipeLoader.blockCrush(provider, Items.NETHER_BRICKS, Items.CRACKED_NETHER_BRICKS); + ItemCrushRecipeLoader.blockCrush(provider, Items.DEEPSLATE_TILES, Items.CRACKED_DEEPSLATE_TILES); + ItemCrushRecipeLoader.blockCrush(provider, Items.POLISHED_BLACKSTONE_BRICKS, Items.CRACKED_POLISHED_BLACKSTONE_BRICKS); + ItemCrushRecipeLoader.blockCrush(provider, Items.SOUL_SOIL, Items.SOUL_SAND); + ItemCrushRecipeLoader.blockCrush(provider, Items.NETHERRACK, ModBlocks.NETHER_DUST.get()); + ItemCrushRecipeLoader.blockCrush(provider, Items.END_STONE, ModBlocks.END_DUST.get()); + + ItemCrushRecipeLoader.flower(provider, Items.LILY_OF_THE_VALLEY, Items.WHITE_DYE); + ItemCrushRecipeLoader.flower(provider, Items.AZURE_BLUET, Items.LIGHT_GRAY_DYE); + ItemCrushRecipeLoader.flower(provider, Items.OXEYE_DAISY, Items.LIGHT_GRAY_DYE); + ItemCrushRecipeLoader.flower(provider, Items.WHITE_TULIP, Items.LIGHT_GRAY_DYE); + ItemCrushRecipeLoader.flower(provider, Items.WITHER_ROSE, Items.BLACK_DYE); + ItemCrushRecipeLoader.flower(provider, Items.POPPY, Items.RED_DYE); + ItemCrushRecipeLoader.flower(provider, Items.ROSE_BUSH, Items.RED_DYE, 4); + ItemCrushRecipeLoader.flower(provider, Items.RED_TULIP, Items.RED_DYE); + ItemCrushRecipeLoader.flower(provider, Items.ORANGE_TULIP, Items.ORANGE_DYE); + ItemCrushRecipeLoader.flower(provider, Items.TORCHFLOWER, Items.ORANGE_DYE); + ItemCrushRecipeLoader.flower(provider, Items.DANDELION, Items.YELLOW_DYE); + ItemCrushRecipeLoader.flower(provider, Items.SUNFLOWER, Items.YELLOW_DYE, 4); + ItemCrushRecipeLoader.flower(provider, Items.PITCHER_PLANT, Items.CYAN_DYE, 4); + ItemCrushRecipeLoader.flower(provider, Items.BLUE_ORCHID, Items.LIGHT_BLUE_DYE); + ItemCrushRecipeLoader.flower(provider, Items.CORNFLOWER, Items.BLUE_DYE); + ItemCrushRecipeLoader.flower(provider, Items.ALLIUM, Items.MAGENTA_DYE); + ItemCrushRecipeLoader.flower(provider, Items.LILAC, Items.MAGENTA_DYE, 4); + ItemCrushRecipeLoader.flower(provider, Items.PEONY, Items.PINK_DYE, 4); + ItemCrushRecipeLoader.flower(provider, Items.PINK_PETALS, Items.PINK_DYE); + ItemCrushRecipeLoader.flower(provider, Items.PINK_TULIP, Items.PINK_DYE); + ItemCrushRecipeLoader.flower(provider, Items.BONE_MEAL, Items.WHITE_DYE); + ItemCrushRecipeLoader.flower(provider, Items.INK_SAC, Items.BLACK_DYE); + ItemCrushRecipeLoader.flower(provider, Items.COCOA_BEANS, Items.BROWN_DYE); + ItemCrushRecipeLoader.flower(provider, Items.LAPIS_LAZULI, Items.BLUE_DYE); } private static void tool(RegistrumRecipeProvider provider, ItemLike tool, ItemLike result) { diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/MassInjectRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/MassInjectRecipeLoader.java index b4322f0975..79c1087515 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/MassInjectRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/MassInjectRecipeLoader.java @@ -63,7 +63,7 @@ public static void init(RegistrumRecipeProvider provider) { .put(ModItemTags.FROST_METAL_INGOTS, 300) .put(ModItemTags.STORAGE_BLOCKS_FROST_METAL, 3000) .build(); - tagRecipes.forEach((tag, mass) -> addTag(provider, tag, mass)); + tagRecipes.forEach((tag, mass) -> MassInjectRecipeLoader.addTag(provider, tag, mass)); ImmutableMap itemRecipes = ImmutableMap.builder() .put(ModItems.CURSED_GOLD_NUGGET, 25) @@ -77,7 +77,7 @@ public static void init(RegistrumRecipeProvider provider) { .put(ModBlocks.HEAVY_IRON_BLOCK, 8000) .put(ModBlocks.EMBER_METAL_BLOCK, 20000) .build(); - itemRecipes.forEach((item, mass) -> addItem(provider, item, mass)); + itemRecipes.forEach((item, mass) -> MassInjectRecipeLoader.addItem(provider, item, mass)); } private static void addTag(RegistrumRecipeProvider provider, TagKey tag, int mass) { diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/MineralFountainRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/MineralFountainRecipeLoader.java index 582945cf13..f5ac7842ae 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/MineralFountainRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/MineralFountainRecipeLoader.java @@ -15,16 +15,23 @@ public class MineralFountainRecipeLoader { public static void init(RegistrumRecipeProvider provider) { - mineralFountainDeepslate(provider, Tags.Blocks.STORAGE_BLOCKS_RAW_COPPER, Blocks.DEEPSLATE_COPPER_ORE); - mineralFountainDeepslate(provider, Tags.Blocks.STORAGE_BLOCKS_RAW_IRON, Blocks.DEEPSLATE_IRON_ORE); - mineralFountainDeepslate(provider, Tags.Blocks.STORAGE_BLOCKS_RAW_GOLD, Blocks.DEEPSLATE_GOLD_ORE); - mineralFountainDeepslate(provider, ModBlockTags.STORAGE_BLOCKS_RAW_ZINC, ModBlocks.DEEPSLATE_ZINC_ORE.get()); - mineralFountainDeepslate(provider, ModBlockTags.STORAGE_BLOCKS_RAW_TIN, ModBlocks.DEEPSLATE_TIN_ORE.get()); - mineralFountainDeepslate(provider, ModBlockTags.STORAGE_BLOCKS_RAW_LEAD, ModBlocks.DEEPSLATE_LEAD_ORE.get()); - mineralFountainDeepslate(provider, ModBlockTags.STORAGE_BLOCKS_RAW_SILVER, ModBlocks.DEEPSLATE_SILVER_ORE.get()); - mineralFountainDeepslate(provider, ModBlockTags.STORAGE_BLOCKS_RAW_TITANIUM, ModBlocks.DEEPSLATE_TITANIUM_ORE.get()); - mineralFountainDeepslate(provider, ModBlockTags.STORAGE_BLOCKS_RAW_TUNGSTEN, ModBlocks.DEEPSLATE_TUNGSTEN_ORE.get()); - mineralFountainDeepslate(provider, ModBlockTags.STORAGE_BLOCKS_RAW_URANIUM, ModBlocks.DEEPSLATE_URANIUM_ORE.get()); + MineralFountainRecipeLoader.mineralFountainDeepslate(provider, Tags.Blocks.STORAGE_BLOCKS_RAW_COPPER, Blocks.DEEPSLATE_COPPER_ORE); + MineralFountainRecipeLoader.mineralFountainDeepslate(provider, Tags.Blocks.STORAGE_BLOCKS_RAW_IRON, Blocks.DEEPSLATE_IRON_ORE); + MineralFountainRecipeLoader.mineralFountainDeepslate(provider, Tags.Blocks.STORAGE_BLOCKS_RAW_GOLD, Blocks.DEEPSLATE_GOLD_ORE); + MineralFountainRecipeLoader.mineralFountainDeepslate( + provider, ModBlockTags.STORAGE_BLOCKS_RAW_ZINC, ModBlocks.DEEPSLATE_ZINC_ORE.get()); + MineralFountainRecipeLoader.mineralFountainDeepslate( + provider, ModBlockTags.STORAGE_BLOCKS_RAW_TIN, ModBlocks.DEEPSLATE_TIN_ORE.get()); + MineralFountainRecipeLoader.mineralFountainDeepslate( + provider, ModBlockTags.STORAGE_BLOCKS_RAW_LEAD, ModBlocks.DEEPSLATE_LEAD_ORE.get()); + MineralFountainRecipeLoader.mineralFountainDeepslate( + provider, ModBlockTags.STORAGE_BLOCKS_RAW_SILVER, ModBlocks.DEEPSLATE_SILVER_ORE.get()); + MineralFountainRecipeLoader.mineralFountainDeepslate( + provider, ModBlockTags.STORAGE_BLOCKS_RAW_TITANIUM, ModBlocks.DEEPSLATE_TITANIUM_ORE.get()); + MineralFountainRecipeLoader.mineralFountainDeepslate( + provider, ModBlockTags.STORAGE_BLOCKS_RAW_TUNGSTEN, ModBlocks.DEEPSLATE_TUNGSTEN_ORE.get()); + MineralFountainRecipeLoader.mineralFountainDeepslate( + provider, ModBlockTags.STORAGE_BLOCKS_RAW_URANIUM, ModBlocks.DEEPSLATE_URANIUM_ORE.get()); MineralFountainChanceRecipe.builder() diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/MultiBlockConversionRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/MultiBlockConversionRecipeLoader.java index 45163cb73b..1cb2ec62cf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/MultiBlockConversionRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/MultiBlockConversionRecipeLoader.java @@ -559,33 +559,33 @@ public static void init(RegistrumRecipeProvider provider) { .outputLayer("ABC", "DEF", "GHI") .outputLayer("JKL", "MNO", "PQR") .outputLayer("STU", "VWX", "YZ[") - .outputSymbol('A', largeCauldronPart(Cube3x3PartHalf.BOTTOM_WN)) - .outputSymbol('B', largeCauldronPart(Cube3x3PartHalf.BOTTOM_N)) - .outputSymbol('C', largeCauldronPart(Cube3x3PartHalf.BOTTOM_EN)) - .outputSymbol('D', largeCauldronPart(Cube3x3PartHalf.BOTTOM_W)) - .outputSymbol('E', largeCauldronPart(Cube3x3PartHalf.BOTTOM_CENTER)) - .outputSymbol('F', largeCauldronPart(Cube3x3PartHalf.BOTTOM_E)) - .outputSymbol('G', largeCauldronPart(Cube3x3PartHalf.BOTTOM_WS)) - .outputSymbol('H', largeCauldronPart(Cube3x3PartHalf.BOTTOM_S)) - .outputSymbol('I', largeCauldronPart(Cube3x3PartHalf.BOTTOM_ES)) - .outputSymbol('J', largeCauldronPart(Cube3x3PartHalf.MID_WN)) - .outputSymbol('K', largeCauldronPart(Cube3x3PartHalf.MID_N)) - .outputSymbol('L', largeCauldronPart(Cube3x3PartHalf.MID_EN)) - .outputSymbol('M', largeCauldronPart(Cube3x3PartHalf.MID_W)) - .outputSymbol('N', largeCauldronPart(Cube3x3PartHalf.MID_CENTER)) - .outputSymbol('O', largeCauldronPart(Cube3x3PartHalf.MID_E)) - .outputSymbol('P', largeCauldronPart(Cube3x3PartHalf.MID_WS)) - .outputSymbol('Q', largeCauldronPart(Cube3x3PartHalf.MID_S)) - .outputSymbol('R', largeCauldronPart(Cube3x3PartHalf.MID_ES)) - .outputSymbol('S', largeCauldronPart(Cube3x3PartHalf.TOP_WN)) - .outputSymbol('T', largeCauldronPart(Cube3x3PartHalf.TOP_N)) - .outputSymbol('U', largeCauldronPart(Cube3x3PartHalf.TOP_EN)) - .outputSymbol('V', largeCauldronPart(Cube3x3PartHalf.TOP_W)) - .outputSymbol('W', largeCauldronPart(Cube3x3PartHalf.TOP_CENTER)) - .outputSymbol('X', largeCauldronPart(Cube3x3PartHalf.TOP_E)) - .outputSymbol('Y', largeCauldronPart(Cube3x3PartHalf.TOP_WS)) - .outputSymbol('Z', largeCauldronPart(Cube3x3PartHalf.TOP_S)) - .outputSymbol('[', largeCauldronPart(Cube3x3PartHalf.TOP_ES)) + .outputSymbol('A', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_WN)) + .outputSymbol('B', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_N)) + .outputSymbol('C', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_EN)) + .outputSymbol('D', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_W)) + .outputSymbol('E', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_CENTER)) + .outputSymbol('F', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_E)) + .outputSymbol('G', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_WS)) + .outputSymbol('H', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_S)) + .outputSymbol('I', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.BOTTOM_ES)) + .outputSymbol('J', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_WN)) + .outputSymbol('K', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_N)) + .outputSymbol('L', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_EN)) + .outputSymbol('M', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_W)) + .outputSymbol('N', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_CENTER)) + .outputSymbol('O', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_E)) + .outputSymbol('P', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_WS)) + .outputSymbol('Q', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_S)) + .outputSymbol('R', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.MID_ES)) + .outputSymbol('S', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_WN)) + .outputSymbol('T', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_N)) + .outputSymbol('U', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_EN)) + .outputSymbol('V', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_W)) + .outputSymbol('W', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_CENTER)) + .outputSymbol('X', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_E)) + .outputSymbol('Y', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_WS)) + .outputSymbol('Z', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_S)) + .outputSymbol('[', MultiBlockConversionRecipeLoader.largeCauldronPart(Cube3x3PartHalf.TOP_ES)) .save(provider, AnvilCraft.of("multiblock_conversion/large_cauldron")); diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/PlanetResourceRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/PlanetResourceRecipeLoader.java index 1f3f60479d..6d9ec4e09f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/PlanetResourceRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/PlanetResourceRecipeLoader.java @@ -22,13 +22,13 @@ public class PlanetResourceRecipeLoader { public static void init(RegistrumRecipeProvider provider) { - createMineralRecipe(provider); - createFluidRecipes(provider); - createGiantItemRecipes(provider); - createGiantFluidRecipes(provider); - createBiologicalRecipe(provider); - createOfferingRecipe(provider); - createWastelandRecipe(provider); + PlanetResourceRecipeLoader.createMineralRecipe(provider); + PlanetResourceRecipeLoader.createFluidRecipes(provider); + PlanetResourceRecipeLoader.createGiantItemRecipes(provider); + PlanetResourceRecipeLoader.createGiantFluidRecipes(provider); + PlanetResourceRecipeLoader.createBiologicalRecipe(provider); + PlanetResourceRecipeLoader.createOfferingRecipe(provider); + PlanetResourceRecipeLoader.createWastelandRecipe(provider); } private static void saveRecipe(RecipeOutput output, String name, PlanetResourceRecipe recipe) { @@ -42,7 +42,7 @@ private static void saveRecipe(RecipeOutput output, String name, PlanetResourceR } private static void createMineralRecipe(RegistrumRecipeProvider provider) { - saveRecipe(provider, "mineral", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "mineral", new PlanetResourceRecipe( PlanetResourceRecipe.Category.MINERAL, Optional.of(new PlanetResourceRecipe.MineralData( "c:raw_materials", "anvilcraft:non_planetary_minerals", 10 @@ -52,7 +52,7 @@ private static void createMineralRecipe(RegistrumRecipeProvider provider) { } private static void createFluidRecipes(RegistrumRecipeProvider provider) { - saveRecipe(provider, "fluid_water", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "fluid_water", new PlanetResourceRecipe( PlanetResourceRecipe.Category.FLUID, Optional.empty(), Optional.of(new PlanetResourceRecipe.FluidData( @@ -61,7 +61,7 @@ private static void createFluidRecipes(RegistrumRecipeProvider provider) { Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty() )); - saveRecipe(provider, "fluid_lava", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "fluid_lava", new PlanetResourceRecipe( PlanetResourceRecipe.Category.FLUID, Optional.empty(), Optional.of(new PlanetResourceRecipe.FluidData( @@ -72,7 +72,7 @@ private static void createFluidRecipes(RegistrumRecipeProvider provider) { } private static void createGiantItemRecipes(RegistrumRecipeProvider provider) { - saveRecipe(provider, "giant_item_ice", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "giant_item_ice", new PlanetResourceRecipe( PlanetResourceRecipe.Category.GIANT_ITEM, Optional.empty(), Optional.empty(), Optional.of(new PlanetResourceRecipe.GiantData( @@ -87,7 +87,7 @@ private static void createGiantItemRecipes(RegistrumRecipeProvider provider) { } private static void createGiantFluidRecipes(RegistrumRecipeProvider provider) { - saveRecipe(provider, "giant_fluid_gas", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "giant_fluid_gas", new PlanetResourceRecipe( PlanetResourceRecipe.Category.GIANT_FLUID, Optional.empty(), Optional.empty(), Optional.of(new PlanetResourceRecipe.GiantData( @@ -98,7 +98,7 @@ private static void createGiantFluidRecipes(RegistrumRecipeProvider provider) { Optional.empty(), Optional.empty(), Optional.empty() )); - saveRecipe(provider, "giant_fluid_ice", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "giant_fluid_ice", new PlanetResourceRecipe( PlanetResourceRecipe.Category.GIANT_FLUID, Optional.empty(), Optional.empty(), Optional.of(new PlanetResourceRecipe.GiantData( @@ -112,7 +112,7 @@ private static void createGiantFluidRecipes(RegistrumRecipeProvider provider) { } private static void createBiologicalRecipe(RegistrumRecipeProvider provider) { - saveRecipe(provider, "biological", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "biological", new PlanetResourceRecipe( PlanetResourceRecipe.Category.BIOLOGICAL, Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(new PlanetResourceRecipe.BiologicalData( @@ -130,7 +130,7 @@ private static void createBiologicalRecipe(RegistrumRecipeProvider provider) { } private static void createOfferingRecipe(RegistrumRecipeProvider provider) { - saveRecipe(provider, "offering", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "offering", new PlanetResourceRecipe( PlanetResourceRecipe.Category.OFFERING, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(new PlanetResourceRecipe.OfferingData( @@ -148,7 +148,7 @@ private static void createOfferingRecipe(RegistrumRecipeProvider provider) { } private static void createWastelandRecipe(RegistrumRecipeProvider provider) { - saveRecipe(provider, "wasteland", new PlanetResourceRecipe( + PlanetResourceRecipeLoader.saveRecipe(provider, "wasteland", new PlanetResourceRecipe( PlanetResourceRecipe.Category.WASTELAND, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(new PlanetResourceRecipe.WastelandData( diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/RegistrumBlockRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/RegistrumBlockRecipeLoader.java index a75d1a82f7..3c9f0941a6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/RegistrumBlockRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/RegistrumBlockRecipeLoader.java @@ -240,7 +240,7 @@ public static NonNullBiConsumer, Regi .define('A', parent) .unlockedBy(AnvilCraftDatagen.hasItem(parent.asItem()), AnvilCraftDatagen.has(lookup, parent)) .save(provider); - stonecutting(Ingredient.of(parent), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(parent), ctx.get(), 2) .unlockedBy(AnvilCraftDatagen.hasItem(parent), AnvilCraftDatagen.has(lookup, parent)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); }; @@ -258,7 +258,7 @@ public static NonNullBiConsumer, Regi .define('A', parent) .unlockedBy(AnvilCraftDatagen.hasItem(parent.asItem()), AnvilCraftDatagen.has(lookup, parent)) .save(provider); - stonecutting(Ingredient.of(parent), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(parent), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(parent), AnvilCraftDatagen.has(lookup, parent)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); }; @@ -275,7 +275,7 @@ public static NonNullBiConsumer, Regi .define('A', parent) .unlockedBy(AnvilCraftDatagen.hasItem(parent.asItem()), AnvilCraftDatagen.has(lookup, parent)) .save(provider); - stonecutting(Ingredient.of(parent), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(parent), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(parent), AnvilCraftDatagen.has(lookup, parent)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); }; @@ -687,13 +687,13 @@ public static void powerConverterSmall(DataGenContext void powerConverterMiddle(DataGenContext void royalSteelBlock(DataGenContext ct public static void smoothRoyalSteelBlock(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/smooth_royal_steel_block")); } public static void cutRoyalSteelBlock(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_royal_steel_block")); } public static void cutRoyalSteelPillar(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.CUT_ROYAL_STEEL_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_ROYAL_STEEL_BLOCK), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_royal_steel_pillar_from_cut_royal_steel_block")); - stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_royal_steel_pillar_from_royal_steel_block")); } public static void cutRoyalSteelSlab(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_royal_steel_slab_from_royal_steel_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_ROYAL_STEEL_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_ROYAL_STEEL_BLOCK), ctx.get(), 2) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_royal_steel_slab_from_cut_royal_steel_block")); } public static void cutRoyalSteelStairs(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.ROYAL_STEEL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_royal_steel_stairs_from_royal_steel_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_ROYAL_STEEL_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_ROYAL_STEEL_BLOCK), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.ROYAL_STEEL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.ROYAL_STEEL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_royal_steel_stairs_from_cut_royal_steel_block")); } @@ -1380,37 +1380,37 @@ public static void frostMetalBlock(DataGenContext ct public static void cutFrostMetalBlock(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FROST_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FROST_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_frost_metal_block")); } public static void cutFrostMetalPillar(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FROST_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FROST_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_frost_metal_pillar_from_frost_metal_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_FROST_METAL_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_FROST_METAL_BLOCK), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FROST_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FROST_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_frost_metal_pillar_from_cut_frost_metal_block")); } public static void cutFrostMetalSlab(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FROST_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FROST_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_frost_metal_slab_from_frost_metal_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_FROST_METAL_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_FROST_METAL_BLOCK), ctx.get(), 2) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FROST_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FROST_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_frost_metal_slab_from_cut_frost_metal_block")); } public static void cutFrostMetalStairs(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.FROST_METAL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FROST_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FROST_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_frost_metal_stairs_from_frost_metal_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_FROST_METAL_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_FROST_METAL_BLOCK), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FROST_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FROST_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_frost_metal_stairs_from_cut_frost_metal_block")); } @@ -1428,30 +1428,30 @@ public static void emberMetalBlock(DataGenContext ct public static void cutEmberMetalBlock(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.EMBER_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.EMBER_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_ember_metal_block")); } public static void cutEmberMetalPillar(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.EMBER_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.EMBER_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_ember_metal_pillar_from_ember_metal_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_EMBER_METAL_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_EMBER_METAL_BLOCK), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.EMBER_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.EMBER_METAL_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_ember_metal_pillar_from_cut_ember_metal_block")); } public static void cutEmberMetalSlab(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 8) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.EMBER_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.EMBER_METAL_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/cut_ember_metal_slab_from_ember_metal_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_EMBER_METAL_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_EMBER_METAL_BLOCK), ctx.get(), 2) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_EMBER_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_EMBER_METAL_BLOCK) @@ -1461,13 +1461,13 @@ public static void cutEmberMetalSlab(DataGenContext public static void cutEmberMetalStairs(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.EMBER_METAL_BLOCK), ctx.get(), 4) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_EMBER_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_EMBER_METAL_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/cut_ember_metal_stairs_from_ember_metal_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_EMBER_METAL_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_EMBER_METAL_BLOCK), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_EMBER_METAL_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_EMBER_METAL_BLOCK) @@ -1502,14 +1502,14 @@ public static void heavyIronBlock(DataGenContext ctx public static void polishedHeavyIronBlock(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 2) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); } public static void polishedHeavyIronSlab(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_heavy_iron_block")); SingleItemRecipeBuilder.stonecutting( @@ -1527,13 +1527,13 @@ public static void polishedHeavyIronSlab(DataGenContext void polishedHeavyIronStairs(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 2) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.POLISHED_HEAVY_IRON_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.POLISHED_HEAVY_IRON_BLOCK), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.POLISHED_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) @@ -1543,7 +1543,7 @@ public static void polishedHeavyIronStairs(DataGenContext void cutHeavyIronBlock(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); SingleItemRecipeBuilder.stonecutting( @@ -1560,7 +1560,7 @@ public static void cutHeavyIronBlock(DataGenContext public static void cutHeavyIronSlab(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 16) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 16) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_heavy_iron_block")); SingleItemRecipeBuilder.stonecutting( @@ -1572,7 +1572,7 @@ public static void cutHeavyIronSlab(DataGenContext c AnvilCraftDatagen.hasItem(ModBlocks.POLISHED_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) ).save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get(), 2) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_BLOCK) @@ -1582,7 +1582,7 @@ public static void cutHeavyIronSlab(DataGenContext c public static void cutHeavyIronStairs(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_heavy_iron_block")); SingleItemRecipeBuilder.stonecutting( @@ -1594,7 +1594,7 @@ public static void cutHeavyIronStairs(DataGenContext AnvilCraftDatagen.hasItem(ModBlocks.POLISHED_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) ).save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_BLOCK) @@ -1604,7 +1604,7 @@ public static void cutHeavyIronStairs(DataGenContext public static void heavyIronPlate(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 16) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 16) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); SingleItemRecipeBuilder.stonecutting( @@ -1618,7 +1618,7 @@ public static void heavyIronPlate(DataGenContext ctx AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get(), 2) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_BLOCK) @@ -1635,7 +1635,7 @@ public static void heavyIronPlate(DataGenContext ctx AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_SLAB) ) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_slab")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_SLAB), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_SLAB), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_SLAB), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_SLAB) @@ -1645,7 +1645,7 @@ public static void heavyIronPlate(DataGenContext ctx public static void heavyIronColumn(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); SingleItemRecipeBuilder.stonecutting( @@ -1659,7 +1659,7 @@ public static void heavyIronColumn(DataGenContext ct AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_BLOCK) @@ -1669,7 +1669,7 @@ public static void heavyIronColumn(DataGenContext ct public static void heavyIronBeam(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); SingleItemRecipeBuilder.stonecutting( @@ -1683,7 +1683,7 @@ public static void heavyIronBeam(DataGenContext ctx, AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_BLOCK) @@ -1693,7 +1693,7 @@ public static void heavyIronBeam(DataGenContext ctx, public static void heavyIronWall(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); SingleItemRecipeBuilder.stonecutting( @@ -1707,7 +1707,7 @@ public static void heavyIronWall(DataGenContext ctx, AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_BLOCK) @@ -1717,7 +1717,7 @@ public static void heavyIronWall(DataGenContext ctx, public static void heavyIronDoor(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 4) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 4) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); SingleItemRecipeBuilder.stonecutting( @@ -1735,7 +1735,7 @@ public static void heavyIronDoor(DataGenContext ctx, public static void heavyIronTrapdoor(DataGenContext ctx, RegistrumRecipeProvider provider) { HolderGetter lookup = provider.getItems(); - stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.HEAVY_IRON_BLOCK), ctx.get(), 8) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.HEAVY_IRON_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); SingleItemRecipeBuilder.stonecutting( @@ -1749,7 +1749,7 @@ public static void heavyIronTrapdoor(DataGenContext AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_HEAVY_IRON_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName() + "_from_polished_heavy_iron_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_HEAVY_IRON_BLOCK), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.CUT_HEAVY_IRON_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_HEAVY_IRON_BLOCK) @@ -1992,7 +1992,7 @@ public static void chocolateSlab(DataGenContext ctx, .define('A', ModBlocks.CHOCOLATE_BLOCK) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.CHOCOLATE_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CHOCOLATE_BLOCK)) .save(provider); - stonecutting(Ingredient.of(ModBlocks.CHOCOLATE_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CHOCOLATE_BLOCK), ctx.get(), 2) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.CHOCOLATE_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CHOCOLATE_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); } @@ -2007,7 +2007,7 @@ public static void blackChocolateSlab(DataGenContext AnvilCraftDatagen.has(lookup, ModBlocks.BLACK_CHOCOLATE_BLOCK) ) .save(provider); - stonecutting(Ingredient.of(ModBlocks.BLACK_CHOCOLATE_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.BLACK_CHOCOLATE_BLOCK), ctx.get(), 2) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.BLACK_CHOCOLATE_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.BLACK_CHOCOLATE_BLOCK) @@ -2025,7 +2025,7 @@ public static void whiteChocolateSlab(DataGenContext AnvilCraftDatagen.has(lookup, ModBlocks.WHITE_CHOCOLATE_BLOCK) ) .save(provider); - stonecutting(Ingredient.of(ModBlocks.WHITE_CHOCOLATE_BLOCK), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.WHITE_CHOCOLATE_BLOCK), ctx.get(), 2) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.WHITE_CHOCOLATE_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.WHITE_CHOCOLATE_BLOCK) @@ -2042,7 +2042,7 @@ public static void chocolateStairs(DataGenContext ct .define('A', ModBlocks.CHOCOLATE_BLOCK) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.CHOCOLATE_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CHOCOLATE_BLOCK)) .save(provider); - stonecutting(Ingredient.of(ModBlocks.CHOCOLATE_BLOCK), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CHOCOLATE_BLOCK), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.CHOCOLATE_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CHOCOLATE_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/" + ctx.getName())); } @@ -2059,7 +2059,7 @@ public static void blackChocolateStairs(DataGenContext void whiteChocolateStairs(DataGenContext void polishedFlintBlock(DataGenContext .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FLINT_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FLINT_BLOCK)) .save(provider, AnvilCraft.recipe("shaped/polished_flint_block")); - stonecutting(Ingredient.of(ModBlocks.FLINT_BLOCK.get()), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.FLINT_BLOCK.get()), ctx.get()) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FLINT_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FLINT_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/polished_flint_block")); } @@ -2332,14 +2332,14 @@ public static void cutFlintBlock(DataGenContext ctx, ) .save(provider, AnvilCraft.recipe("shaped/cut_flint_block")); - stonecutting(Ingredient.of(ModBlocks.FLINT_BLOCK.get()), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.FLINT_BLOCK.get()), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.FLINT_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FLINT_BLOCK) ) .save(provider, AnvilCraft.recipe("stonecutting/cut_flint_block_from_flint_block")); - stonecutting(Ingredient.of(ModBlocks.POLISHED_FLINT_BLOCK.get()), ctx.get()) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.POLISHED_FLINT_BLOCK.get()), ctx.get()) .unlockedBy( AnvilCraftDatagen.hasItem(ModBlocks.POLISHED_FLINT_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.POLISHED_FLINT_BLOCK) @@ -2355,7 +2355,7 @@ public static void cutFlintSlabBlock(DataGenContext .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.CUT_FLINT_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_FLINT_BLOCK)) .save(provider, AnvilCraft.recipe("shaped/cut_flint_slab")); - stonecutting(Ingredient.of(ModBlocks.FLINT_BLOCK.get()), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.FLINT_BLOCK.get()), ctx.get(), 2) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.FLINT_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.FLINT_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_flint_slab_from_flint_block")); @@ -2371,7 +2371,7 @@ public static void cutFlintSlabBlock(DataGenContext ) .save(provider, AnvilCraft.recipe("stonecutting/cut_flint_slab_from_polished_flint_block")); - stonecutting(Ingredient.of(ModBlocks.CUT_FLINT_BLOCK.get()), ctx.get(), 2) + RegistrumBlockRecipeLoader.stonecutting(Ingredient.of(ModBlocks.CUT_FLINT_BLOCK.get()), ctx.get(), 2) .unlockedBy(AnvilCraftDatagen.hasItem(ModBlocks.CUT_FLINT_BLOCK), AnvilCraftDatagen.has(lookup, ModBlocks.CUT_FLINT_BLOCK)) .save(provider, AnvilCraft.recipe("stonecutting/cut_flint_slab_from_cut_flint_block")); } @@ -2386,18 +2386,18 @@ public static void cutFlintStairsBlock(DataGenContext void cutFlintPillarBlock(DataGenContext void standardMetalIngotWithOreRecipes( } public static void tungstenIngot(DataGenContext ctx, RegistrumRecipeProvider provider) { - standardMetalIngotWithOreRecipes( + RegistrumItemRecipeLoader.standardMetalIngotWithOreRecipes( ctx, provider, ModBlocks.TUNGSTEN_BLOCK, @@ -995,7 +995,7 @@ public static void titaniumNugget(DataGenContext ctx, } public static void titaniumIngot(DataGenContext ctx, RegistrumRecipeProvider provider) { - standardMetalIngotWithOreRecipes( + RegistrumItemRecipeLoader.standardMetalIngotWithOreRecipes( ctx, provider, ModBlocks.TITANIUM_BLOCK, @@ -1014,7 +1014,7 @@ public static void zincNugget(DataGenContext ctx, Regi } public static void zincIngot(DataGenContext ctx, RegistrumRecipeProvider provider) { - standardMetalIngotWithOreRecipes( + RegistrumItemRecipeLoader.standardMetalIngotWithOreRecipes( ctx, provider, ModBlocks.ZINC_BLOCK, @@ -1033,7 +1033,7 @@ public static void tinNugget(DataGenContext ctx, Regis } public static void tinIngot(DataGenContext ctx, RegistrumRecipeProvider provider) { - standardMetalIngotWithOreRecipes( + RegistrumItemRecipeLoader.standardMetalIngotWithOreRecipes( ctx, provider, ModBlocks.TIN_BLOCK, @@ -1052,7 +1052,7 @@ public static void leadNugget(DataGenContext ctx, Regi } public static void leadIngot(DataGenContext ctx, RegistrumRecipeProvider provider) { - standardMetalIngotWithOreRecipes( + RegistrumItemRecipeLoader.standardMetalIngotWithOreRecipes( ctx, provider, ModBlocks.LEAD_BLOCK, @@ -1071,7 +1071,7 @@ public static void silverNugget(DataGenContext ctx, Re } public static void silverIngot(DataGenContext ctx, RegistrumRecipeProvider provider) { - standardMetalIngotWithOreRecipes( + RegistrumItemRecipeLoader.standardMetalIngotWithOreRecipes( ctx, provider, ModBlocks.SILVER_BLOCK, @@ -1090,7 +1090,7 @@ public static void uraniumNugget(DataGenContext ctx, R } public static void uraniumIngot(DataGenContext ctx, RegistrumRecipeProvider provider) { - standardMetalIngotWithOreRecipes( + RegistrumItemRecipeLoader.standardMetalIngotWithOreRecipes( ctx, provider, ModBlocks.URANIUM_BLOCK, diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SolidLiquidRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SolidLiquidRecipeLoader.java index 3ded056907..79619a7068 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SolidLiquidRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SolidLiquidRecipeLoader.java @@ -33,12 +33,12 @@ public static void init(RegistrumRecipeProvider provider) { SolidLiquidRecipeLoader.solidLiquid(provider, ModItemTags.FLOUR, ModItems.DOUGH); SolidLiquidRecipeLoader.solidLiquid(provider, Items.DRIED_KELP, Items.KELP); - VanillaConstants.CONCRETE_POWDERS.forEach(block -> solidLiquid(provider, block, block.concrete)); + VanillaConstants.CONCRETE_POWDERS.forEach(block -> SolidLiquidRecipeLoader.solidLiquid(provider, block, block.concrete)); VanillaConstants.WEATHERING_COPPERS.forEach(weatheringCopper -> { if (!(weatheringCopper instanceof Block block)) return; weatheringCopper.getNext(block.defaultBlockState()).ifPresent( - state -> solidLiquid(provider, block, state.getBlock()) + state -> SolidLiquidRecipeLoader.solidLiquid(provider, block, state.getBlock()) ); }); diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SpecialCelestialBodyRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SpecialCelestialBodyRecipeLoader.java index fc6ad9049e..932937ffa0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SpecialCelestialBodyRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SpecialCelestialBodyRecipeLoader.java @@ -20,11 +20,11 @@ public class SpecialCelestialBodyRecipeLoader { public static void init(RegistrumRecipeProvider provider) { - createOverworldLike(provider); - createFleshPlanet(provider); - createIntelligentPlanet(provider); - createHollowPlanet(provider); - createErrorPlanet(provider); + SpecialCelestialBodyRecipeLoader.createOverworldLike(provider); + SpecialCelestialBodyRecipeLoader.createFleshPlanet(provider); + SpecialCelestialBodyRecipeLoader.createIntelligentPlanet(provider); + SpecialCelestialBodyRecipeLoader.createHollowPlanet(provider); + SpecialCelestialBodyRecipeLoader.createErrorPlanet(provider); } private static void saveRecipe(RecipeOutput output, String name, SpecialCelestialBodyRecipe recipe) { @@ -50,63 +50,90 @@ private static SpecialCelestialBodyRecipe.WeightedEntry item(String id, int weig } private static void createOverworldLike(RegistrumRecipeProvider provider) { - saveRecipe(provider, "overworld_like", new SpecialCelestialBodyRecipe( + SpecialCelestialBodyRecipeLoader.saveRecipe(provider, "overworld_like", new SpecialCelestialBodyRecipe( "overworld_like", "planet_overworld", false, 32, 14, 20, 16, true, Optional.of(LiquidCoverage.MEDIUM), 2, 2, 0f, - List.of(mc("grass_block")), - List.of(item("minecraft:raw_copper", 50), item("minecraft:raw_iron", 30), item("minecraft:raw_gold", 20)), - List.of(item("minecraft:water", 100)), - List.of(item("minecraft:porkchop", 5), item("minecraft:beef", 5), item("minecraft:mutton", 5), - item("minecraft:chicken", 5), item("minecraft:leather", 5), item("minecraft:feather", 5), - item("minecraft:white_wool", 10), item("minecraft:light_gray_wool", 4), - item("minecraft:gray_wool", 4), item("minecraft:black_wool", 4), - item("minecraft:brown_wool", 4), item("minecraft:red_wool", 2), - item("minecraft:orange_wool", 2), item("minecraft:yellow_wool", 2), - item("minecraft:lime_wool", 2), item("minecraft:green_wool", 2), - item("minecraft:cyan_wool", 2), item("minecraft:light_blue_wool", 2), - item("minecraft:blue_wool", 2), item("minecraft:purple_wool", 2), - item("minecraft:magenta_wool", 2), item("minecraft:pink_wool", 2)), + List.of(SpecialCelestialBodyRecipeLoader.mc("grass_block")), + List.of( + SpecialCelestialBodyRecipeLoader.item("minecraft:raw_copper", 50), + SpecialCelestialBodyRecipeLoader.item("minecraft:raw_iron", 30), + SpecialCelestialBodyRecipeLoader.item("minecraft:raw_gold", 20) + ), + List.of(SpecialCelestialBodyRecipeLoader.item("minecraft:water", 100)), + List.of( + SpecialCelestialBodyRecipeLoader.item("minecraft:porkchop", 5), + SpecialCelestialBodyRecipeLoader.item("minecraft:beef", 5), + SpecialCelestialBodyRecipeLoader.item("minecraft:mutton", 5), + SpecialCelestialBodyRecipeLoader.item("minecraft:chicken", 5), + SpecialCelestialBodyRecipeLoader.item("minecraft:leather", 5), + SpecialCelestialBodyRecipeLoader.item("minecraft:feather", 5), + SpecialCelestialBodyRecipeLoader.item("minecraft:white_wool", 10), + SpecialCelestialBodyRecipeLoader.item("minecraft:light_gray_wool", 4), + SpecialCelestialBodyRecipeLoader.item("minecraft:gray_wool", 4), + SpecialCelestialBodyRecipeLoader.item("minecraft:black_wool", 4), + SpecialCelestialBodyRecipeLoader.item("minecraft:brown_wool", 4), + SpecialCelestialBodyRecipeLoader.item("minecraft:red_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:orange_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:yellow_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:lime_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:green_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:cyan_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:light_blue_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:blue_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:purple_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:magenta_wool", 2), + SpecialCelestialBodyRecipeLoader.item("minecraft:pink_wool", 2) + ), List.of(), List.of(), List.of() )); } private static void createFleshPlanet(RegistrumRecipeProvider provider) { - saveRecipe(provider, "flesh_planet", new SpecialCelestialBodyRecipe( + SpecialCelestialBodyRecipeLoader.saveRecipe(provider, "flesh_planet", new SpecialCelestialBodyRecipe( "flesh_planet", "planet_flesh", true, 40, 10, 9, 17, true, Optional.of(LiquidCoverage.NONE), 2, 2, 22f, - List.of(anvil("rotten_flesh_block")), - List.of(item("minecraft:rotten_flesh", 30), item("minecraft:bone", 30), - item("minecraft:string", 20), item("minecraft:spider_eye", 15), - item("minecraft:phantom_membrane", 3), item("minecraft:ghast_tear", 2)), + List.of(SpecialCelestialBodyRecipeLoader.anvil("rotten_flesh_block")), + List.of( + SpecialCelestialBodyRecipeLoader.item("minecraft:rotten_flesh", 30), + SpecialCelestialBodyRecipeLoader.item("minecraft:bone", 30), + SpecialCelestialBodyRecipeLoader.item("minecraft:string", 20), + SpecialCelestialBodyRecipeLoader.item("minecraft:spider_eye", 15), + SpecialCelestialBodyRecipeLoader.item("minecraft:phantom_membrane", 3), + SpecialCelestialBodyRecipeLoader.item("minecraft:ghast_tear", 2) + ), List.of(), List.of(), List.of(), List.of(), List.of() )); } private static void createIntelligentPlanet(RegistrumRecipeProvider provider) { - saveRecipe(provider, "intelligent_planet", new SpecialCelestialBodyRecipe( + SpecialCelestialBodyRecipeLoader.saveRecipe(provider, "intelligent_planet", new SpecialCelestialBodyRecipe( "intelligent_planet", "planet_intelligence", true, 58, 12, 12, 18, false, Optional.of(LiquidCoverage.HIGH), 1, 2, 2.71828f, - List.of(anvil("spacetime_supercomputer")), - List.of(), List.of(item("anvilcraft:exp_fluid", 100)), + List.of(SpecialCelestialBodyRecipeLoader.anvil("spacetime_supercomputer")), + List.of(), List.of(SpecialCelestialBodyRecipeLoader.item("anvilcraft:exp_fluid", 100)), List.of(), List.of(), List.of(), List.of() )); } private static void createHollowPlanet(RegistrumRecipeProvider provider) { - saveRecipe(provider, "hollow_planet", new SpecialCelestialBodyRecipe( + SpecialCelestialBodyRecipeLoader.saveRecipe(provider, "hollow_planet", new SpecialCelestialBodyRecipe( "hollow_planet", "planet_hollow", true, 60, 10, 1, 17, false, Optional.of(LiquidCoverage.NONE), 3, 4, 45f, - List.of(anvil("negative_matter_block")), - List.of(item("minecraft:obsidian", 90), item("anvilcraft:void_matter", 8), item("anvilcraft:negative_matter_nugget", 2)), + List.of(SpecialCelestialBodyRecipeLoader.anvil("negative_matter_block")), + List.of( + SpecialCelestialBodyRecipeLoader.item("minecraft:obsidian", 90), + SpecialCelestialBodyRecipeLoader.item("anvilcraft:void_matter", 8), + SpecialCelestialBodyRecipeLoader.item("anvilcraft:negative_matter_nugget", 2) + ), List.of(), List.of(), List.of(), List.of(), List.of() )); } private static void createErrorPlanet(RegistrumRecipeProvider provider) { - saveRecipe(provider, "error_planet", new SpecialCelestialBodyRecipe( + SpecialCelestialBodyRecipeLoader.saveRecipe(provider, "error_planet", new SpecialCelestialBodyRecipe( "error_planet", "planet_error", true, 64, 64, 64, 64, false, Optional.of(LiquidCoverage.NONE), -1, 0, 0f, - List.of(anvil("creative_generator")), + List.of(SpecialCelestialBodyRecipeLoader.anvil("creative_generator")), List.of(), List.of(), List.of(), List.of(), List.of(), List.of() )); } diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SqueezingRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SqueezingRecipeLoader.java index 539a86704c..1f35d35d1d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SqueezingRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SqueezingRecipeLoader.java @@ -10,10 +10,10 @@ public class SqueezingRecipeLoader { public static void init(RegistrumRecipeProvider provider) { - squeezing(provider, Blocks.WET_SPONGE, Blocks.SPONGE, Blocks.WATER_CAULDRON, 250); - squeezing(provider, Blocks.MOSS_BLOCK, Blocks.MOSS_CARPET, Blocks.WATER_CAULDRON, 250); - squeezing(provider, Blocks.MAGMA_BLOCK, Blocks.NETHERRACK, Blocks.LAVA_CAULDRON, 250); - squeezing(provider, Blocks.SNOW_BLOCK, Blocks.ICE, Blocks.POWDER_SNOW_CAULDRON, 250); + SqueezingRecipeLoader.squeezing(provider, Blocks.WET_SPONGE, Blocks.SPONGE, Blocks.WATER_CAULDRON, 250); + SqueezingRecipeLoader.squeezing(provider, Blocks.MOSS_BLOCK, Blocks.MOSS_CARPET, Blocks.WATER_CAULDRON, 250); + SqueezingRecipeLoader.squeezing(provider, Blocks.MAGMA_BLOCK, Blocks.NETHERRACK, Blocks.LAVA_CAULDRON, 250); + SqueezingRecipeLoader.squeezing(provider, Blocks.SNOW_BLOCK, Blocks.ICE, Blocks.POWDER_SNOW_CAULDRON, 250); SqueezingRecipe.builder() .requires(Blocks.SCULK) diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/StampingRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/StampingRecipeLoader.java index ca751f758f..7659ca619d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/StampingRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/StampingRecipeLoader.java @@ -16,21 +16,21 @@ public class StampingRecipeLoader { public static void init(RegistrumRecipeProvider provider) { final HolderGetter items = provider.getItems(); - stamping(provider, Items.IRON_INGOT, Items.HEAVY_WEIGHTED_PRESSURE_PLATE); - stamping(provider, Items.GOLD_INGOT, Items.LIGHT_WEIGHTED_PRESSURE_PLATE); - stamping(provider, Items.COPPER_INGOT, ModBlocks.COPPER_PRESSURE_PLATE); - stamping(provider, ModItemTags.TUNGSTEN_INGOTS, ModBlocks.TUNGSTEN_PRESSURE_PLATE); - stamping(provider, ModItemTags.TITANIUM_INGOTS, ModBlocks.TITANIUM_PRESSURE_PLATE); - stamping(provider, ModItemTags.ZINC_INGOTS, ModBlocks.ZINC_PRESSURE_PLATE); - stamping(provider, ModItemTags.TIN_INGOTS, ModBlocks.TIN_PRESSURE_PLATE); - stamping(provider, ModItemTags.LEAD_INGOTS, ModBlocks.LEAD_PRESSURE_PLATE); - stamping(provider, ModItemTags.SILVER_INGOTS, ModBlocks.SILVER_PRESSURE_PLATE); - stamping(provider, ModItemTags.URANIUM_INGOTS, ModBlocks.URANIUM_PRESSURE_PLATE); - stamping(provider, ModItemTags.PLUTONIUM_INGOTS, ModBlocks.PLUTONIUM_PRESSURE_PLATE); - stamping(provider, ModItemTags.BRONZE_INGOTS, ModBlocks.BRONZE_PRESSURE_PLATE); - stamping(provider, ModItemTags.BRASS_INGOTS, ModBlocks.BRASS_PRESSURE_PLATE); - stamping(provider, Items.SNOWBALL, Items.SNOW); - stamping(provider, Items.CHERRY_LEAVES, Items.PINK_PETALS); + StampingRecipeLoader.stamping(provider, Items.IRON_INGOT, Items.HEAVY_WEIGHTED_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, Items.GOLD_INGOT, Items.LIGHT_WEIGHTED_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, Items.COPPER_INGOT, ModBlocks.COPPER_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.TUNGSTEN_INGOTS, ModBlocks.TUNGSTEN_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.TITANIUM_INGOTS, ModBlocks.TITANIUM_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.ZINC_INGOTS, ModBlocks.ZINC_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.TIN_INGOTS, ModBlocks.TIN_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.LEAD_INGOTS, ModBlocks.LEAD_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.SILVER_INGOTS, ModBlocks.SILVER_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.URANIUM_INGOTS, ModBlocks.URANIUM_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.PLUTONIUM_INGOTS, ModBlocks.PLUTONIUM_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.BRONZE_INGOTS, ModBlocks.BRONZE_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, ModItemTags.BRASS_INGOTS, ModBlocks.BRASS_PRESSURE_PLATE); + StampingRecipeLoader.stamping(provider, Items.SNOWBALL, Items.SNOW); + StampingRecipeLoader.stamping(provider, Items.CHERRY_LEAVES, Items.PINK_PETALS); StampingRecipe.builder() .requires(ModItems.WOOD_FIBER) .result(Items.PAPER, 4) @@ -107,7 +107,7 @@ private static void stamping(RegistrumRecipeProvider provider, ItemLike input, I } private static void stamping(RegistrumRecipeProvider provider, ItemLike input, ItemLike result) { - stamping(provider, input, result, 1); + StampingRecipeLoader.stamping(provider, input, result, 1); } private static void stamping(RegistrumRecipeProvider provider, TagKey input, ItemLike result) { diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SuperHeatingRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SuperHeatingRecipeLoader.java index 44cc12f629..081be163b0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/SuperHeatingRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/SuperHeatingRecipeLoader.java @@ -123,37 +123,37 @@ public static void init(RegistrumRecipeProvider provider) { .save(provider, AnvilCraft.of("super_heating/melt_gem_cauldron_from_chromatic_stone")); // metalBlockFromRaw - metalBlockFromRaw(provider, Tags.Items.STORAGE_BLOCKS_RAW_COPPER, Items.COPPER_BLOCK); - metalBlockFromRaw(provider, Tags.Items.STORAGE_BLOCKS_RAW_IRON, Items.IRON_BLOCK); - metalBlockFromRaw(provider, Tags.Items.STORAGE_BLOCKS_RAW_GOLD, Items.GOLD_BLOCK); - metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_ZINC, ModBlocks.ZINC_BLOCK); - metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_TIN, ModBlocks.TIN_BLOCK); - metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_TITANIUM, ModBlocks.TITANIUM_BLOCK); - metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_TUNGSTEN, ModBlocks.TUNGSTEN_BLOCK); - metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_LEAD, ModBlocks.LEAD_BLOCK); - metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_SILVER, ModBlocks.SILVER_BLOCK); - metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_URANIUM, ModBlocks.URANIUM_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, Tags.Items.STORAGE_BLOCKS_RAW_COPPER, Items.COPPER_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, Tags.Items.STORAGE_BLOCKS_RAW_IRON, Items.IRON_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, Tags.Items.STORAGE_BLOCKS_RAW_GOLD, Items.GOLD_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_ZINC, ModBlocks.ZINC_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_TIN, ModBlocks.TIN_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_TITANIUM, ModBlocks.TITANIUM_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_TUNGSTEN, ModBlocks.TUNGSTEN_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_LEAD, ModBlocks.LEAD_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_SILVER, ModBlocks.SILVER_BLOCK); + SuperHeatingRecipeLoader.metalBlockFromRaw(provider, ModItemTags.STORAGE_BLOCKS_RAW_URANIUM, ModBlocks.URANIUM_BLOCK); // limePowder - limePowder(provider, ModItems.CRAB_CLAW, 1); - limePowder(provider, Items.NAUTILUS_SHELL, 1); - limePowder(provider, Items.POINTED_DRIPSTONE, 1); - limePowder(provider, Items.DRIPSTONE_BLOCK, 4); - limePowder(provider, Items.CALCITE, 4); - limePowder(provider, ModItemTags.DEAD_CORAL_BLOCKS, 4); - limePowder(provider, ModItemTags.DEAD_CORALS, 1); + SuperHeatingRecipeLoader.limePowder(provider, ModItems.CRAB_CLAW, 1); + SuperHeatingRecipeLoader.limePowder(provider, Items.NAUTILUS_SHELL, 1); + SuperHeatingRecipeLoader.limePowder(provider, Items.POINTED_DRIPSTONE, 1); + SuperHeatingRecipeLoader.limePowder(provider, Items.DRIPSTONE_BLOCK, 4); + SuperHeatingRecipeLoader.limePowder(provider, Items.CALCITE, 4); + SuperHeatingRecipeLoader.limePowder(provider, ModItemTags.DEAD_CORAL_BLOCKS, 4); + SuperHeatingRecipeLoader.limePowder(provider, ModItemTags.DEAD_CORALS, 1); // ingotFromEarth - ingotFromEarth(provider, Tags.Items.RAW_MATERIALS_COPPER, Items.COPPER_INGOT); - ingotFromEarth(provider, Tags.Items.RAW_MATERIALS_IRON, Items.IRON_INGOT); - ingotFromEarth(provider, Tags.Items.RAW_MATERIALS_GOLD, Items.GOLD_INGOT); - ingotFromEarth(provider, ModItemTags.RAW_ZINC, ModItems.ZINC_INGOT); - ingotFromEarth(provider, ModItemTags.RAW_TIN, ModItems.TIN_INGOT); - ingotFromEarth(provider, ModItemTags.RAW_TITANIUM, ModItems.TITANIUM_INGOT); - ingotFromEarth(provider, ModItemTags.RAW_TUNGSTEN, ModItems.TUNGSTEN_INGOT); - ingotFromEarth(provider, ModItemTags.RAW_LEAD, ModItems.LEAD_INGOT); - ingotFromEarth(provider, ModItemTags.RAW_SILVER, ModItems.SILVER_INGOT); - ingotFromEarth(provider, ModItemTags.RAW_URANIUM, ModItems.URANIUM_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, Tags.Items.RAW_MATERIALS_COPPER, Items.COPPER_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, Tags.Items.RAW_MATERIALS_IRON, Items.IRON_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, Tags.Items.RAW_MATERIALS_GOLD, Items.GOLD_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, ModItemTags.RAW_ZINC, ModItems.ZINC_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, ModItemTags.RAW_TIN, ModItems.TIN_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, ModItemTags.RAW_TITANIUM, ModItems.TITANIUM_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, ModItemTags.RAW_TUNGSTEN, ModItems.TUNGSTEN_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, ModItemTags.RAW_LEAD, ModItems.LEAD_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, ModItemTags.RAW_SILVER, ModItems.SILVER_INGOT); + SuperHeatingRecipeLoader.ingotFromEarth(provider, ModItemTags.RAW_URANIUM, ModItems.URANIUM_INGOT); } private static void metalBlockFromRaw(RegistrumRecipeProvider provider, TagKey raw, ItemLike result) { diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/TempleDemandRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/TempleDemandRecipeLoader.java index 6c4b3df585..3eb72497cd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/TempleDemandRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/TempleDemandRecipeLoader.java @@ -21,8 +21,8 @@ public class TempleDemandRecipeLoader { public static void init(RegistrumRecipeProvider provider) { - createBlessingRecipe(provider); - createPunishmentRecipe(provider); + TempleDemandRecipeLoader.createBlessingRecipe(provider); + TempleDemandRecipeLoader.createPunishmentRecipe(provider); } private static void saveRecipe(RecipeOutput output, String name, TempleDemandRecipe recipe) { @@ -46,7 +46,7 @@ private static void createBlessingRecipe(RegistrumRecipeProvider provider) { new TempleDemandRecipe.Entry("minecraft:cookie", 64) ) ); - saveRecipe(provider, "blessing", recipe); + TempleDemandRecipeLoader.saveRecipe(provider, "blessing", recipe); } private static void createPunishmentRecipe(RegistrumRecipeProvider provider) { @@ -58,6 +58,6 @@ private static void createPunishmentRecipe(RegistrumRecipeProvider provider) { new TempleDemandRecipe.Entry("minecraft:tnt", 1024) ) ); - saveRecipe(provider, "punishment", recipe); + TempleDemandRecipeLoader.saveRecipe(provider, "punishment", recipe); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/TimeWarpRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/TimeWarpRecipeLoader.java index 331c639742..e0c46391b1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/TimeWarpRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/TimeWarpRecipeLoader.java @@ -36,26 +36,26 @@ public class TimeWarpRecipeLoader { public static void init(RegistrumRecipeProvider provider) { final HolderGetter items = provider.getItems(); - timeWarp(provider, ModItems.RESIN, 1, ModItems.AMBER, 1); - timeWarp(provider, Items.OBSIDIAN, 1, Items.CRYING_OBSIDIAN, 1); - timeWarp(provider, Items.CHARCOAL, 1, Items.COAL, 2); - timeWarp(provider, Items.SAND, 1, Items.DIRT, 1); - timeWarp(provider, Items.IRON_BLOCK, 1, Items.RAW_IRON, 3); - timeWarp(provider, Items.GOLD_BLOCK, 1, Items.RAW_GOLD, 3); - timeWarp(provider, Items.COPPER_BLOCK, 1, Items.RAW_COPPER, 3); - timeWarp(provider, ModItems.GEODE, 1, Items.BUDDING_AMETHYST, 1); - timeWarp(provider, ModBlocks.CINERITE, 1, Items.TUFF, 1); - timeWarp(provider, ModBlocks.NETHER_DUST, 1, Items.SOUL_SOIL, 1); - timeWarp(provider, ModBlocks.END_DUST, 1, Items.END_STONE, 1); - timeWarp(provider, ModItems.LIME_POWDER, 8, Items.CALCITE, 1); - timeWarp(provider, ModItems.NETHERITE_CRYSTAL_NUCLEUS, 1, Items.ANCIENT_DEBRIS, 1); - timeWarp(provider, ModItemTags.STORAGE_BLOCKS_ZINC, 1, ModItems.RAW_ZINC, 3); - timeWarp(provider, ModItemTags.STORAGE_BLOCKS_TIN, 1, ModItems.RAW_TIN, 3); - timeWarp(provider, ModItemTags.STORAGE_BLOCKS_TITANIUM, 1, ModItems.RAW_TITANIUM, 3); - timeWarp(provider, ModItemTags.STORAGE_BLOCKS_TUNGSTEN, 1, ModItems.RAW_TUNGSTEN, 3); - timeWarp(provider, ModItemTags.STORAGE_BLOCKS_LEAD, 1, ModItems.RAW_LEAD, 3); - timeWarp(provider, ModItemTags.STORAGE_BLOCKS_SILVER, 1, ModItems.RAW_SILVER, 3); - timeWarp(provider, ModItems.SEA_HEART_SHELL_SHARD, 1, ModItems.SEA_HEART_SHELL, 1); + TimeWarpRecipeLoader.timeWarp(provider, ModItems.RESIN, 1, ModItems.AMBER, 1); + TimeWarpRecipeLoader.timeWarp(provider, Items.OBSIDIAN, 1, Items.CRYING_OBSIDIAN, 1); + TimeWarpRecipeLoader.timeWarp(provider, Items.CHARCOAL, 1, Items.COAL, 2); + TimeWarpRecipeLoader.timeWarp(provider, Items.SAND, 1, Items.DIRT, 1); + TimeWarpRecipeLoader.timeWarp(provider, Items.IRON_BLOCK, 1, Items.RAW_IRON, 3); + TimeWarpRecipeLoader.timeWarp(provider, Items.GOLD_BLOCK, 1, Items.RAW_GOLD, 3); + TimeWarpRecipeLoader.timeWarp(provider, Items.COPPER_BLOCK, 1, Items.RAW_COPPER, 3); + TimeWarpRecipeLoader.timeWarp(provider, ModItems.GEODE, 1, Items.BUDDING_AMETHYST, 1); + TimeWarpRecipeLoader.timeWarp(provider, ModBlocks.CINERITE, 1, Items.TUFF, 1); + TimeWarpRecipeLoader.timeWarp(provider, ModBlocks.NETHER_DUST, 1, Items.SOUL_SOIL, 1); + TimeWarpRecipeLoader.timeWarp(provider, ModBlocks.END_DUST, 1, Items.END_STONE, 1); + TimeWarpRecipeLoader.timeWarp(provider, ModItems.LIME_POWDER, 8, Items.CALCITE, 1); + TimeWarpRecipeLoader.timeWarp(provider, ModItems.NETHERITE_CRYSTAL_NUCLEUS, 1, Items.ANCIENT_DEBRIS, 1); + TimeWarpRecipeLoader.timeWarp(provider, ModItemTags.STORAGE_BLOCKS_ZINC, 1, ModItems.RAW_ZINC, 3); + TimeWarpRecipeLoader.timeWarp(provider, ModItemTags.STORAGE_BLOCKS_TIN, 1, ModItems.RAW_TIN, 3); + TimeWarpRecipeLoader.timeWarp(provider, ModItemTags.STORAGE_BLOCKS_TITANIUM, 1, ModItems.RAW_TITANIUM, 3); + TimeWarpRecipeLoader.timeWarp(provider, ModItemTags.STORAGE_BLOCKS_TUNGSTEN, 1, ModItems.RAW_TUNGSTEN, 3); + TimeWarpRecipeLoader.timeWarp(provider, ModItemTags.STORAGE_BLOCKS_LEAD, 1, ModItems.RAW_LEAD, 3); + TimeWarpRecipeLoader.timeWarp(provider, ModItemTags.STORAGE_BLOCKS_SILVER, 1, ModItems.RAW_SILVER, 3); + TimeWarpRecipeLoader.timeWarp(provider, ModItems.SEA_HEART_SHELL_SHARD, 1, ModItems.SEA_HEART_SHELL, 1); TimeWarpRecipe.builder() .requires(Items.EMERALD) @@ -92,17 +92,17 @@ public static void init(RegistrumRecipeProvider provider) { .result(ModBlocks.CHROMATIC_STONE) .save(provider); - timeWarpToOilCauldron(provider, Items.ROTTEN_FLESH, 64); - timeWarpToOilCauldron(provider, Items.SPIDER_EYE, 64); - timeWarpToOilCauldron(provider, ModItemTags.RAW_CHICKEN, 64); - timeWarpToOilCauldron(provider, Tags.Items.FOODS_RAW_FISH, 64); - timeWarpToOilCauldron(provider, ModItemTags.RAW_BEEF, 16); - timeWarpToOilCauldron(provider, ModItemTags.RAW_PORKCHOP, 16); - timeWarpToOilCauldron(provider, ModItemTags.RAW_MUTTON, 16); - timeWarpToOilCauldron(provider, ModItemTags.RAW_RABBIT, 16); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, Items.ROTTEN_FLESH, 64); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, Items.SPIDER_EYE, 64); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, ModItemTags.RAW_CHICKEN, 64); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, Tags.Items.FOODS_RAW_FISH, 64); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, ModItemTags.RAW_BEEF, 16); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, ModItemTags.RAW_PORKCHOP, 16); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, ModItemTags.RAW_MUTTON, 16); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, ModItemTags.RAW_RABBIT, 16); - timeWarpToOilCauldron(provider, Items.ZOMBIE_HEAD, 1); - timeWarpToOilCauldron(provider, Items.PIGLIN_HEAD, 1); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, Items.ZOMBIE_HEAD, 1); + TimeWarpRecipeLoader.timeWarpToOilCauldron(provider, Items.PIGLIN_HEAD, 1); TimeWarpRecipe.builder() .requires(items, ModItemTags.NETHERITE_BLOCK) diff --git a/src/main/java/dev/dubhe/anvilcraft/data/recipe/UnpackRecipeLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/recipe/UnpackRecipeLoader.java index b8bd1c155a..c6715fbafe 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/recipe/UnpackRecipeLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/recipe/UnpackRecipeLoader.java @@ -10,15 +10,15 @@ public class UnpackRecipeLoader { public static void init(RegistrumRecipeProvider provider) { - unpack(provider, Items.WET_SPONGE, ModItems.SPONGE_GEMMULE, 4); - unpack(provider, Items.MELON, Items.MELON_SLICE, 9); - unpack(provider, Items.SNOW_BLOCK, Items.SNOWBALL, 4); - unpack(provider, Items.CLAY, Items.CLAY_BALL, 4); - unpack(provider, Items.GLOWSTONE, Items.GLOWSTONE_DUST, 4); - unpack(provider, Items.QUARTZ_BLOCK, Items.QUARTZ, 4); - unpack(provider, Items.DRIPSTONE_BLOCK, Items.POINTED_DRIPSTONE, 4); - unpack(provider, Items.AMETHYST_BLOCK, Items.AMETHYST_SHARD, 4); - unpack(provider, Items.HONEYCOMB_BLOCK, Items.HONEYCOMB, 4); + UnpackRecipeLoader.unpack(provider, Items.WET_SPONGE, ModItems.SPONGE_GEMMULE, 4); + UnpackRecipeLoader.unpack(provider, Items.MELON, Items.MELON_SLICE, 9); + UnpackRecipeLoader.unpack(provider, Items.SNOW_BLOCK, Items.SNOWBALL, 4); + UnpackRecipeLoader.unpack(provider, Items.CLAY, Items.CLAY_BALL, 4); + UnpackRecipeLoader.unpack(provider, Items.GLOWSTONE, Items.GLOWSTONE_DUST, 4); + UnpackRecipeLoader.unpack(provider, Items.QUARTZ_BLOCK, Items.QUARTZ, 4); + UnpackRecipeLoader.unpack(provider, Items.DRIPSTONE_BLOCK, Items.POINTED_DRIPSTONE, 4); + UnpackRecipeLoader.unpack(provider, Items.AMETHYST_BLOCK, Items.AMETHYST_SHARD, 4); + UnpackRecipeLoader.unpack(provider, Items.HONEYCOMB_BLOCK, Items.HONEYCOMB, 4); UnpackRecipe.builder() .requires(Items.HONEY_BLOCK) @@ -51,10 +51,10 @@ public static void init(RegistrumRecipeProvider provider) { .result(ModBlocks.FLUID_TANK) .save(provider, AnvilCraft.of("unpack/fluid_tank_minecart")); - unpackMinecart(provider, Items.CHEST_MINECART, Items.CHEST, "chest_minecart"); - unpackMinecart(provider, Items.FURNACE_MINECART, Items.FURNACE, "furnace_minecart"); - unpackMinecart(provider, Items.TNT_MINECART, Items.TNT, "tnt_minecart"); - unpackMinecart(provider, Items.HOPPER_MINECART, Items.HOPPER, "hopper_minecart"); + UnpackRecipeLoader.unpackMinecart(provider, Items.CHEST_MINECART, Items.CHEST, "chest_minecart"); + UnpackRecipeLoader.unpackMinecart(provider, Items.FURNACE_MINECART, Items.FURNACE, "furnace_minecart"); + UnpackRecipeLoader.unpackMinecart(provider, Items.TNT_MINECART, Items.TNT, "tnt_minecart"); + UnpackRecipeLoader.unpackMinecart(provider, Items.HOPPER_MINECART, Items.HOPPER, "hopper_minecart"); } private static void unpackMinecart( diff --git a/src/main/java/dev/dubhe/anvilcraft/data/tags/BlockTagLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/tags/BlockTagLoader.java index 08c9d21037..39ce49f37f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/tags/BlockTagLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/tags/BlockTagLoader.java @@ -21,21 +21,21 @@ private static Identifier findId(Block item) { /// @param provider 提供器 public static void init(RegistrumTagsProvider provider) { provider.rawBuilder(ModBlockTags.REDSTONE_TORCH) - .addElement(findId(Blocks.REDSTONE_WALL_TORCH)) - .addElement(findId(Blocks.REDSTONE_TORCH)); + .addElement(BlockTagLoader.findId(Blocks.REDSTONE_WALL_TORCH)) + .addElement(BlockTagLoader.findId(Blocks.REDSTONE_TORCH)); provider.rawBuilder(ModBlockTags.MUSHROOM_BLOCK) - .addElement(findId(Blocks.BROWN_MUSHROOM_BLOCK)) - .addElement(findId(Blocks.RED_MUSHROOM_BLOCK)) - .addElement(findId(Blocks.MUSHROOM_STEM)); + .addElement(BlockTagLoader.findId(Blocks.BROWN_MUSHROOM_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.RED_MUSHROOM_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.MUSHROOM_STEM)); provider.rawBuilder(ModBlockTags.HAMMER_CHANGEABLE) - .addElement(findId(Blocks.OBSERVER)) - .addElement(findId(Blocks.HOPPER)) - .addElement(findId(Blocks.DROPPER)) - .addElement(findId(Blocks.DISPENSER)) - .addElement(findId(Blocks.CRAFTER)) - .addElement(findId(Blocks.LIGHTNING_ROD)); + .addElement(BlockTagLoader.findId(Blocks.OBSERVER)) + .addElement(BlockTagLoader.findId(Blocks.HOPPER)) + .addElement(BlockTagLoader.findId(Blocks.DROPPER)) + .addElement(BlockTagLoader.findId(Blocks.DISPENSER)) + .addElement(BlockTagLoader.findId(Blocks.CRAFTER)) + .addElement(BlockTagLoader.findId(Blocks.LIGHTNING_ROD)); provider.rawBuilder(ModBlockTags.HAMMER_REMOVABLE) .addTag(BlockTags.TRAPDOORS.location()) @@ -43,66 +43,66 @@ public static void init(RegistrumTagsProvider provider) { .addTag(BlockTags.BUTTONS.location()) .addTag(BlockTags.PRESSURE_PLATES.location()) .addTag(BlockTags.FENCE_GATES.location()) - .addElement(findId(Blocks.BELL)) - .addElement(findId(Blocks.REDSTONE_LAMP)) - .addElement(findId(Blocks.RAIL)) - .addElement(findId(Blocks.ACTIVATOR_RAIL)) - .addElement(findId(Blocks.DETECTOR_RAIL)) - .addElement(findId(Blocks.POWERED_RAIL)) - .addElement(findId(Blocks.NOTE_BLOCK)) - .addElement(findId(Blocks.OBSERVER)) - .addElement(findId(Blocks.HOPPER)) - .addElement(findId(Blocks.DROPPER)) - .addElement(findId(Blocks.DISPENSER)) - .addElement(findId(Blocks.CRAFTER)) - .addElement(findId(Blocks.HONEY_BLOCK)) - .addElement(findId(Blocks.SLIME_BLOCK)) - .addElement(findId(Blocks.PISTON)) - .addElement(findId(Blocks.STICKY_PISTON)) - .addElement(findId(Blocks.PISTON_HEAD)) - .addElement(findId(Blocks.LIGHTNING_ROD)) - .addElement(findId(Blocks.DAYLIGHT_DETECTOR)) - .addElement(findId(Blocks.LECTERN)) - .addElement(findId(Blocks.TRIPWIRE_HOOK)) - .addElement(findId(Blocks.SCULK_SHRIEKER)) - .addElement(findId(Blocks.LEVER)) - .addElement(findId(Blocks.SCULK_SENSOR)) - .addElement(findId(Blocks.CALIBRATED_SCULK_SENSOR)) - .addElement(findId(Blocks.REDSTONE_WIRE)) - .addElement(findId(Blocks.REDSTONE_TORCH)) - .addElement(findId(Blocks.REDSTONE_WALL_TORCH)) - .addElement(findId(Blocks.REDSTONE_BLOCK)) - .addElement(findId(Blocks.REPEATER)) - .addElement(findId(Blocks.COMPARATOR)) - .addElement(findId(Blocks.TARGET)) - .addElement(findId(Blocks.COPPER_BULB)) - .addElement(findId(Blocks.EXPOSED_COPPER_BULB)) - .addElement(findId(Blocks.WEATHERED_COPPER_BULB)) - .addElement(findId(Blocks.OXIDIZED_COPPER_BULB)) - .addElement(findId(Blocks.WAXED_COPPER_BULB)) - .addElement(findId(Blocks.WAXED_EXPOSED_COPPER_BULB)) - .addElement(findId(Blocks.WAXED_WEATHERED_COPPER_BULB)) - .addElement(findId(Blocks.WAXED_OXIDIZED_COPPER_BULB)) - .addElement(findId(Blocks.CAULDRON)) - .addElement(findId(Blocks.LAVA_CAULDRON)) - .addElement(findId(Blocks.WATER_CAULDRON)) - .addElement(findId(Blocks.POWDER_SNOW_CAULDRON)) - .addElement(findId(Blocks.CAMPFIRE)) - .addElement(findId(Blocks.STONECUTTER)) - .addElement(findId(Blocks.SCAFFOLDING)) - .addElement(findId(Blocks.ANVIL)) - .addElement(findId(Blocks.CHIPPED_ANVIL)) - .addElement(findId(Blocks.DAMAGED_ANVIL)) - .addElement(findId(Blocks.FURNACE)) - .addElement(findId(Blocks.BLAST_FURNACE)) - .addElement(findId(Blocks.SMOKER)) - .addElement(findId(Blocks.CHEST)) - .addElement(findId(Blocks.TRAPPED_CHEST)) - .addElement(findId(Blocks.ENDER_CHEST)) - .addElement(findId(Blocks.BARREL)) - .addElement(findId(Blocks.COMPOSTER)) - .addElement(findId(Blocks.TNT)) - .addElement(findId(Blocks.BEACON)) + .addElement(BlockTagLoader.findId(Blocks.BELL)) + .addElement(BlockTagLoader.findId(Blocks.REDSTONE_LAMP)) + .addElement(BlockTagLoader.findId(Blocks.RAIL)) + .addElement(BlockTagLoader.findId(Blocks.ACTIVATOR_RAIL)) + .addElement(BlockTagLoader.findId(Blocks.DETECTOR_RAIL)) + .addElement(BlockTagLoader.findId(Blocks.POWERED_RAIL)) + .addElement(BlockTagLoader.findId(Blocks.NOTE_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.OBSERVER)) + .addElement(BlockTagLoader.findId(Blocks.HOPPER)) + .addElement(BlockTagLoader.findId(Blocks.DROPPER)) + .addElement(BlockTagLoader.findId(Blocks.DISPENSER)) + .addElement(BlockTagLoader.findId(Blocks.CRAFTER)) + .addElement(BlockTagLoader.findId(Blocks.HONEY_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.SLIME_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.PISTON)) + .addElement(BlockTagLoader.findId(Blocks.STICKY_PISTON)) + .addElement(BlockTagLoader.findId(Blocks.PISTON_HEAD)) + .addElement(BlockTagLoader.findId(Blocks.LIGHTNING_ROD)) + .addElement(BlockTagLoader.findId(Blocks.DAYLIGHT_DETECTOR)) + .addElement(BlockTagLoader.findId(Blocks.LECTERN)) + .addElement(BlockTagLoader.findId(Blocks.TRIPWIRE_HOOK)) + .addElement(BlockTagLoader.findId(Blocks.SCULK_SHRIEKER)) + .addElement(BlockTagLoader.findId(Blocks.LEVER)) + .addElement(BlockTagLoader.findId(Blocks.SCULK_SENSOR)) + .addElement(BlockTagLoader.findId(Blocks.CALIBRATED_SCULK_SENSOR)) + .addElement(BlockTagLoader.findId(Blocks.REDSTONE_WIRE)) + .addElement(BlockTagLoader.findId(Blocks.REDSTONE_TORCH)) + .addElement(BlockTagLoader.findId(Blocks.REDSTONE_WALL_TORCH)) + .addElement(BlockTagLoader.findId(Blocks.REDSTONE_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.REPEATER)) + .addElement(BlockTagLoader.findId(Blocks.COMPARATOR)) + .addElement(BlockTagLoader.findId(Blocks.TARGET)) + .addElement(BlockTagLoader.findId(Blocks.COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.EXPOSED_COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.WEATHERED_COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.OXIDIZED_COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.WAXED_COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.WAXED_EXPOSED_COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.WAXED_WEATHERED_COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.WAXED_OXIDIZED_COPPER_BULB)) + .addElement(BlockTagLoader.findId(Blocks.CAULDRON)) + .addElement(BlockTagLoader.findId(Blocks.LAVA_CAULDRON)) + .addElement(BlockTagLoader.findId(Blocks.WATER_CAULDRON)) + .addElement(BlockTagLoader.findId(Blocks.POWDER_SNOW_CAULDRON)) + .addElement(BlockTagLoader.findId(Blocks.CAMPFIRE)) + .addElement(BlockTagLoader.findId(Blocks.STONECUTTER)) + .addElement(BlockTagLoader.findId(Blocks.SCAFFOLDING)) + .addElement(BlockTagLoader.findId(Blocks.ANVIL)) + .addElement(BlockTagLoader.findId(Blocks.CHIPPED_ANVIL)) + .addElement(BlockTagLoader.findId(Blocks.DAMAGED_ANVIL)) + .addElement(BlockTagLoader.findId(Blocks.FURNACE)) + .addElement(BlockTagLoader.findId(Blocks.BLAST_FURNACE)) + .addElement(BlockTagLoader.findId(Blocks.SMOKER)) + .addElement(BlockTagLoader.findId(Blocks.CHEST)) + .addElement(BlockTagLoader.findId(Blocks.TRAPPED_CHEST)) + .addElement(BlockTagLoader.findId(Blocks.ENDER_CHEST)) + .addElement(BlockTagLoader.findId(Blocks.BARREL)) + .addElement(BlockTagLoader.findId(Blocks.COMPOSTER)) + .addElement(BlockTagLoader.findId(Blocks.TNT)) + .addElement(BlockTagLoader.findId(Blocks.BEACON)) .addElement(ModBlocks.HEAVY_IRON_BLOCK.getId()) .addElement(ModBlocks.HEAVY_IRON_BEAM.getId()) .addElement(ModBlocks.HEAVY_IRON_COLUMN.getId()) @@ -117,7 +117,7 @@ public static void init(RegistrumTagsProvider provider) { provider.rawBuilder(ModBlockTags.UNDER_CAULDRON) .addTag(BlockTags.CAMPFIRES.location()) - .addElement(findId(Blocks.MAGMA_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.MAGMA_BLOCK)) .addElement(ModBlocks.HEATER.getId()) .addElement(ModBlocks.CORRUPTED_BEACON.getId()); @@ -126,16 +126,16 @@ public static void init(RegistrumTagsProvider provider) { .addTag(Tags.Blocks.GRAVELS.location()); provider.rawBuilder(ModBlockTags.BLOCK_DEVOURER_PROBABILITY_DROPPING) - .addElement(findId(Blocks.STONE)) - .addElement(findId(Blocks.DEEPSLATE)) - .addElement(findId(Blocks.ANDESITE)) - .addElement(findId(Blocks.DIORITE)) - .addElement(findId(Blocks.GRANITE)) - .addElement(findId(Blocks.TUFF)) - .addElement(findId(Blocks.NETHERRACK)) - .addElement(findId(Blocks.BASALT)) - .addElement(findId(Blocks.BLACKSTONE)) - .addElement(findId(Blocks.END_STONE)); + .addElement(BlockTagLoader.findId(Blocks.STONE)) + .addElement(BlockTagLoader.findId(Blocks.DEEPSLATE)) + .addElement(BlockTagLoader.findId(Blocks.ANDESITE)) + .addElement(BlockTagLoader.findId(Blocks.DIORITE)) + .addElement(BlockTagLoader.findId(Blocks.GRANITE)) + .addElement(BlockTagLoader.findId(Blocks.TUFF)) + .addElement(BlockTagLoader.findId(Blocks.NETHERRACK)) + .addElement(BlockTagLoader.findId(Blocks.BASALT)) + .addElement(BlockTagLoader.findId(Blocks.BLACKSTONE)) + .addElement(BlockTagLoader.findId(Blocks.END_STONE)); provider.rawBuilder(ModBlockTags.LASER_CAN_PASS_THROUGH) .addTag(Tags.Blocks.GLASS_BLOCKS.location()) @@ -143,60 +143,60 @@ public static void init(RegistrumTagsProvider provider) { .addTag(BlockTags.REPLACEABLE.location()); provider.rawBuilder(ModBlockTags.END_PORTAL_UNABLE_CHANGE) - .addElement(findId(Blocks.DRAGON_EGG)); + .addElement(BlockTagLoader.findId(Blocks.DRAGON_EGG)); provider.rawBuilder(ModBlockTags.NEUTRONIUM_CANNOT_PASS_THROUGH) - .addElement(findId(Blocks.END_STONE)) - .addElement(findId(Blocks.BEDROCK)) - .addElement(findId(Blocks.COMMAND_BLOCK)) - .addElement(findId(Blocks.REPEATING_COMMAND_BLOCK)) - .addElement(findId(Blocks.CHAIN_COMMAND_BLOCK)) - .addElement(findId(Blocks.BARRIER)) - .addElement(findId(Blocks.STRUCTURE_BLOCK)) - .addElement(findId(Blocks.JIGSAW)) + .addElement(BlockTagLoader.findId(Blocks.END_STONE)) + .addElement(BlockTagLoader.findId(Blocks.BEDROCK)) + .addElement(BlockTagLoader.findId(Blocks.COMMAND_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.REPEATING_COMMAND_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.CHAIN_COMMAND_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.BARRIER)) + .addElement(BlockTagLoader.findId(Blocks.STRUCTURE_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.JIGSAW)) .addElement(ModBlocks.END_DUST.getId()) .addElement(ModBlocks.NEGATIVE_MATTER_BLOCK.getId()); provider.rawBuilder(ModBlockTags.VOID_DECAY_PRODUCTS) - .addElement(findId(Blocks.STONE)) - .addElement(findId(Blocks.DEEPSLATE)) - .addElement(findId(Blocks.ANDESITE)) - .addElement(findId(Blocks.GRANITE)) - .addElement(findId(Blocks.DIORITE)) - .addElement(findId(Blocks.NETHERRACK)) - .addElement(findId(Blocks.BLACKSTONE)) - .addElement(findId(Blocks.END_STONE)) - .addElement(findId(Blocks.ICE)) - .addElement(findId(Blocks.RAW_IRON_BLOCK)) - .addElement(findId(Blocks.OXIDIZED_COPPER)) - .addElement(findId(Blocks.IRON_ORE)) - .addElement(findId(Blocks.DEEPSLATE_IRON_ORE)) - .addElement(findId(Blocks.COPPER_ORE)) - .addElement(findId(Blocks.DEEPSLATE_COPPER_ORE)) - .addElement(findId(Blocks.GOLD_ORE)) - .addElement(findId(Blocks.DEEPSLATE_GOLD_ORE)) - .addElement(findId(Blocks.DIRT)) - .addElement(findId(Blocks.COARSE_DIRT)) - .addElement(findId(Blocks.ROOTED_DIRT)) - .addElement(findId(Blocks.MUD)) - .addElement(findId(Blocks.CLAY)) - .addElement(findId(Blocks.COBBLESTONE)) - .addElement(findId(Blocks.MOSSY_COBBLESTONE)) - .addElement(findId(Blocks.CALCITE)) - .addElement(findId(Blocks.TUFF)) - .addElement(findId(Blocks.DRIPSTONE_BLOCK)) - .addElement(findId(Blocks.SANDSTONE)) - .addElement(findId(Blocks.RED_SANDSTONE)) - .addElement(findId(Blocks.BASALT)) - .addElement(findId(Blocks.SMOOTH_BASALT)) - .addElement(findId(Blocks.SCULK)) - .addElement(findId(Blocks.MOSS_BLOCK)) - .addElement(findId(Blocks.INFESTED_COBBLESTONE)) - .addElement(findId(Blocks.INFESTED_STONE)) - .addElement(findId(Blocks.INFESTED_DEEPSLATE)) - .addElement(findId(Blocks.NETHER_GOLD_ORE)) - .addElement(findId(Blocks.GILDED_BLACKSTONE)) - .addElement(findId(Blocks.NETHER_QUARTZ_ORE)); + .addElement(BlockTagLoader.findId(Blocks.STONE)) + .addElement(BlockTagLoader.findId(Blocks.DEEPSLATE)) + .addElement(BlockTagLoader.findId(Blocks.ANDESITE)) + .addElement(BlockTagLoader.findId(Blocks.GRANITE)) + .addElement(BlockTagLoader.findId(Blocks.DIORITE)) + .addElement(BlockTagLoader.findId(Blocks.NETHERRACK)) + .addElement(BlockTagLoader.findId(Blocks.BLACKSTONE)) + .addElement(BlockTagLoader.findId(Blocks.END_STONE)) + .addElement(BlockTagLoader.findId(Blocks.ICE)) + .addElement(BlockTagLoader.findId(Blocks.RAW_IRON_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.OXIDIZED_COPPER)) + .addElement(BlockTagLoader.findId(Blocks.IRON_ORE)) + .addElement(BlockTagLoader.findId(Blocks.DEEPSLATE_IRON_ORE)) + .addElement(BlockTagLoader.findId(Blocks.COPPER_ORE)) + .addElement(BlockTagLoader.findId(Blocks.DEEPSLATE_COPPER_ORE)) + .addElement(BlockTagLoader.findId(Blocks.GOLD_ORE)) + .addElement(BlockTagLoader.findId(Blocks.DEEPSLATE_GOLD_ORE)) + .addElement(BlockTagLoader.findId(Blocks.DIRT)) + .addElement(BlockTagLoader.findId(Blocks.COARSE_DIRT)) + .addElement(BlockTagLoader.findId(Blocks.ROOTED_DIRT)) + .addElement(BlockTagLoader.findId(Blocks.MUD)) + .addElement(BlockTagLoader.findId(Blocks.CLAY)) + .addElement(BlockTagLoader.findId(Blocks.COBBLESTONE)) + .addElement(BlockTagLoader.findId(Blocks.MOSSY_COBBLESTONE)) + .addElement(BlockTagLoader.findId(Blocks.CALCITE)) + .addElement(BlockTagLoader.findId(Blocks.TUFF)) + .addElement(BlockTagLoader.findId(Blocks.DRIPSTONE_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.SANDSTONE)) + .addElement(BlockTagLoader.findId(Blocks.RED_SANDSTONE)) + .addElement(BlockTagLoader.findId(Blocks.BASALT)) + .addElement(BlockTagLoader.findId(Blocks.SMOOTH_BASALT)) + .addElement(BlockTagLoader.findId(Blocks.SCULK)) + .addElement(BlockTagLoader.findId(Blocks.MOSS_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.INFESTED_COBBLESTONE)) + .addElement(BlockTagLoader.findId(Blocks.INFESTED_STONE)) + .addElement(BlockTagLoader.findId(Blocks.INFESTED_DEEPSLATE)) + .addElement(BlockTagLoader.findId(Blocks.NETHER_GOLD_ORE)) + .addElement(BlockTagLoader.findId(Blocks.GILDED_BLACKSTONE)) + .addElement(BlockTagLoader.findId(Blocks.NETHER_QUARTZ_ORE)); provider.rawBuilder(ModBlockTags.CRAFTING_MATRIX_ELEMENT) .addElement(ModBlocks.SPACE_OVERCOMPRESSOR.getId()) @@ -213,11 +213,11 @@ public static void init(RegistrumTagsProvider provider) { .addElement(ModBlocks.DEFLECTION_RING.getId()); provider.rawBuilder(ModBlockTags.ANVIL_HAMMER_BLACKLIST) - .addElement(findId(Blocks.NETHER_PORTAL)) - .addElement(findId(Blocks.PISTON_HEAD)) - .addElement(findId(Blocks.END_PORTAL_FRAME)) - .addElement(findId(Blocks.ATTACHED_MELON_STEM)) - .addElement(findId(Blocks.ATTACHED_PUMPKIN_STEM)) + .addElement(BlockTagLoader.findId(Blocks.NETHER_PORTAL)) + .addElement(BlockTagLoader.findId(Blocks.PISTON_HEAD)) + .addElement(BlockTagLoader.findId(Blocks.END_PORTAL_FRAME)) + .addElement(BlockTagLoader.findId(Blocks.ATTACHED_MELON_STEM)) + .addElement(BlockTagLoader.findId(Blocks.ATTACHED_PUMPKIN_STEM)) .addElement(ModBlocks.CELESTIAL_FORGING_ANVIL_INTERFACE_PLACEHOLDER.getId()) .addTag(BlockTags.BEDS.location()) .addTag(BlockTags.ALL_SIGNS.location()) @@ -234,57 +234,57 @@ public static void init(RegistrumTagsProvider provider) { .addTag(BlockTags.WART_BLOCKS.location()) .addTag(BlockTags.BEEHIVES.location()) .addTag(ModBlockTags.MUSHROOM_BLOCK.location()) - .addElement(findId(Blocks.MANGROVE_ROOTS)) - .addElement(findId(Blocks.SHROOMLIGHT)) - .addElement(findId(Blocks.MUSHROOM_STEM)) - .addElement(findId(Blocks.SUGAR_CANE)) - .addElement(findId(Blocks.BAMBOO_BLOCK)) - .addElement(findId(Blocks.CHORUS_PLANT)) - .addElement(findId(Blocks.CHORUS_FLOWER)) - .addElement(findId(Blocks.CACTUS)) - .addElement(findId(Blocks.KELP_PLANT)) - .addElement(findId(Blocks.BAMBOO)) - .addElement(findId(Blocks.BAMBOO_SAPLING)); + .addElement(BlockTagLoader.findId(Blocks.MANGROVE_ROOTS)) + .addElement(BlockTagLoader.findId(Blocks.SHROOMLIGHT)) + .addElement(BlockTagLoader.findId(Blocks.MUSHROOM_STEM)) + .addElement(BlockTagLoader.findId(Blocks.SUGAR_CANE)) + .addElement(BlockTagLoader.findId(Blocks.BAMBOO_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.CHORUS_PLANT)) + .addElement(BlockTagLoader.findId(Blocks.CHORUS_FLOWER)) + .addElement(BlockTagLoader.findId(Blocks.CACTUS)) + .addElement(BlockTagLoader.findId(Blocks.KELP_PLANT)) + .addElement(BlockTagLoader.findId(Blocks.BAMBOO)) + .addElement(BlockTagLoader.findId(Blocks.BAMBOO_SAPLING)); provider.rawBuilder(ModBlockTags.CLEANING_APPLICABLE) - .addElement(findId(Blocks.GRASS_BLOCK)) - .addElement(findId(Blocks.TALL_GRASS)) - .addElement(findId(Blocks.SHORT_GRASS)) - .addElement(findId(Blocks.FERN)) - .addElement(findId(Blocks.LARGE_FERN)) + .addElement(BlockTagLoader.findId(Blocks.GRASS_BLOCK)) + .addElement(BlockTagLoader.findId(Blocks.TALL_GRASS)) + .addElement(BlockTagLoader.findId(Blocks.SHORT_GRASS)) + .addElement(BlockTagLoader.findId(Blocks.FERN)) + .addElement(BlockTagLoader.findId(Blocks.LARGE_FERN)) .addTag(BlockTags.FLOWERS.location()) - .addElement(findId(Blocks.DEAD_BUSH)) - .addElement(findId(Blocks.RED_MUSHROOM)) - .addElement(findId(Blocks.BROWN_MUSHROOM)) - .addElement(findId(Blocks.CRIMSON_FUNGUS)) - .addElement(findId(Blocks.WARPED_FUNGUS)) - .addElement(findId(Blocks.CRIMSON_ROOTS)) - .addElement(findId(Blocks.WARPED_ROOTS)) - .addElement(findId(Blocks.NETHER_SPROUTS)) - .addElement(findId(Blocks.SCULK_VEIN)) - .addElement(findId(Blocks.COBWEB)) - .addElement(findId(Blocks.GLOW_LICHEN)) - .addElement(findId(Blocks.VINE)) - .addElement(findId(Blocks.SNOW)) - .addElement(findId(Blocks.MOSS_CARPET)) - .addElement(findId(Blocks.LILY_PAD)) - .addElement(findId(Blocks.SEAGRASS)) - .addElement(findId(Blocks.TALL_SEAGRASS)) - .addElement(findId(Blocks.SEA_PICKLE)) - .addElement(findId(Blocks.KELP_PLANT)) + .addElement(BlockTagLoader.findId(Blocks.DEAD_BUSH)) + .addElement(BlockTagLoader.findId(Blocks.RED_MUSHROOM)) + .addElement(BlockTagLoader.findId(Blocks.BROWN_MUSHROOM)) + .addElement(BlockTagLoader.findId(Blocks.CRIMSON_FUNGUS)) + .addElement(BlockTagLoader.findId(Blocks.WARPED_FUNGUS)) + .addElement(BlockTagLoader.findId(Blocks.CRIMSON_ROOTS)) + .addElement(BlockTagLoader.findId(Blocks.WARPED_ROOTS)) + .addElement(BlockTagLoader.findId(Blocks.NETHER_SPROUTS)) + .addElement(BlockTagLoader.findId(Blocks.SCULK_VEIN)) + .addElement(BlockTagLoader.findId(Blocks.COBWEB)) + .addElement(BlockTagLoader.findId(Blocks.GLOW_LICHEN)) + .addElement(BlockTagLoader.findId(Blocks.VINE)) + .addElement(BlockTagLoader.findId(Blocks.SNOW)) + .addElement(BlockTagLoader.findId(Blocks.MOSS_CARPET)) + .addElement(BlockTagLoader.findId(Blocks.LILY_PAD)) + .addElement(BlockTagLoader.findId(Blocks.SEAGRASS)) + .addElement(BlockTagLoader.findId(Blocks.TALL_SEAGRASS)) + .addElement(BlockTagLoader.findId(Blocks.SEA_PICKLE)) + .addElement(BlockTagLoader.findId(Blocks.KELP_PLANT)) .addTag(BlockTags.WALL_CORALS.location()) .addTag(BlockTags.CORAL_PLANTS.location()); provider.rawBuilder(ModBlockTags.BROKEN_CRYSTALS_CLUSTERS) - .addElement(findId(Blocks.AMETHYST_CLUSTER)); + .addElement(BlockTagLoader.findId(Blocks.AMETHYST_CLUSTER)); provider.rawBuilder(ModBlockTags.SPECTRAL_CAN_THROUGH) .addTag(Tags.Blocks.GLASS_BLOCKS.location()) .addTag(Tags.Blocks.GLASS_PANES.location()) .addTag(BlockTags.LEAVES.location()) - .addElement(findId(Blocks.IRON_BARS)) - .addElement(findId(Blocks.MANGROVE_ROOTS)) - .addElement(findId(Blocks.COPPER_GRATE)) + .addElement(BlockTagLoader.findId(Blocks.IRON_BARS)) + .addElement(BlockTagLoader.findId(Blocks.MANGROVE_ROOTS)) + .addElement(BlockTagLoader.findId(Blocks.COPPER_GRATE)) .addOptionalTag(ModBlockTags.AE2_GLASS_CABLE.location()) .addOptionalTag(ModBlockTags.AE2_COVERED_CABLE.location()) .addOptionalTag(ModBlockTags.AE2_SMART_CABLE.location()) @@ -293,7 +293,7 @@ public static void init(RegistrumTagsProvider provider) { provider.rawBuilder(ModBlockTags.HEATABLE_BLOCKS) .addTag(ModBlockTags.STORAGE_BLOCKS_TUNGSTEN.location()) - .addElement(findId(Blocks.NETHERITE_BLOCK)); + .addElement(BlockTagLoader.findId(Blocks.NETHERITE_BLOCK)); provider.rawBuilder(ModBlockTags.STICKABLE_WITH_SLIDING_RAILS) .addTag(ModBlockTags.SLIDING_RAILS.location()) @@ -365,7 +365,7 @@ public static void init(RegistrumTagsProvider provider) { provider.rawBuilder(ModBlockTags.SLIDING_RAIL_STOP_LIKE) .addTag(ModBlockTags.HEATABLE_BLOCKS.location()) - .addElement(findId(Blocks.CAMPFIRE)) + .addElement(BlockTagLoader.findId(Blocks.CAMPFIRE)) .addElement(ModBlocks.SLIDING_RAIL_STOP.getId()) .addElement(ModBlocks.HEATER.getId()) .addElement(ModBlocks.BURNING_HEATER.getId()) diff --git a/src/main/java/dev/dubhe/anvilcraft/data/tags/EntityTypeTagLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/tags/EntityTypeTagLoader.java index b56aba2bd7..67e6eea47a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/tags/EntityTypeTagLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/tags/EntityTypeTagLoader.java @@ -26,26 +26,26 @@ public static void init(RegistrumTagsProvider> provider) { .addOptionalTag(ModEntityTypeTags.SILENCE_AMULET_VALID.location()); provider.rawBuilder(ModEntityTypeTags.EMERALD_AMULET_VALID) - .addElement(findId(EntityType.IRON_GOLEM)) + .addElement(EntityTypeTagLoader.findId(EntityType.IRON_GOLEM)) .addTag(EntityTypeTags.ILLAGER.location()); provider.rawBuilder(ModEntityTypeTags.SAPPHIRE_AMULET_VALID) - .addElement(findId(EntityType.GUARDIAN)) - .addElement(findId(EntityType.ELDER_GUARDIAN)); + .addElement(EntityTypeTagLoader.findId(EntityType.GUARDIAN)) + .addElement(EntityTypeTagLoader.findId(EntityType.ELDER_GUARDIAN)); provider.rawBuilder(ModEntityTypeTags.ANVIL_AMULET_VALID) - .addElement(findId(EntityType.FALLING_BLOCK)) + .addElement(EntityTypeTagLoader.findId(EntityType.FALLING_BLOCK)) .addElement(ModEntities.FALLING_GIANT_ANVIL.getId()); provider.rawBuilder(ModEntityTypeTags.CAT_AMULET_VALID) - .addElement(findId(EntityType.CREEPER)) - .addElement(findId(EntityType.PHANTOM)); + .addElement(EntityTypeTagLoader.findId(EntityType.CREEPER)) + .addElement(EntityTypeTagLoader.findId(EntityType.PHANTOM)); provider.rawBuilder(ModEntityTypeTags.DOG_AMULET_VALID) .addTag(EntityTypeTags.SKELETONS.location()); provider.rawBuilder(ModEntityTypeTags.SILENCE_AMULET_VALID) - .addElement(findId(EntityType.WARDEN)); + .addElement(EntityTypeTagLoader.findId(EntityType.WARDEN)); provider.rawBuilder(ModEntityTypeTags.FALLING_GIANT_ANVIL_DAMAGE_IMMUNE) .addTag(EntityTypeTags.FALL_DAMAGE_IMMUNE.location()); diff --git a/src/main/java/dev/dubhe/anvilcraft/data/tags/FluidTagLoader.java b/src/main/java/dev/dubhe/anvilcraft/data/tags/FluidTagLoader.java index 8ea13918e6..1a01578a5a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/data/tags/FluidTagLoader.java +++ b/src/main/java/dev/dubhe/anvilcraft/data/tags/FluidTagLoader.java @@ -20,10 +20,10 @@ private static Identifier findId(Fluid item) { /// @param provider 提供器 public static void init(RegistrumTagsProvider provider) { provider.rawBuilder(ModFluidTags.MENGER_SPONGE_CAN_ABSORB) - .addElement(findId(Fluids.WATER)) - .addElement(findId(Fluids.FLOWING_WATER)) - .addElement(findId(Fluids.LAVA)) - .addElement(findId(Fluids.FLOWING_LAVA)) + .addElement(FluidTagLoader.findId(Fluids.WATER)) + .addElement(FluidTagLoader.findId(Fluids.FLOWING_WATER)) + .addElement(FluidTagLoader.findId(Fluids.LAVA)) + .addElement(FluidTagLoader.findId(Fluids.FLOWING_LAVA)) .addElement(ModFluids.OIL.getId()) .addElement(ModFluids.FLOWING_OIL.getId()) .addElement(ModFluids.MELT_GEM.getId()) diff --git a/src/main/java/dev/dubhe/anvilcraft/dfu/AnvilCraftDfu.java b/src/main/java/dev/dubhe/anvilcraft/dfu/AnvilCraftDfu.java index 4ea2b038ab..45569cfc0c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/dfu/AnvilCraftDfu.java +++ b/src/main/java/dev/dubhe/anvilcraft/dfu/AnvilCraftDfu.java @@ -14,7 +14,7 @@ public class AnvilCraftDfu { public static final int DATA_VERSION = 0; private static final Set REFERENCES; - private static final DataFixerBuilder.Result DFU = construct(); + private static final DataFixerBuilder.Result DFU = AnvilCraftDfu.construct(); static { ImmutableSet.Builder builder = ImmutableSet.builder(); @@ -22,15 +22,15 @@ public class AnvilCraftDfu { } public static DataFixerBuilder.Result construct() { - DataFixerBuilder builder = new DataFixerBuilder(DATA_VERSION); - addFixers(builder); + DataFixerBuilder builder = new DataFixerBuilder(AnvilCraftDfu.DATA_VERSION); + AnvilCraftDfu.addFixers(builder); return builder.build(); } public static void constructAndOptimize() { ProgressMeter meter = StartupNotificationManager.prependProgressBar("AnvilCraft DFU", 0); Executor exec = ModWorkManager.parallelExecutor(); - CompletableFuture result = DFU.optimize(REFERENCES, exec); + CompletableFuture result = AnvilCraftDfu.DFU.optimize(AnvilCraftDfu.REFERENCES, exec); result.join(); StartupNotificationManager.popBar(meter); } diff --git a/src/main/java/dev/dubhe/anvilcraft/enchantment/FellingEffect.java b/src/main/java/dev/dubhe/anvilcraft/enchantment/FellingEffect.java index ac2cb4433c..ed1333b02c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/enchantment/FellingEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/enchantment/FellingEffect.java @@ -46,7 +46,7 @@ public void apply(ServerLevel level, int i, EnchantedItemInUse enchantedItemInUs @Override public MapCodec codec() { - return CODEC; + return FellingEffect.CODEC; } /// 连锁破坏 diff --git a/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestLeftClickEffect.java b/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestLeftClickEffect.java index 853ce9eac6..cc5f9b7bc5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestLeftClickEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestLeftClickEffect.java @@ -123,6 +123,6 @@ private boolean isGrass(BlockState state) { @Override public MapCodec codec() { - return CODEC; + return HarvestLeftClickEffect.CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestRightClickEffect.java b/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestRightClickEffect.java index 4928700f80..bcbdc1f39f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestRightClickEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/enchantment/HarvestRightClickEffect.java @@ -147,6 +147,6 @@ private Block harvestable(BlockState state) { @Override public MapCodec codec() { - return CODEC; + return HarvestRightClickEffect.CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/enchantment/InRangeModifyEffect.java b/src/main/java/dev/dubhe/anvilcraft/enchantment/InRangeModifyEffect.java index 90124cdf37..27a0204ecb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/enchantment/InRangeModifyEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/enchantment/InRangeModifyEffect.java @@ -15,10 +15,10 @@ public record InRangeModifyEffect( private static final LevelBasedValue MAX = new LevelBasedValue.Constant(Float.MAX_VALUE); public static final MapCodec CODEC = RecordCodecBuilder.mapCodec(inst -> inst.group( LevelBasedValue.CODEC - .optionalFieldOf("min", MIN) + .optionalFieldOf("min", InRangeModifyEffect.MIN) .forGetter(InRangeModifyEffect::min), LevelBasedValue.CODEC - .optionalFieldOf("max", MAX) + .optionalFieldOf("max", InRangeModifyEffect.MAX) .forGetter(InRangeModifyEffect::max), EnchantmentValueEffect.CODEC .fieldOf("modifier") @@ -26,11 +26,11 @@ public record InRangeModifyEffect( ).apply(inst, InRangeModifyEffect::new)); public static InRangeModifyEffect min(int min, EnchantmentValueEffect modifier) { - return new InRangeModifyEffect(new LevelBasedValue.Constant(min), MAX, modifier); + return new InRangeModifyEffect(new LevelBasedValue.Constant(min), InRangeModifyEffect.MAX, modifier); } public static InRangeModifyEffect max(int max, EnchantmentValueEffect modifier) { - return new InRangeModifyEffect(MIN, new LevelBasedValue.Constant(max), modifier); + return new InRangeModifyEffect(InRangeModifyEffect.MIN, new LevelBasedValue.Constant(max), modifier); } public static InRangeModifyEffect range(int min, int max, EnchantmentValueEffect modifier) { @@ -47,6 +47,6 @@ public float process(int enchantmentLevel, RandomSource random, float value) { @Override public MapCodec codec() { - return CODEC; + return InRangeModifyEffect.CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/AnimateAscendingBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/AnimateAscendingBlockEntity.java index 345ee0940d..3a13d21f3b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/AnimateAscendingBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/AnimateAscendingBlockEntity.java @@ -63,24 +63,25 @@ private AnimateAscendingBlockEntity(Level level, double x, double y, double z, B } public void setStartPos(BlockPos startPos) { - this.entityData.set(DATA_START_POS, startPos); + this.entityData.set(AnimateAscendingBlockEntity.DATA_START_POS, startPos); } public BlockPos getStartPos() { - return this.entityData.get(DATA_START_POS); + return this.entityData.get(AnimateAscendingBlockEntity.DATA_START_POS); } public void setEndPos(BlockPos startPos) { - this.entityData.set(DATA_END_POS, startPos); + this.entityData.set(AnimateAscendingBlockEntity.DATA_END_POS, startPos); } public BlockPos getEndPos() { - return this.entityData.get(DATA_END_POS); + return this.entityData.get(AnimateAscendingBlockEntity.DATA_END_POS); } @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { - builder.define(DATA_START_POS, BlockPos.ZERO).define(DATA_END_POS, BlockPos.ZERO); + builder.define(AnimateAscendingBlockEntity.DATA_START_POS, BlockPos.ZERO).define( + AnimateAscendingBlockEntity.DATA_END_POS, BlockPos.ZERO); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/CauldronOutletEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/CauldronOutletEntity.java index ca8366e01e..f866e64deb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/CauldronOutletEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/CauldronOutletEntity.java @@ -304,33 +304,33 @@ public boolean hurtServer(ServerLevel level, DamageSource source, float damage) @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { - builder.define(DATA_CAULDRON_POS, BlockPos.ZERO) - .define(DATA_ATTACHED_DIRECTION, Direction.UP) - .define(DATA_CAULDRON_STATE, Blocks.AIR.defaultBlockState()); + builder.define(CauldronOutletEntity.DATA_CAULDRON_POS, BlockPos.ZERO) + .define(CauldronOutletEntity.DATA_ATTACHED_DIRECTION, Direction.UP) + .define(CauldronOutletEntity.DATA_CAULDRON_STATE, Blocks.AIR.defaultBlockState()); } public BlockPos getCauldronPos() { - return this.entityData.get(DATA_CAULDRON_POS); + return this.entityData.get(CauldronOutletEntity.DATA_CAULDRON_POS); } public void setCauldronPos(BlockPos pos) { - this.entityData.set(DATA_CAULDRON_POS, pos); + this.entityData.set(CauldronOutletEntity.DATA_CAULDRON_POS, pos); } public Direction getAttachedDirection() { - return this.entityData.get(DATA_ATTACHED_DIRECTION); + return this.entityData.get(CauldronOutletEntity.DATA_ATTACHED_DIRECTION); } public void setAttachedDirection(Direction direction) { - this.entityData.set(DATA_ATTACHED_DIRECTION, direction); + this.entityData.set(CauldronOutletEntity.DATA_ATTACHED_DIRECTION, direction); } public BlockState getCauldronState() { - return this.entityData.get(DATA_CAULDRON_STATE); + return this.entityData.get(CauldronOutletEntity.DATA_CAULDRON_STATE); } public void setCauldronState(BlockState state) { - this.entityData.set(DATA_CAULDRON_STATE, state); + this.entityData.set(CauldronOutletEntity.DATA_CAULDRON_STATE, state); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/FallingSpectralBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/FallingSpectralBlockEntity.java index d586d35868..3f80872cb4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/FallingSpectralBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/FallingSpectralBlockEntity.java @@ -5,6 +5,7 @@ import dev.dubhe.anvilcraft.block.workstation.SpectralAnvilBlock; import dev.dubhe.anvilcraft.init.block.ModBlockTags; import dev.dubhe.anvilcraft.init.entity.ModEntities; +import dev.dubhe.anvilcraft.util.EntityUtil; import it.unimi.dsi.fastutil.floats.FloatArraySet; import it.unimi.dsi.fastutil.floats.FloatArrays; import it.unimi.dsi.fastutil.floats.FloatSet; @@ -144,7 +145,7 @@ public void tick() { public Vec3 collide(Vec3 vec) { AABB aabb = this.getBoundingBox(); List list = this.level().getEntityCollisions(this, aabb.expandTowards(vec)); - Vec3 vec3 = vec.lengthSqr() == 0.0 ? vec : collideBoundingBox(this, vec, aabb, this.level(), list); + Vec3 vec3 = vec.lengthSqr() == 0.0 ? vec : FallingSpectralBlockEntity.collideBoundingBox(this, vec, aabb, this.level(), list); boolean flag = vec.x != vec3.x; boolean flag1 = vec.y != vec3.y; boolean flag2 = vec.z != vec3.z; @@ -156,12 +157,12 @@ public Vec3 collide(Vec3 vec) { aabb2 = aabb2.expandTowards(0.0, -1.0E-5F, 0.0); } - List list1 = collectColliders(this, this.level(), list, aabb2); + List list1 = FallingSpectralBlockEntity.collectColliders(this, this.level(), list, aabb2); float f = (float) vec3.y; - float[] afloat = collectCandidateStepUpHeights(aabb1, list1, this.maxUpStep(), f); + float[] afloat = FallingSpectralBlockEntity.collectCandidateStepUpHeights(aabb1, list1, this.maxUpStep(), f); for (float f1 : afloat) { - Vec3 vec31 = collideWithShapes(new Vec3(vec.x, f1, vec.z), aabb1, list1); + Vec3 vec31 = Entity.collideWithShapes(new Vec3(vec.x, f1, vec.z), aabb1, list1); if (vec31.horizontalDistanceSqr() > vec3.horizontalDistanceSqr()) { double d0 = aabb.minY - aabb1.minY; return vec31.add(0.0, -d0, 0.0); @@ -178,8 +179,8 @@ public static Vec3 collideBoundingBox( Level level, List potentialHits ) { - List list = collectColliders(entity, level, potentialHits, collisionBox.expandTowards(vec)); - return collideWithShapes(vec, collisionBox, list); + List list = FallingSpectralBlockEntity.collectColliders(entity, level, potentialHits, collisionBox.expandTowards(vec)); + return Entity.collideWithShapes(vec, collisionBox, list); } private static @Unmodifiable List collectColliders( @@ -199,7 +200,7 @@ public static Vec3 collideBoundingBox( builder.add(worldborder.getCollisionShape()); } - builder.addAll(getBlockCollisions(level, entity, boundingBox)); + builder.addAll(FallingSpectralBlockEntity.getBlockCollisions(level, entity, boundingBox)); return builder.build(); } @@ -232,7 +233,7 @@ private static Iterable getBlockCollisions(Level level, @Nullable En false, (pos, shape) -> { BlockState state = level.getBlockState(pos); - if (shouldIgnoreBlockInMovement(state)) { + if (FallingSpectralBlockEntity.shouldIgnoreBlockInMovement(state)) { return Shapes.empty(); } return shape; @@ -264,8 +265,7 @@ public boolean causeFallDamage(double fallDistance, float damageModifier, Damage ? fallable.getFallDamageSource(this) : this.damageSources().fallingBlock(this); this.level().getEntities(this, this.getBoundingBox(), predicate).forEach(entity -> { - // noinspection deprecation - entity.hurtOrSimulate(damageSource, f); + EntityUtil.hurtOrSimulate(entity, damageSource, f); if (this.level() instanceof ServerLevel serverLevel) { NeoForge.EVENT_BUS.post(new AnvilEvent.HurtEntity(this, this.getOnPos(), serverLevel, entity, f)); } @@ -283,10 +283,9 @@ public boolean causeFallDamage(double fallDistance, float damageModifier, Damage } protected static boolean shouldIgnoreBlockInMovement(BlockState state) { - // noinspection deprecation return state.isAir() || state.is(BlockTags.FIRE) - || state.liquid() + || !state.getFluidState().isEmpty() || state.is(ModBlockTags.SPECTRAL_CAN_THROUGH) || state.getBlock() instanceof TransparentBlock || state.canBeReplaced() diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/FloatingBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/FloatingBlockEntity.java index e1b59a670b..d63710d422 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/FloatingBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/FloatingBlockEntity.java @@ -110,13 +110,13 @@ public void tick() { ) { this.discard(); this.callOnBrokenAfterFall(block, blockPos); - this.spawnAtLocation((ServerLevel) level(), block); + this.spawnAtLocation((ServerLevel) this.level(), block); } } else { this.discard(); if (this.dropItem && this.level().getServer().getGameRules().get(GameRules.ENTITY_DROPS)) { this.callOnBrokenAfterFall(block, blockPos); - this.spawnAtLocation((ServerLevel) level(), block); + this.spawnAtLocation((ServerLevel) this.level(), block); } } } else { diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/FluidTankMinecartEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/FluidTankMinecartEntity.java index 653993d3ed..ab9020d815 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/FluidTankMinecartEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/FluidTankMinecartEntity.java @@ -18,6 +18,7 @@ import net.minecraft.util.ProblemReporter; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.player.Player; @@ -56,7 +57,7 @@ public class FluidTankMinecartEntity extends AbstractMinecart implements IFluidR EntityDataSerializers.INT ); - private final FluidStackResourceHandler tank = new FluidStackResourceHandler(CAPACITY); + private final FluidStackResourceHandler tank = new FluidStackResourceHandler(FluidTankMinecartEntity.CAPACITY); private @Nullable BlockPos fluidNetworkPos; private FluidStack lastSyncedFluid = FluidStack.EMPTY; @@ -77,7 +78,7 @@ public FluidTankMinecartEntity( @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { super.defineSynchedData(builder); - builder.define(FLUID_ID, -1).define(FLUID_AMOUNT, 0); + builder.define(FluidTankMinecartEntity.FLUID_ID, -1).define(FluidTankMinecartEntity.FLUID_AMOUNT, 0); } @Override @@ -155,7 +156,7 @@ public ItemStack getPickResult() { } @Override - protected void destroy(ServerLevel level, net.minecraft.world.damagesource.DamageSource source) { + protected void destroy(ServerLevel level, DamageSource source) { this.kill(level); if (level.getGameRules().get(GameRules.ENTITY_DROPS)) { this.spawnAtLocation(level, this.createDropStack()); @@ -174,7 +175,7 @@ private ItemStack createItemStack(boolean includeFluid) { ProblemReporter.DISCARDING, this.registryAccess() ); - this.tank.serialize(output.child(TAG_TANK)); + this.tank.serialize(output.child(FluidTankMinecartEntity.TAG_TANK)); BlockItem.setBlockEntityData(stack, ModBlockEntities.FLUID_TANK.get(), output); } if (this.getCustomName() != null) { @@ -187,7 +188,7 @@ private ItemStack createItemStack(boolean includeFluid) { public void loadTankFromItem(ItemStack stack) { TypedEntityData data = stack.get(DataComponents.BLOCK_ENTITY_DATA); if (data == null) return; - data.copyTagWithoutId().getCompound(TAG_TANK).ifPresent(tankTag -> { + data.copyTagWithoutId().getCompound(FluidTankMinecartEntity.TAG_TANK).ifPresent(tankTag -> { this.loadTank(tankTag); this.syncFluidData(); }); @@ -196,13 +197,13 @@ public void loadTankFromItem(ItemStack stack) { @Override protected void addAdditionalSaveData(ValueOutput output) { super.addAdditionalSaveData(output); - this.tank.serialize(output.child(TAG_TANK)); + this.tank.serialize(output.child(FluidTankMinecartEntity.TAG_TANK)); } @Override protected void readAdditionalSaveData(ValueInput input) { super.readAdditionalSaveData(input); - this.tank.deserialize(input.childOrEmpty(TAG_TANK)); + this.tank.deserialize(input.childOrEmpty(FluidTankMinecartEntity.TAG_TANK)); this.syncFluidData(); } @@ -216,25 +217,25 @@ private void syncFluidData() { FluidStack fluid = this.tank.getStack(); if (FluidStack.matches(fluid, this.lastSyncedFluid)) return; this.lastSyncedFluid = fluid.copy(); - this.entityData.set(FLUID_ID, fluid.isEmpty() ? -1 : BuiltInRegistries.FLUID.getId(fluid.getFluid())); - this.entityData.set(FLUID_AMOUNT, fluid.getAmount()); + this.entityData.set(FluidTankMinecartEntity.FLUID_ID, fluid.isEmpty() ? -1 : BuiltInRegistries.FLUID.getId(fluid.getFluid())); + this.entityData.set(FluidTankMinecartEntity.FLUID_AMOUNT, fluid.getAmount()); } /// 按罐内存量给出的比较器强度,同时用于摩擦计算 public int getComparatorLevel() { int amount = this.tank.getStack().getAmount(); - return amount == 0 ? 0 : Mth.floor(amount * 14.0F / CAPACITY) + 1; + return amount == 0 ? 0 : Mth.floor(amount * 14.0F / FluidTankMinecartEntity.CAPACITY) + 1; } /// 获取用于渲染的流体内容;客户端读取同步数据,服务端直接读罐 public FluidStack getSyncedFluid() { if (!this.level().isClientSide()) return this.tank.getStack(); - int id = this.entityData.get(FLUID_ID); - int amount = this.entityData.get(FLUID_AMOUNT); + int id = this.entityData.get(FluidTankMinecartEntity.FLUID_ID); + int amount = this.entityData.get(FluidTankMinecartEntity.FLUID_AMOUNT); if (id < 0 || amount <= 0) return FluidStack.EMPTY; Fluid fluid = BuiltInRegistries.FLUID.byId(id); if (fluid == Fluids.EMPTY) return FluidStack.EMPTY; - return new FluidStack(fluid, Math.min(amount, CAPACITY)); + return new FluidStack(fluid, Math.min(amount, FluidTankMinecartEntity.CAPACITY)); } @Override @@ -247,6 +248,6 @@ public int getFluidAmount() { } public int getCapacity() { - return CAPACITY; + return FluidTankMinecartEntity.CAPACITY; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/IonocraftEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/IonocraftEntity.java index c4378ff4c2..75e26eb90d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/IonocraftEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/IonocraftEntity.java @@ -37,13 +37,13 @@ public IonocraftEntity(Level level, Vec3 pos) { this.yo = pos.y; this.zo = pos.z; this.component = new DynamicPowerComponent(this, this::getPowerSupplyingBoundingBox); - this.component.getPowerConsumptions().add(CONSUMPTION); + this.component.getPowerConsumptions().add(IonocraftEntity.CONSUMPTION); } public IonocraftEntity(EntityType type, Level level) { super(type, level); this.component = new DynamicPowerComponent(this, this::getPowerSupplyingBoundingBox); - this.component.getPowerConsumptions().add(CONSUMPTION); + this.component.getPowerConsumptions().add(IonocraftEntity.CONSUMPTION); } public AABB getPowerSupplyingBoundingBox() { @@ -68,9 +68,9 @@ protected void defineSynchedData(SynchedEntityData.Builder builder) { @Override public void tick() { this.setDeltaMovement(this.getDeltaMovement().multiply(0.8, 0.8, 0.8)); - if (!level().isClientSide()) { - PowerGrid powerGrid = PowerGrid.findPowerGridContains(level(), this.getPowerSupplyingBoundingBox()).orElse(null); - PowerGrid findSmaller = PowerGrid.findPowerGridContains(level(), this.getBoundingBox()).orElse(null); + if (!this.level().isClientSide()) { + PowerGrid powerGrid = PowerGrid.findPowerGridContains(this.level(), this.getPowerSupplyingBoundingBox()).orElse(null); + PowerGrid findSmaller = PowerGrid.findPowerGridContains(this.level(), this.getBoundingBox()).orElse(null); this.component.switchTo(powerGrid); if (findSmaller == null && powerGrid != null) { if (!(this.component.getPowerGrid() != null && this.component.getPowerGrid().isWorking())) { diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/MagnetizedNodeEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/MagnetizedNodeEntity.java index 0cfa31304f..25d05ff167 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/MagnetizedNodeEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/MagnetizedNodeEntity.java @@ -71,10 +71,10 @@ public void tick() { this.blockPos.getY() + 1.01, this.blockPos.getZ() + 1.01 ); - level() + this.level() .getEntities(EntityType.ITEM, aabb, IItemEntityExtension::anvilcraft$isAdsorbable) .forEach(entity -> { - entity.teleportTo(position().x, position().y, position().z); + entity.teleportTo(this.position().x, this.position().y, this.position().z); entity.setDeltaMovement(Vec3.ZERO); }); } @@ -96,7 +96,9 @@ public boolean hurtServer(ServerLevel level, DamageSource source, float damage) @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { - builder.define(DATA_BLOCK_POS, BlockPos.ZERO).define(DATA_BLOCK_STATE, Blocks.AIR.defaultBlockState()); + builder + .define(MagnetizedNodeEntity.DATA_BLOCK_POS, BlockPos.ZERO) + .define(MagnetizedNodeEntity.DATA_BLOCK_STATE, Blocks.AIR.defaultBlockState()); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/RailgunAnvilEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/RailgunAnvilEntity.java index ed9927696e..f3cb86646c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/RailgunAnvilEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/RailgunAnvilEntity.java @@ -76,11 +76,11 @@ public static RailgunAnvilEntity create( ) { RailgunAnvilEntity entity = new RailgunAnvilEntity(ModEntities.RAILGUN_ANVIL.get(), level); entity.setPos(owner.getEyePosition().add(owner.getViewVector(1.0F).scale(0.75))); - entity.entityData.set(DISPLAY_STATE, state); - entity.entityData.set(GHOST, ghost); - entity.entityData.set(PIERCE, pierce); - entity.entityData.set(KNOCKBACK, knockback); - entity.entityData.set(OWNER_ID, owner.getId()); + entity.entityData.set(RailgunAnvilEntity.DISPLAY_STATE, state); + entity.entityData.set(RailgunAnvilEntity.GHOST, ghost); + entity.entityData.set(RailgunAnvilEntity.PIERCE, pierce); + entity.entityData.set(RailgunAnvilEntity.KNOCKBACK, knockback); + entity.entityData.set(RailgunAnvilEntity.OWNER_ID, owner.getId()); entity.owner = owner.getUUID(); entity.weapon = weapon.copy(); entity.dropItem = !ghost; @@ -90,7 +90,7 @@ public static RailgunAnvilEntity create( @Override public BlockState getBlockState() { - return this.entityData.get(DISPLAY_STATE); + return this.entityData.get(RailgunAnvilEntity.DISPLAY_STATE); } @Override @@ -210,7 +210,7 @@ private boolean convertToFallingBlock(AccelerateManager.AccelerationEntry accele if (falling.getBlockState().getBlock() instanceof FallingBlock fallingBlock) { fallingBlock.falling(falling); } - if (this.entityData.get(GHOST)) { + if (this.entityData.get(RailgunAnvilEntity.GHOST)) { falling.dropItem = false; falling.disableDrop(); } @@ -223,9 +223,9 @@ private boolean convertToFallingBlock(AccelerateManager.AccelerationEntry accele private void hit(EntityHitResult hit) { Entity target = hit.getEntity(); this.hitEntities.add(target.getUUID()); - Entity ownerEntity = this.owner == null ? null : ((ServerLevel) this.level()).getEntity(this.owner); + Entity ownerEntity = this.owner == null ? null : this.level().getEntity(this.owner); float damage = (float) (this.getDeltaMovement().length() * 2.0) - * BASE_DAMAGE_MULTIPLIER + * RailgunAnvilEntity.BASE_DAMAGE_MULTIPLIER * this.getAmmoDamageMultiplier(); DamageSource source = ownerEntity instanceof LivingEntity livingOwner ? this.damageSources().source(DamageTypes.FALLING_ANVIL, this, livingOwner) @@ -237,7 +237,7 @@ private void hit(EntityHitResult hit) { livingOwner.setLastHurtMob(target); EnchantmentHelper.doPostAttackEffectsWithItemSource( (ServerLevel) this.level(), livingTarget, source, this.weapon); - int knockback = this.entityData.get(KNOCKBACK); + int knockback = this.entityData.get(RailgunAnvilEntity.KNOCKBACK); if (knockback > 0) { livingTarget.push( this.getDeltaMovement().x * knockback * 0.4, @@ -246,16 +246,16 @@ private void hit(EntityHitResult hit) { ); } } - if (this.hitEntities.size() > this.entityData.get(PIERCE)) this.startFalling(); + if (this.hitEntities.size() > this.entityData.get(RailgunAnvilEntity.PIERCE)) this.startFalling(); } private void startFalling() { if (!this.isFlying()) return; - this.entityData.set(FLYING, false); + this.entityData.set(RailgunAnvilEntity.FLYING, false); this.blockState = this.getBlockState(); this.setNoGravity(false); this.setDeltaMovement(0.0, Math.min(0.0, this.getDeltaMovement().y), 0.0); - if (this.entityData.get(GHOST) || this.loyalty) { + if (this.entityData.get(RailgunAnvilEntity.GHOST) || this.loyalty) { this.cancelDrop = true; this.dropItem = false; } @@ -271,7 +271,7 @@ private float getAmmoDamageMultiplier() { private void startReturning() { if (this.level().isClientSide() || this.isReturning()) return; - this.entityData.set(RETURNING, true); + this.entityData.set(RailgunAnvilEntity.RETURNING, true); this.setNoGravity(true); this.noPhysics = true; this.setDeltaMovement(Vec3.ZERO); @@ -306,10 +306,10 @@ private void tickReturning() { } private @Nullable Entity getOwnerEntity() { - Entity entity = this.level().getEntity(this.entityData.get(OWNER_ID)); + Entity entity = this.level().getEntity(this.entityData.get(RailgunAnvilEntity.OWNER_ID)); if (entity != null || !(this.level() instanceof ServerLevel serverLevel) || this.owner == null) return entity; entity = serverLevel.getEntity(this.owner); - if (entity != null) this.entityData.set(OWNER_ID, entity.getId()); + if (entity != null) this.entityData.set(RailgunAnvilEntity.OWNER_ID, entity.getId()); return entity; } @@ -329,7 +329,7 @@ private void dropReturnedItem(Vec3 position, int pickupDelay) { } public boolean isReturning() { - return this.entityData.get(RETURNING); + return this.entityData.get(RailgunAnvilEntity.RETURNING); } public ItemStack getReturnedItem() { @@ -339,22 +339,22 @@ public ItemStack getReturnedItem() { @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { super.defineSynchedData(builder); - builder.define(DISPLAY_STATE, Blocks.ANVIL.defaultBlockState()) - .define(GHOST, false) - .define(PIERCE, 0) - .define(KNOCKBACK, 0) - .define(FLYING, true) - .define(RETURNING, false) - .define(OWNER_ID, -1); + builder.define(RailgunAnvilEntity.DISPLAY_STATE, Blocks.ANVIL.defaultBlockState()) + .define(RailgunAnvilEntity.GHOST, false) + .define(RailgunAnvilEntity.PIERCE, 0) + .define(RailgunAnvilEntity.KNOCKBACK, 0) + .define(RailgunAnvilEntity.FLYING, true) + .define(RailgunAnvilEntity.RETURNING, false) + .define(RailgunAnvilEntity.OWNER_ID, -1); } @Override protected void addAdditionalSaveData(ValueOutput output) { super.addAdditionalSaveData(output); output.putBoolean("Flying", this.isFlying()); - output.putBoolean("Ghost", this.entityData.get(GHOST)); - output.putInt("Pierce", this.entityData.get(PIERCE)); - output.putInt("Knockback", this.entityData.get(KNOCKBACK)); + output.putBoolean("Ghost", this.entityData.get(RailgunAnvilEntity.GHOST)); + output.putInt("Pierce", this.entityData.get(RailgunAnvilEntity.PIERCE)); + output.putInt("Knockback", this.entityData.get(RailgunAnvilEntity.KNOCKBACK)); output.putBoolean("Loyalty", this.loyalty); output.putBoolean("Returning", this.isReturning()); output.putInt("FlightTicks", this.tickCount); @@ -368,30 +368,30 @@ protected void addAdditionalSaveData(ValueOutput output) { @Override protected void readAdditionalSaveData(ValueInput input) { super.readAdditionalSaveData(input); - this.entityData.set(FLYING, input.getBooleanOr("Flying", true)); - this.entityData.set(GHOST, input.getBooleanOr("Ghost", false)); - this.entityData.set(PIERCE, input.getIntOr("Pierce", 0)); - this.entityData.set(KNOCKBACK, input.getIntOr("Knockback", 0)); + this.entityData.set(RailgunAnvilEntity.FLYING, input.getBooleanOr("Flying", true)); + this.entityData.set(RailgunAnvilEntity.GHOST, input.getBooleanOr("Ghost", false)); + this.entityData.set(RailgunAnvilEntity.PIERCE, input.getIntOr("Pierce", 0)); + this.entityData.set(RailgunAnvilEntity.KNOCKBACK, input.getIntOr("Knockback", 0)); this.loyalty = input.getBooleanOr("Loyalty", false); - this.entityData.set(RETURNING, input.getBooleanOr("Returning", false)); + this.entityData.set(RailgunAnvilEntity.RETURNING, input.getBooleanOr("Returning", false)); this.tickCount = input.getIntOr("FlightTicks", 0); if (this.isReturning()) { this.setNoGravity(true); this.noPhysics = true; } - input.read("DisplayState", BlockState.CODEC).ifPresent(state -> this.entityData.set(DISPLAY_STATE, state)); + input.read("DisplayState", BlockState.CODEC).ifPresent(state -> this.entityData.set(RailgunAnvilEntity.DISPLAY_STATE, state)); this.owner = input.read("Owner", UUIDUtil.CODEC).orElse(null); this.weapon = input.read("Weapon", ItemStack.OPTIONAL_CODEC).orElse(ItemStack.EMPTY); this.hitEntities.clear(); input.listOrEmpty("HitEntities", UUIDUtil.CODEC).forEach(this.hitEntities::add); - if (this.entityData.get(GHOST) || this.loyalty) { + if (this.entityData.get(RailgunAnvilEntity.GHOST) || this.loyalty) { this.dropItem = false; this.disableDrop(); } } private boolean isFlying() { - return this.entityData.get(FLYING); + return this.entityData.get(RailgunAnvilEntity.FLYING); } private record MovementResult(boolean collided, Vec3 velocity, boolean converted) { diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/SlidingBlockEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/SlidingBlockEntity.java index 4222fdaa1f..6c76d4e0d2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/SlidingBlockEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/SlidingBlockEntity.java @@ -43,7 +43,7 @@ public class SlidingBlockEntity extends Entity { @Setter private SlidingBlockSection section; @Getter - private Direction moveDirection; + private Direction moveDirection = Direction.NORTH; private int time = 0; public SlidingBlockEntity(EntityType entityType, Level level) { @@ -115,7 +115,7 @@ public void tick() { if (this.level().isOutsideBuildHeight(pos)) { this.stop(); } else if (this.checkCanMove()) { - this.setDeltaMovement(Vec3.ZERO.relative(this.moveDirection, DEFAULT_MOVEMENT)); + this.setDeltaMovement(Vec3.ZERO.relative(this.moveDirection, SlidingBlockEntity.DEFAULT_MOVEMENT)); } else if (!this.level().isClientSide() && !this.isRemoved()) { this.setDeltaMovement(Vec3.ZERO); this.stop(); @@ -168,11 +168,11 @@ public boolean isAttackable() { } public void setStartPos(BlockPos startPos) { - this.entityData.set(DATA_START_POS, startPos); + this.entityData.set(SlidingBlockEntity.DATA_START_POS, startPos); } public BlockPos getStartPos() { - return this.entityData.get(DATA_START_POS); + return this.entityData.get(SlidingBlockEntity.DATA_START_POS); } @Override @@ -187,7 +187,7 @@ public boolean hurtServer(ServerLevel level, DamageSource source, float damage) @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { - builder.define(DATA_START_POS, BlockPos.ZERO); + builder.define(SlidingBlockEntity.DATA_START_POS, BlockPos.ZERO); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/SpectralProjectileEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/SpectralProjectileEntity.java index 15d5a01088..0ec6f9ca2e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/SpectralProjectileEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/SpectralProjectileEntity.java @@ -3,6 +3,7 @@ import dev.anvilcraft.lib.v2.util.Util; import dev.dubhe.anvilcraft.init.entity.ModEntities; import dev.dubhe.anvilcraft.mixin.accessor.AbstractArrowAccessor; +import dev.dubhe.anvilcraft.util.EntityUtil; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.core.registries.Registries; @@ -41,12 +42,12 @@ public class SpectralProjectileEntity extends AbstractArrow { public SpectralProjectileEntity(EntityType entityType, Level level) { super(entityType, level); - this.entityData.set(AS_ITEM_STACK, ItemStack.EMPTY); + this.entityData.set(SpectralProjectileEntity.AS_ITEM_STACK, ItemStack.EMPTY); } public SpectralProjectileEntity(Level level, LivingEntity owner, ItemStack pickupItemStack, @Nullable ItemStack firedFromWeapon) { super(ModEntities.SPECTRAL_PROJECTILE.get(), owner, level, pickupItemStack, firedFromWeapon); - this.entityData.set(AS_ITEM_STACK, ItemStack.EMPTY); + this.entityData.set(SpectralProjectileEntity.AS_ITEM_STACK, ItemStack.EMPTY); } public static SpectralProjectileEntity of( @@ -63,7 +64,7 @@ public static SpectralProjectileEntity of( firedFromWeapon ); // pickup item不让为空,这里给光灵箭是在玩双关梗()实际上它总是不让捡起来 - sp.entityData.set(AS_ITEM_STACK, asStack); + sp.entityData.set(SpectralProjectileEntity.AS_ITEM_STACK, asStack); sp.pickup = Pickup.DISALLOWED; if (asStack.is(ItemTags.ARROWS)) sp.setBaseDamage(5.0); else { @@ -82,7 +83,7 @@ public static SpectralProjectileEntity of( } public ItemStack getAsItemStack() { - return this.entityData.get(AS_ITEM_STACK); + return this.entityData.get(SpectralProjectileEntity.AS_ITEM_STACK); } @Override @@ -93,7 +94,7 @@ protected ItemStack getDefaultPickupItem() { @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { super.defineSynchedData(builder); - builder.define(AS_ITEM_STACK, Items.ARROW.getDefaultInstance()); + builder.define(SpectralProjectileEntity.AS_ITEM_STACK, Items.ARROW.getDefaultInstance()); } @Override @@ -170,8 +171,7 @@ protected void onHitEntity(EntityHitResult result) { entity.igniteForSeconds(5.0F); } - // noinspection deprecation - if (entity.hurtOrSimulate(damagesource, j)) { + if (EntityUtil.hurtOrSimulate(entity, damagesource, j)) { if (flag) { return; } diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/ThrownHeavyHalberdEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/ThrownHeavyHalberdEntity.java index df44d33a03..cb22dc5eb6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/ThrownHeavyHalberdEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/ThrownHeavyHalberdEntity.java @@ -3,6 +3,7 @@ import dev.anvilcraft.lib.v2.util.Util; import dev.dubhe.anvilcraft.item.tool.HeavyHalberdItem; import dev.dubhe.anvilcraft.mixin.accessor.AbstractArrowAccessor; +import dev.dubhe.anvilcraft.util.EntityUtil; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; @@ -47,8 +48,8 @@ public ThrownHeavyHalberdEntity( ) { super(type, shooter, level, pickupItemStack, null); this.setBaseDamage(HeavyHalberdItem.getThrownBaseDamage(pickupItemStack)); - this.entityData.set(ID_LOYALTY, this.getLoyaltyFromItem(pickupItemStack)); - this.entityData.set(ID_FOIL, pickupItemStack.hasFoil()); + this.entityData.set(ThrownHeavyHalberdEntity.ID_LOYALTY, this.getLoyaltyFromItem(pickupItemStack)); + this.entityData.set(ThrownHeavyHalberdEntity.ID_FOIL, pickupItemStack.hasFoil()); } public ThrownHeavyHalberdEntity( @@ -56,8 +57,8 @@ public ThrownHeavyHalberdEntity( ) { super(type, x, y, z, level, pickupItemStack, pickupItemStack); this.setBaseDamage(HeavyHalberdItem.getThrownBaseDamage(pickupItemStack)); - this.entityData.set(ID_LOYALTY, this.getLoyaltyFromItem(pickupItemStack)); - this.entityData.set(ID_FOIL, pickupItemStack.hasFoil()); + this.entityData.set(ThrownHeavyHalberdEntity.ID_LOYALTY, this.getLoyaltyFromItem(pickupItemStack)); + this.entityData.set(ThrownHeavyHalberdEntity.ID_FOIL, pickupItemStack.hasFoil()); } public abstract String getTextureBase(); @@ -65,8 +66,8 @@ public ThrownHeavyHalberdEntity( @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { super.defineSynchedData(builder); - builder.define(ID_LOYALTY, (byte) 0); - builder.define(ID_FOIL, false); + builder.define(ThrownHeavyHalberdEntity.ID_LOYALTY, (byte) 0); + builder.define(ThrownHeavyHalberdEntity.ID_FOIL, false); } @Override @@ -76,7 +77,7 @@ public void tick() { } Entity currentOwner = this.getOwner(); - int loyalty = this.entityData.get(ID_LOYALTY); + int loyalty = this.entityData.get(ThrownHeavyHalberdEntity.ID_LOYALTY); if (loyalty > 0 && (this.dealtDamage || this.isNoPhysics() || this.getY() <= this.level().getMinY()) && currentOwner != null) { if (!this.isAcceptableReturnOwner()) { if (this.level() instanceof ServerLevel level && this.pickup == AbstractArrow.Pickup.ALLOWED) { @@ -116,7 +117,7 @@ private boolean isAcceptableReturnOwner() { } public boolean isFoil() { - return this.entityData.get(ID_FOIL); + return this.entityData.get(ThrownHeavyHalberdEntity.ID_FOIL); } /// Gets the EntityHitResult representing the entity hit @@ -142,8 +143,7 @@ protected void onHitEntity(EntityHitResult result) { float damage = Mth.ceil(Mth.clamp(speed * baseDamage, 0.0, 2.147483647E9)); this.dealtDamage = true; - // noinspection deprecation - if (victim.hurtOrSimulate(source, damage)) { + if (EntityUtil.hurtOrSimulate(victim, source, damage)) { if (victim.getType() == EntityType.ENDERMAN) { return; } @@ -205,7 +205,7 @@ public void playerTouch(Player entity) { public void readAdditionalSaveData(ValueInput compound) { super.readAdditionalSaveData(compound); this.dealtDamage = compound.getBooleanOr("DealtDamage", false); - this.entityData.set(ID_LOYALTY, this.getLoyaltyFromItem(this.getPickupItemStackOrigin())); + this.entityData.set(ThrownHeavyHalberdEntity.ID_LOYALTY, this.getLoyaltyFromItem(this.getPickupItemStackOrigin())); } @Override @@ -222,7 +222,7 @@ private byte getLoyaltyFromItem(ItemStack stack) { @Override public void tickDespawn() { - int i = this.entityData.get(ID_LOYALTY); + int i = this.entityData.get(ThrownHeavyHalberdEntity.ID_LOYALTY); if (this.pickup != AbstractArrow.Pickup.ALLOWED || i <= 0) { super.tickDespawn(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/WeaponBeamEntity.java b/src/main/java/dev/dubhe/anvilcraft/entity/WeaponBeamEntity.java index 15f66b57b6..372753a32e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/WeaponBeamEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/WeaponBeamEntity.java @@ -39,11 +39,11 @@ public WeaponBeamEntity(EntityType type, Level level) { } public static WeaponBeamEntity create(Level level, Vec3 start, Vec3 end, int style) { - return create(level, start, end, style, 1, null); + return WeaponBeamEntity.create(level, start, end, style, 1, null); } public static WeaponBeamEntity create(Level level, Vec3 start, Vec3 end, int style, int strength) { - return create(level, start, end, style, strength, null); + return WeaponBeamEntity.create(level, start, end, style, strength, null); } public static WeaponBeamEntity create( @@ -73,7 +73,7 @@ public static void showContinuous( beam -> beam.getStyle() == style && beam.getOwnerId() == owner.getId() ); if (beams.isEmpty()) { - level.addFreshEntity(create(level, start, end, style, strength, owner)); + level.addFreshEntity(WeaponBeamEntity.create(level, start, end, style, strength, owner)); return; } @@ -86,24 +86,27 @@ private void refresh(Vec3 start, Vec3 end, int style, int strength, @Nullable En this.tickCount = 0; this.setPos(start); Vec3 offset = end.subtract(start); - this.entityData.set(END_X, (float) offset.x); - this.entityData.set(END_Y, (float) offset.y); - this.entityData.set(END_Z, (float) offset.z); - this.entityData.set(STYLE, style); - this.entityData.set(STRENGTH, strength); - this.entityData.set(OWNER_ID, owner == null ? -1 : owner.getId()); + this.entityData.set(WeaponBeamEntity.END_X, (float) offset.x); + this.entityData.set(WeaponBeamEntity.END_Y, (float) offset.y); + this.entityData.set(WeaponBeamEntity.END_Z, (float) offset.z); + this.entityData.set(WeaponBeamEntity.STYLE, style); + this.entityData.set(WeaponBeamEntity.STRENGTH, strength); + this.entityData.set(WeaponBeamEntity.OWNER_ID, owner == null ? -1 : owner.getId()); } public Vec3 getEndOffset() { - return new Vec3(this.entityData.get(END_X), this.entityData.get(END_Y), this.entityData.get(END_Z)); + return new Vec3( + this.entityData.get(WeaponBeamEntity.END_X), this.entityData.get(WeaponBeamEntity.END_Y), + this.entityData.get(WeaponBeamEntity.END_Z) + ); } public int getStyle() { - return this.entityData.get(STYLE); + return this.entityData.get(WeaponBeamEntity.STYLE); } public int getStrength() { - return this.entityData.get(STRENGTH); + return this.entityData.get(WeaponBeamEntity.STRENGTH); } public @Nullable Entity getOwner() { @@ -112,24 +115,24 @@ public int getStrength() { } public int getOwnerId() { - return this.entityData.get(OWNER_ID); + return this.entityData.get(WeaponBeamEntity.OWNER_ID); } @Override public void tick() { super.tick(); - if (this.level().isClientSide() && this.getStyle() != TESLA) return; - if (this.tickCount > (this.getStyle() == TESLA ? 5 : 2)) this.discard(); + if (this.level().isClientSide() && this.getStyle() != WeaponBeamEntity.TESLA) return; + if (this.tickCount > (this.getStyle() == WeaponBeamEntity.TESLA ? 5 : 2)) this.discard(); } @Override protected void defineSynchedData(SynchedEntityData.Builder builder) { - builder.define(END_X, 0.0F) - .define(END_Y, 0.0F) - .define(END_Z, 0.0F) - .define(STYLE, CORRUPTED) - .define(STRENGTH, 1) - .define(OWNER_ID, -1); + builder.define(WeaponBeamEntity.END_X, 0.0F) + .define(WeaponBeamEntity.END_Y, 0.0F) + .define(WeaponBeamEntity.END_Z, 0.0F) + .define(WeaponBeamEntity.STYLE, WeaponBeamEntity.CORRUPTED) + .define(WeaponBeamEntity.STRENGTH, 1) + .define(WeaponBeamEntity.OWNER_ID, -1); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/entity/ai/behavior/TradeAtStationBehavior.java b/src/main/java/dev/dubhe/anvilcraft/entity/ai/behavior/TradeAtStationBehavior.java index d39a7a02d9..ecb12b0ce2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/entity/ai/behavior/TradeAtStationBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/entity/ai/behavior/TradeAtStationBehavior.java @@ -16,6 +16,7 @@ import net.minecraft.world.entity.ai.village.poi.PoiType; import net.minecraft.world.entity.npc.villager.Villager; +import java.util.Comparator; import java.util.Optional; public class TradeAtStationBehavior extends Behavior { @@ -35,14 +36,15 @@ public TradeAtStationBehavior() { MemoryModuleType.LAST_WORKED_AT_POI, MemoryStatus.VALUE_PRESENT, MemoryModuleType.WALK_TARGET, MemoryStatus.REGISTERED, MemoryModuleType.LOOK_TARGET, MemoryStatus.REGISTERED - ), MAX_TICKS); + ), TradeAtStationBehavior.MAX_TICKS + ); } @Override protected boolean checkExtraStartConditions(ServerLevel level, Villager villager) { if (villager.getOffers().isEmpty()) return false; if (villager.isSleeping() || villager.isBaby()) return false; - BlockPos found = findMatchingStation(level, villager); + BlockPos found = TradeAtStationBehavior.findMatchingStation(level, villager); if (found == null) return false; this.stationPos = found; return true; @@ -54,14 +56,14 @@ protected void start(ServerLevel level, Villager villager, long gameTime) { this.failedAttempts = 0; Brain brain = villager.getBrain(); brain.setMemory(MemoryModuleType.LOOK_TARGET, new BlockPosTracker(this.stationPos)); - brain.setMemory(MemoryModuleType.WALK_TARGET, new WalkTarget(this.stationPos, SPEED_MODIFIER, 1)); + brain.setMemory(MemoryModuleType.WALK_TARGET, new WalkTarget(this.stationPos, TradeAtStationBehavior.SPEED_MODIFIER, 1)); } @Override protected boolean canStillUse(ServerLevel level, Villager villager, long gameTime) { if (this.stationPos == null) return false; if (this.failedAttempts >= 3) return false; - TradingStationBlockEntity be = getStation(level, this.stationPos); + TradingStationBlockEntity be = TradeAtStationBehavior.getStation(level, this.stationPos); if (be == null) return false; return be.canTradeWithVillager(villager); } @@ -70,10 +72,10 @@ protected boolean canStillUse(ServerLevel level, Villager villager, long gameTim protected void tick(ServerLevel level, Villager villager, long gameTime) { if (this.stationPos == null) return; double distSqr = villager.blockPosition().distSqr(this.stationPos); - if (distSqr > INTERACT_DISTANCE_SQR) { + if (distSqr > TradeAtStationBehavior.INTERACT_DISTANCE_SQR) { Brain brain = villager.getBrain(); if (brain.getMemory(MemoryModuleType.WALK_TARGET).isEmpty()) { - brain.setMemory(MemoryModuleType.WALK_TARGET, new WalkTarget(this.stationPos, SPEED_MODIFIER, 1)); + brain.setMemory(MemoryModuleType.WALK_TARGET, new WalkTarget(this.stationPos, TradeAtStationBehavior.SPEED_MODIFIER, 1)); } return; } @@ -83,18 +85,18 @@ protected void tick(ServerLevel level, Villager villager, long gameTime) { this.tradeCooldown--; return; } - TradingStationBlockEntity be = getStation(level, this.stationPos); + TradingStationBlockEntity be = TradeAtStationBehavior.getStation(level, this.stationPos); if (be == null) { this.failedAttempts = Integer.MAX_VALUE; return; } if (be.tryTradingWithVillager(villager)) { villager.playCelebrateSound(); - this.tradeCooldown = TRADE_INTERVAL_TICKS; + this.tradeCooldown = TradeAtStationBehavior.TRADE_INTERVAL_TICKS; this.failedAttempts = 0; } else { this.failedAttempts++; - this.tradeCooldown = TRADE_INTERVAL_TICKS; + this.tradeCooldown = TradeAtStationBehavior.TRADE_INTERVAL_TICKS; } } @@ -114,14 +116,14 @@ private static BlockPos findMatchingStation(ServerLevel level, Villager villager Optional match = poi.findAll( h -> h.value() == target, pos -> { - TradingStationBlockEntity be = getStation(level, pos); + TradingStationBlockEntity be = TradeAtStationBehavior.getStation(level, pos); return be != null && be.canTradeWithVillager(villager); }, villager.blockPosition(), - SEARCH_RADIUS, + TradeAtStationBehavior.SEARCH_RADIUS, PoiManager.Occupancy.ANY ) - .min(java.util.Comparator.comparingDouble(p -> p.distSqr(villager.blockPosition()))); + .min(Comparator.comparingDouble(p -> p.distSqr(villager.blockPosition()))); return match.orElse(null); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/BlockEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/BlockEventListener.java index 2f05d84a25..d860ca66ab 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/BlockEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/BlockEventListener.java @@ -40,7 +40,7 @@ public class BlockEventListener { private static final Map CREATIVE_CRATE_ATTACKS = new HashMap<>(); public static void clearCreativeCrateAttack(Player player, BlockPos pos) { - CREATIVE_CRATE_ATTACKS.remove(player.getUUID(), pos); + BlockEventListener.CREATIVE_CRATE_ATTACKS.remove(player.getUUID(), pos); } /// 侦听左键方块事件 @@ -65,7 +65,7 @@ public static void onCreativeCrateAttack(PlayerInteractEvent.LeftClickBlock even if (event.getLevel().isClientSide()) { return; } - clearCreativeCrateAttack(player, event.getPos()); + BlockEventListener.clearCreativeCrateAttack(player, event.getPos()); return; } if (!player.isCreative() && !crate.getDisplayStack().isEmpty()) { @@ -74,7 +74,7 @@ public static void onCreativeCrateAttack(PlayerInteractEvent.LeftClickBlock even } if (event.getAction() != PlayerInteractEvent.LeftClickBlock.Action.START) return; if (!player.isCreative()) { - BlockPos activePos = CREATIVE_CRATE_ATTACKS.get(player.getUUID()); + BlockPos activePos = BlockEventListener.CREATIVE_CRATE_ATTACKS.get(player.getUUID()); if (event.getPos().equals(activePos)) { event.setUseBlock(TriState.FALSE); event.setUseItem(TriState.FALSE); @@ -86,7 +86,7 @@ public static void onCreativeCrateAttack(PlayerInteractEvent.LeftClickBlock even event.setCanceled(true); } else { if (!event.getLevel().isClientSide()) { - CREATIVE_CRATE_ATTACKS.put(player.getUUID(), event.getPos().immutable()); + BlockEventListener.CREATIVE_CRATE_ATTACKS.put(player.getUUID(), event.getPos().immutable()); } event.setUseBlock(TriState.FALSE); event.setUseItem(TriState.FALSE); @@ -119,7 +119,7 @@ public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event) && targetState.is(BlockTags.ANVIL) && player.isShiftKeyDown() ) { - onAnvilFixed(level, stack, pos, targetState); + BlockEventListener.onAnvilFixed(level, stack, pos, targetState); event.setCancellationResult(InteractionResult.SUCCESS); event.setCanceled(true); } else if (targetState.getBlock() instanceof BaseBatchCraftingBlock target && player.isShiftKeyDown()) { diff --git a/src/main/java/dev/dubhe/anvilcraft/event/BreakBlockEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/BreakBlockEventListener.java index f14bd6d18b..6b544d50dc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/BreakBlockEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/BreakBlockEventListener.java @@ -26,7 +26,7 @@ public class BreakBlockEventListener { public static void preventInfiniteFluidTankBreak(BreakBlockEvent event) { if (!(event.getPlayer() instanceof ServerPlayer player)) return; BlockPos pos = event.getPos(); - ServerLevel level = (ServerLevel) player.level(); + ServerLevel level = player.level(); if (!InfiniteFluidTankBreakProtection.isProtected(level, pos)) return; if (TranscendenceResonatorItem.isResonanceMining(level, player, pos)) { InfiniteFluidTankBreakProtection.clear(player); diff --git a/src/main/java/dev/dubhe/anvilcraft/event/CauldronOutletEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/CauldronOutletEventListener.java index 8d7da80229..734615f7fe 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/CauldronOutletEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/CauldronOutletEventListener.java @@ -43,7 +43,7 @@ public static void onPlayerUseAnvilHammerOnCauldron(PlayerInteractEvent.RightCli } // 获取应该在哪个方向创建口 - Direction direction = getDirectionFromPlayerFacing(event.getFace(), player); + Direction direction = CauldronOutletEventListener.getDirectionFromPlayerFacing(event.getFace(), player); // 检查方向,不能在顶部生成 if (direction == Direction.UP) { @@ -53,29 +53,29 @@ public static void onPlayerUseAnvilHammerOnCauldron(PlayerInteractEvent.RightCli // 计算新口的位置,下方用专门的方法 Vec3 newPosition; if (direction == Direction.DOWN) { - newPosition = calculateMouthPositionForBottom(blockPos); + newPosition = CauldronOutletEventListener.calculateMouthPositionForBottom(blockPos); } else { - newPosition = calculateMouthPosition(blockPos, direction); + newPosition = CauldronOutletEventListener.calculateMouthPosition(blockPos, direction); } if (level.isClientSide()) return; // 检查该位置是否已有口,有就移除并播放音效 - CauldronOutletEntity existingMouth = findExistingCauldronMouthAtPosition(level, blockPos, newPosition); + CauldronOutletEntity existingMouth = CauldronOutletEventListener.findExistingCauldronMouthAtPosition(level, blockPos, newPosition); if (existingMouth != null) { existingMouth.discard(); - playOutletSound(level, blockPos); + CauldronOutletEventListener.playOutletSound(level, blockPos); return; } // 检查该炼药锅是否已有其他口并移除 - removeExistingCauldronMouth(level, blockPos); - removeOpposingOutlet(level, blockPos, direction); + CauldronOutletEventListener.removeExistingCauldronMouth(level, blockPos); + CauldronOutletEventListener.removeOpposingOutlet(level, blockPos, direction); // 创建炼药锅口实体,播放音效 CauldronOutletEntity cauldronMouthEntity = new CauldronOutletEntity(level, newPosition, blockPos, direction); level.addFreshEntity(cauldronMouthEntity); - playOutletSound(level, blockPos); + CauldronOutletEventListener.playOutletSound(level, blockPos); } private static void playOutletSound(Level level, BlockPos pos) { @@ -107,7 +107,7 @@ private static List getCauldronMouths(Level level, BlockPo } private static @Nullable CauldronOutletEntity findExistingCauldronMouthAtPosition(Level level, BlockPos cauldronPos, Vec3 position) { - List existingMouths = getCauldronMouths(level, cauldronPos); + List existingMouths = CauldronOutletEventListener.getCauldronMouths(level, cauldronPos); for (CauldronOutletEntity mouth : existingMouths) { if (mouth.position().distanceTo(position) < 0.1) { return mouth; @@ -117,7 +117,7 @@ private static List getCauldronMouths(Level level, BlockPo } private static void removeExistingCauldronMouth(Level level, BlockPos cauldronPos) { - List existingMouths = getCauldronMouths(level, cauldronPos); + List existingMouths = CauldronOutletEventListener.getCauldronMouths(level, cauldronPos); for (CauldronOutletEntity mouth : existingMouths) { mouth.discard(); } @@ -125,7 +125,7 @@ private static void removeExistingCauldronMouth(Level level, BlockPos cauldronPo private static void removeOpposingOutlet(Level level, BlockPos cauldronPos, Direction direction) { BlockPos targetPos = cauldronPos.relative(direction); - for (CauldronOutletEntity outlet : getCauldronMouths(level, targetPos)) { + for (CauldronOutletEntity outlet : CauldronOutletEventListener.getCauldronMouths(level, targetPos)) { if (outlet.getAttachedDirection() == direction.getOpposite()) outlet.discard(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/FallingBlockCollisionEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/FallingBlockCollisionEventListener.java index 4cb5a282c6..5f2c4bf7da 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/FallingBlockCollisionEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/FallingBlockCollisionEventListener.java @@ -45,8 +45,7 @@ public class FallingBlockCollisionEventListener { @SubscribeEvent public static void anvilCollisionCraft(AnvilEvent.CollisionBlock event) { if (event.isCanceled()) return; - Level level = event.getLevel(); - if (level.isClientSide()) return; + if (!(event.getLevel() instanceof ServerLevel level)) return; Vec3 entityPos = event.getEntity().position(); BlockPos pos = event.getPos(); if (AnvilCraft.CONFIG.anvilCollisionCraftSpeed > event.getSpeed()) return; @@ -65,12 +64,12 @@ public static void anvilCollisionCraft(AnvilEvent.CollisionBlock event) { resultRecipe = recipe; } if (resultRecipe != null) { - executeRecipe(event, resultRecipe, level, pos, entityPos); + FallingBlockCollisionEventListener.executeRecipe(event, resultRecipe, level, pos, entityPos); return; } if (event.getEntity().getBlockState().is(BlockTags.ANVIL)) { if (state.getDestroySpeed(level, pos) > 0) { - removeBlock(level, pos); + FallingBlockCollisionEventListener.removeBlock(level, pos); } level.explode( null, @@ -89,12 +88,11 @@ public static void anvilCollisionCraft(AnvilEvent.CollisionBlock event) { private static void executeRecipe( AnvilEvent.CollisionBlock event, RecipeHolder recipeHolder, - Level level, + ServerLevel level, BlockPos pos, Vec3 entityPos ) { - if (!(level instanceof ServerLevel serverLevel)) return; - removeBlock(level, pos); + FallingBlockCollisionEventListener.removeBlock(level, pos); AnvilCollisionCraftRecipe recipe = recipeHolder.value(); if (recipe.consume()) { event.getEntity().discard(); @@ -116,7 +114,7 @@ private static void executeRecipe( ? Explosion.BlockInteraction.DESTROY_WITH_DECAY : Explosion.BlockInteraction.DESTROY; ServerExplosion explosion = new ServerExplosion( - serverLevel, + level, null, damageSource, damageCalculator, @@ -128,7 +126,7 @@ private static void executeRecipe( explosion.anvilcraft$setBlockTransformExplosion(recipe.transformBlocks()); int blockCount = explosion.explode(); ParticleOptions explosionParticle = explosion.isSmall() ? smallExplosionParticles : largeExplosionParticles; - for (ServerPlayer serverplayer : serverLevel.players()) { + for (ServerPlayer serverplayer : level.players()) { if (serverplayer.distanceToSqr(x, y, z) < 4096.0) { Optional playerKnockback = Optional.ofNullable(explosion.getHitPlayers().get(serverplayer)); serverplayer.connection.send( @@ -147,7 +145,7 @@ private static void executeRecipe( ArrayList itemEntities = new ArrayList<>(); for (ChanceItemStack outputItem : recipe.outputItems()) { - ItemStack itemStack = outputItem.getResult(serverLevel).create(); + ItemStack itemStack = outputItem.getResult(level).create(); if (itemStack.isEmpty()) continue; itemEntities.add(itemStack); } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/GuideEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/GuideEventListener.java index 04e4bca09c..7371c5aae0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/GuideEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/GuideEventListener.java @@ -26,7 +26,7 @@ public static void onHasGuide(CheckIntegrationLoadedEvent event) { @SubscribeEvent(priority = EventPriority.HIGHEST) public static void onOpenGuide(GuideBookEvent.OpenGuideBookEvent event) { - Ageratum.openGuide(event.getPlayer(), AnvilCraft.of(INDEX_FILE)); + Ageratum.openGuide(event.getPlayer(), AnvilCraft.of(GuideEventListener.INDEX_FILE)); event.setCanceled(true); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/InWorldRecipeEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/InWorldRecipeEventListener.java index ee438c48cb..10f481cdc3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/InWorldRecipeEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/InWorldRecipeEventListener.java @@ -28,10 +28,10 @@ @EventBusSubscriber(modid = AnvilCraft.MOD_ID) public class InWorldRecipeEventListener { @SubscribeEvent + @SuppressWarnings("deprecation") public static void inWorldRecipe(InWorldRecipeManagerEvent.Init event) { RecipeManager manager = event.getRecipeManager(); List> init = VanillaRecipesWrap.init(manager.getRecipes()); - // noinspection deprecation new MeshRecipeGeneratingCache(manager.anvillib$getRegistries()) .buildRecipes() .ifPresent(recipeHolders -> { diff --git a/src/main/java/dev/dubhe/anvilcraft/event/PistonMoveBlockListener.java b/src/main/java/dev/dubhe/anvilcraft/event/PistonMoveBlockListener.java index 7881511499..045e5d0764 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/PistonMoveBlockListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/PistonMoveBlockListener.java @@ -20,9 +20,9 @@ public class PistonMoveBlockListener { private static final Map CHARGE_NUMS = new HashMap<>(); static { - CHARGE_NUMS.put(Blocks.COPPER_BLOCK, 1d / 4); - CHARGE_NUMS.put(Blocks.EXPOSED_COPPER, 1d / 8); - CHARGE_NUMS.put(Blocks.WEATHERED_COPPER, 1d / 16); + PistonMoveBlockListener.CHARGE_NUMS.put(Blocks.COPPER_BLOCK, 1d / 4); + PistonMoveBlockListener.CHARGE_NUMS.put(Blocks.EXPOSED_COPPER, 1d / 8); + PistonMoveBlockListener.CHARGE_NUMS.put(Blocks.WEATHERED_COPPER, 1d / 16); } /// 活塞移动方块 @@ -31,7 +31,7 @@ public static void onPistonMoveBlocks(Level level, List blocks) { BlockState blockState = level.getBlockState(pos); if (!(blockState.getBlock() instanceof MagnetBlock)) continue; if (blockState.getValue(MagnetBlock.LIT)) continue; - double n = getChargeNum(level, pos); + double n = PistonMoveBlockListener.getChargeNum(level, pos); if (n <= 0) { continue; } @@ -43,8 +43,8 @@ private static Double getChargeNum(Level level, BlockPos pos) { double max = 0d; for (Direction face : Direction.values()) { Block block = level.getBlockState(pos.relative(face)).getBlock(); - if (!CHARGE_NUMS.containsKey(block)) continue; - max = max < CHARGE_NUMS.get(block) ? CHARGE_NUMS.get(block) : max; + if (!PistonMoveBlockListener.CHARGE_NUMS.containsKey(block)) continue; + max = max < PistonMoveBlockListener.CHARGE_NUMS.get(block) ? PistonMoveBlockListener.CHARGE_NUMS.get(block) : max; } return max; } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/PlayerEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/PlayerEventListener.java index 73ec2961b7..ea19ac4920 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/PlayerEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/PlayerEventListener.java @@ -200,14 +200,14 @@ public static void onPlayerHurt(LivingIncomingDamageEvent event) { @SubscribeEvent(priority = EventPriority.LOWEST) public static void onPlayerBlockWithHeavyHalberd(LivingIncomingDamageEvent event) { if (!(event.getEntity() instanceof Player player)) return; - if (isBlockingWithHeavyHalberd(player) && event.getSource().is(Tags.DamageTypes.IS_PHYSICAL)) { + if (PlayerEventListener.isBlockingWithHeavyHalberd(player) && event.getSource().is(Tags.DamageTypes.IS_PHYSICAL)) { event.setAmount(event.getAmount() * 0.5F); } } @SubscribeEvent(priority = EventPriority.LOWEST) public static void onPlayerShieldBlock(LivingShieldBlockEvent event) { - if (!(event.getEntity() instanceof Player player) || !isBlockingWithHeavyHalberd(player)) return; + if (!(event.getEntity() instanceof Player player) || !PlayerEventListener.isBlockingWithHeavyHalberd(player)) return; // 剑模式沿用旧版剑格挡,不触发盾牌的全额减伤、耐久消耗和禁用逻辑。 event.setBlocked(false); } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/PlayerTickEventHandler.java b/src/main/java/dev/dubhe/anvilcraft/event/PlayerTickEventHandler.java index a6484537c6..8d403d33e3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/PlayerTickEventHandler.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/PlayerTickEventHandler.java @@ -57,9 +57,9 @@ public static void onPlayerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) { @SubscribeEvent public static void onPlayerTick(PlayerTickEvent.Post event) { if (event.getEntity() instanceof ServerPlayer serverPlayer) { - applyPowerGrid(serverPlayer); + PlayerTickEventHandler.applyPowerGrid(serverPlayer); IonoCraftBackpackItem.playerTick(serverPlayer); - handleCapacitorCharging(serverPlayer); + PlayerTickEventHandler.handleCapacitorCharging(serverPlayer); SpectralWeaponLauncherItem.playerTick(serverPlayer); Merciless.tick(serverPlayer); Ferocious.tick(serverPlayer); diff --git a/src/main/java/dev/dubhe/anvilcraft/event/PortalEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/PortalEventListener.java index 38e7a9e6f7..2dac59341b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/PortalEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/PortalEventListener.java @@ -42,7 +42,6 @@ private static void processBlockPortalConversionRecipe(ServerLevel level, Fallin if (recipeOp.isPresent()) result = recipeOp.get().value().getResults().getResult(level); if (result == null) return; entity.blockState = result.getKey(); - CompoundTag nbt = result.getValue(); - entity.blockData = nbt == null ? null : nbt.copy(); + entity.blockData = result.getValue().copy(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/ReloadEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/ReloadEventListener.java index 4d4149d8c7..6e31e32529 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/ReloadEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/ReloadEventListener.java @@ -4,6 +4,7 @@ import dev.dubhe.anvilcraft.recipe.anvil.outcome.RoyalPreferenceOutcome; import net.minecraft.resources.Identifier; import net.minecraft.server.MinecraftServer; +import net.minecraft.util.Unit; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.neoforge.event.AddServerReloadListenersEvent; @@ -23,7 +24,8 @@ public static void onServerReload(AddServerReloadListenersEvent event) { if (server != null && server.overworld() != null) { RoyalPreferenceOutcome.RoyalPreference.initRoyalPreference(server.overworld().getSeed()); } - return barrier.wait(null); + return barrier.wait(Unit.INSTANCE).thenAccept(ignored -> { + }); } ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/TooltipEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/TooltipEventListener.java index 32a8f8cb88..abb9e6f086 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/TooltipEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/TooltipEventListener.java @@ -3,6 +3,7 @@ import dev.dubhe.anvilcraft.AnvilCraft; import dev.dubhe.anvilcraft.api.event.AppendCustomHoverTextEvent; import dev.dubhe.anvilcraft.api.tooltip.ItemTooltipManager; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.init.item.ModComponents; import net.minecraft.ChatFormatting; import net.minecraft.core.component.DataComponentType; @@ -49,6 +50,9 @@ public static void onTooltip(AppendCustomHoverTextEvent event) { final boolean shift = flag.hasShiftDown(); ItemTooltipManager.addTooltip(stack, builder, flag); + if (stack.getItem() instanceof IItemTooltipProvider provider) { + provider.appendItemTooltip(stack, ctx, display, builder, flag); + } stack.addToTooltip( ModComponents.MERCILESS_ENCHANTMENTS, ctx, @@ -57,11 +61,19 @@ public static void onTooltip(AppendCustomHoverTextEvent event) { flag ); stack.addToTooltip(ModComponents.CAN_TAKE_OUT_AMMO, ctx, display, builder, flag); - stack.addUnitComponentToTooltip(ModComponents.FIRE_REFORGING, FIRE_REFORGING, display, builder); + stack.addUnitComponentToTooltip(ModComponents.FIRE_REFORGING, TooltipEventListener.FIRE_REFORGING, display, builder); stack.addToTooltip(ModComponents.MERCILESS, ctx, display, builder, flag); stack.addToTooltip(ModComponents.FEROCIOUS, ctx, display, builder, flag); stack.addToTooltip(ModComponents.ETERNAL, ctx, display, builder, flag); - TooltipEventListener.addShiftUnitTooltip(ModComponents.PROVIDENCE, PROVIDENCE, PROVIDENCE_SHIFT, stack, shift, display, builder); + TooltipEventListener.addShiftUnitTooltip( + ModComponents.PROVIDENCE, + TooltipEventListener.PROVIDENCE, + TooltipEventListener.PROVIDENCE_SHIFT, + stack, + shift, + display, + builder + ); stack.addToTooltip(ModComponents.MULTIPHASE, ctx, display, builder, flag); stack.addToTooltip(ModComponents.STORED_ENERGY, ctx, display, builder, flag); stack.addToTooltip(ModComponents.FLIGHT_TIME, ctx, display, builder, flag); diff --git a/src/main/java/dev/dubhe/anvilcraft/event/UseOnBlockEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/UseOnBlockEventListener.java index 6b424ecfb1..0a28b41dd7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/UseOnBlockEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/UseOnBlockEventListener.java @@ -3,6 +3,7 @@ import dev.dubhe.anvilcraft.util.ModEnchantmentHelper; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.ItemTags; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.UseOnContext; import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.fml.common.EventBusSubscriber; @@ -16,10 +17,12 @@ public static void onUseOnBlock(UseItemOnBlockEvent e) { UseOnContext context = e.getUseOnContext(); if (!context.getItemInHand().is(ItemTags.HOES)) return; if (context.getLevel().isClientSide()) return; + Player player = context.getPlayer(); + if (player == null) return; ModEnchantmentHelper.onUseOnBlock( (ServerLevel) context.getLevel(), context.getItemInHand(), - context.getPlayer(), + player, context.getHand().asEquipmentSlot(), context.getClickedPos().getCenter(), context.getLevel().getBlockState(context.getClickedPos()) diff --git a/src/main/java/dev/dubhe/anvilcraft/event/anvil/AnvilEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/anvil/AnvilEventListener.java index 0fd9737a64..33fe83e5af 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/anvil/AnvilEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/anvil/AnvilEventListener.java @@ -59,9 +59,9 @@ public class AnvilEventListener { /// @param event 铁砧落地事件 @SubscribeEvent public static void onLand(AnvilEvent.OnLand event) { - if (!behaviorRegistered) { + if (!AnvilEventListener.behaviorRegistered) { IAnvilBehavior.register(); - behaviorRegistered = true; + AnvilEventListener.behaviorRegistered = true; } ServerLevel level = event.getLevel(); BlockPos pos = event.getPos(); @@ -73,7 +73,7 @@ public static void onLand(AnvilEvent.OnLand event) { && hitBlockState.is(ModBlocks.LARGE_CAULDRON)) { LargeCauldronBlockEntity cauldron = LargeCauldronBlockEntity.getMain(level, hitBlockPos, hitBlockState); if (cauldron != null && cauldron.handleGiantAnvilImpact(event)) { - handleBehaviors(level, hitBlockPos, hitBlockState, event); + AnvilEventListener.handleBehaviors(level, hitBlockPos, hitBlockState, event); return; } } @@ -83,14 +83,14 @@ public static void onLand(AnvilEvent.OnLand event) { if (level.getBlockState(mainPartPos).is(multiPartBlock)) breakBlockPos = mainPartPos; } BlockState breakBlockState = level.getBlockState(breakBlockPos); - if (hasStonecutterBelow(level, breakBlockPos, breakBlockState)) { - brokeBlock(level, breakBlockPos, event); + if (AnvilEventListener.hasStonecutterBelow(level, breakBlockPos, breakBlockState)) { + AnvilEventListener.brokeBlock(level, breakBlockPos, event); return; } if (!ProceduralProcessStepManager.checkAnyMatches(event)) { - handleNeoAnvilRecipe(event); + AnvilEventListener.handleNeoAnvilRecipe(event); } - if (handleBehaviors(level, hitBlockPos, hitBlockState, event)) return; + if (AnvilEventListener.handleBehaviors(level, hitBlockPos, hitBlockState, event)) return; if (blockState.is(ModBlocks.NEOFORGE)) { if (event.getFallDistance() > 1) { if (level.getRandom().nextDouble() < 0.01) { @@ -137,7 +137,7 @@ public static void handleNeoAnvilRecipe(AnvilEvent.OnLand event) { private static boolean hasStonecutterBelow(Level level, BlockPos pos, BlockState state) { if (state.getBlock() instanceof AbstractMultiPartBlock multiPartBlock) { - return hasStonecutterBelowAnyPart(level, pos, state, multiPartBlock); + return AnvilEventListener.hasStonecutterBelowAnyPart(level, pos, state, multiPartBlock); } return level.getBlockState(pos.below()).is(Blocks.STONECUTTER); } @@ -158,10 +158,10 @@ private static

> boolean hasStonecutterBelowAnyPart( return false; } + @SuppressWarnings("deprecation") private static void brokeBlock(Level level, BlockPos pos, AnvilEvent.OnLand event) { if (!(level instanceof ServerLevel serverLevel)) return; BlockState state = level.getBlockState(pos); - // noinspection deprecation if (state.getBlock().getExplosionResistance() >= 1200.0) event.setAnvilDamage(true); if (state.getDestroySpeed(level, pos) < 0) return; diff --git a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/GiantAnvilLandingEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/GiantAnvilLandingEventListener.java index da2f990234..156c8fe7f6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/GiantAnvilLandingEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/GiantAnvilLandingEventListener.java @@ -63,7 +63,7 @@ public static void handleMultiblock(AnvilEvent.GiantOnLand event) { } else if (!centerState.is(Tags.Blocks.PLAYER_WORKSTATIONS_CRAFTING_TABLES)) { return; } - int size = findCraftingTableSize(landPos, level); + int size = GiantAnvilLandingEventListener.findCraftingTableSize(landPos, level); if (size < 3 || size > 15) return; BlockPos inputCorner = landPos.offset(-size / 2, -size, -size / 2); @@ -112,7 +112,7 @@ public static void handleMultiblock(AnvilEvent.GiantOnLand event) { BlockPos.MutableBlockPos mpos = new BlockPos.MutableBlockPos(); final Optional> entity = value.getModifySpawnerAction() .map(ModifySpawnerAction::fromPos) - .map(pos -> rotatePos(pos, size, rotation)) + .map(pos -> GiantAnvilLandingEventListener.rotatePos(pos, size, rotation)) .map(inputCorner::offset) .map(level::getBlockEntity) .filter(be -> be instanceof HasMobBlockEntity) @@ -127,8 +127,9 @@ public static void handleMultiblock(AnvilEvent.GiantOnLand event) { case CLOCKWISE_90 -> mpos.setWithOffset(inputCorner, size - 1 - z, y, x); default -> mpos.setWithOffset(inputCorner, x, y, z); } - // noinspection deprecation - BlockState newState = outputPattern.getPredicate(x, y, z).getDefaultState().rotate(rotation); + BlockState newState = outputPattern.getPredicate(x, y, z) + .getDefaultState() + .rotate(level, mpos, rotation); level.setBlock(mpos, newState, 18); } } @@ -181,7 +182,9 @@ public static void handleMultiblock(AnvilEvent.GiantOnLand event) { } ); entity.ifPresent(entityType -> { - BlockPos offset = rotatePos(value.getModifySpawnerAction().get().toPos(), size, rotation); + BlockPos offset = GiantAnvilLandingEventListener.rotatePos( + value.getModifySpawnerAction().get().toPos(), size, rotation + ); Optional.ofNullable(level.getBlockEntity(inputCorner.offset(offset))) .filter(be -> be instanceof Spawner) .ifPresent(be -> ((Spawner) be).setEntityId(entityType, level.getRandom())); @@ -191,7 +194,11 @@ public static void handleMultiblock(AnvilEvent.GiantOnLand event) { private static int findCraftingTableSize(BlockPos centerPos, Level level) { int maxSize = 0; - for (int size = MIN_MULTIBLOCK_SIZE; size <= MAX_MULTIBLOCK_SIZE; size += 2) { + for ( + int size = GiantAnvilLandingEventListener.MIN_MULTIBLOCK_SIZE; + size <= GiantAnvilLandingEventListener.MAX_MULTIBLOCK_SIZE; + size += 2 + ) { boolean flag = true; for (int x = -size / 2; x <= size / 2 && flag; x++) { for (int z = -size / 2; z <= size / 2 && flag; z++) { diff --git a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyMode.java b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyMode.java index 3700c114db..4112143910 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyMode.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyMode.java @@ -13,37 +13,37 @@ import java.util.List; public abstract class DestroyMode { - public static final DestroyMode NORMAL = createForEffect(BlockMiningEffect.NORMAL); - public static final DestroyMode SILK_TOUCH = createForEffect(BlockMiningEffect.SILK_TOUCH); - public static final DestroyMode AUTO_SMELTING = createForEffect(BlockMiningEffect.SMELTING); - public static final DestroyMode FORTUNE = createForEffect(BlockMiningEffect.FORTUNE_5); - public static final DestroyMode DISINTEGRATION = createForEffect(BlockMiningEffect.DISINTEGRATION); + public static final DestroyMode NORMAL = DestroyMode.createForEffect(BlockMiningEffect.NORMAL); + public static final DestroyMode SILK_TOUCH = DestroyMode.createForEffect(BlockMiningEffect.SILK_TOUCH); + public static final DestroyMode AUTO_SMELTING = DestroyMode.createForEffect(BlockMiningEffect.SMELTING); + public static final DestroyMode FORTUNE = DestroyMode.createForEffect(BlockMiningEffect.FORTUNE_5); + public static final DestroyMode DISINTEGRATION = DestroyMode.createForEffect(BlockMiningEffect.DISINTEGRATION); private static DestroyMode createForEffect(BlockMiningEffect effect) { return new DestroyMode() { @Override public List apply(BlockState state, BlockPos pos, ShockContext ctx) { - return applyEffect(state, pos, ctx, effect, null); + return DestroyMode.applyEffect(state, pos, ctx, effect, null); } @Override public List apply(BlockState state, BlockPos pos, ShockContext ctx, ItemStack baseTool) { - return applyEffect(state, pos, ctx, effect, baseTool); + return DestroyMode.applyEffect(state, pos, ctx, effect, baseTool); } }; } public static DestroyMode fromEffect(BlockMiningEffect effect) { - if (effect.equals(BlockMiningEffect.SILK_TOUCH)) return SILK_TOUCH; - if (effect.equals(BlockMiningEffect.DISINTEGRATION)) return DISINTEGRATION; - if (effect.equals(BlockMiningEffect.SMELTING)) return AUTO_SMELTING; - if (effect.equals(BlockMiningEffect.FORTUNE_5)) return FORTUNE; - return NORMAL; + if (effect.equals(BlockMiningEffect.SILK_TOUCH)) return DestroyMode.SILK_TOUCH; + if (effect.equals(BlockMiningEffect.DISINTEGRATION)) return DestroyMode.DISINTEGRATION; + if (effect.equals(BlockMiningEffect.SMELTING)) return DestroyMode.AUTO_SMELTING; + if (effect.equals(BlockMiningEffect.FORTUNE_5)) return DestroyMode.FORTUNE; + return DestroyMode.NORMAL; } /** 根据边框铁砧行为创建破坏模式,并保留其自定义掉落处理器。 */ public static DestroyMode fromAnvilBehavior(ShockAnvilBehavior behavior) { - return fromEffect(behavior.miningEffect()).withDropBehavior(behavior.dropBehavior()); + return DestroyMode.fromEffect(behavior.miningEffect()).withDropBehavior(behavior.dropBehavior()); } private final ShockDropBehavior dropBehavior; diff --git a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyType.java b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyType.java index ce6b7c6293..46239afc98 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyType.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/DestroyType.java @@ -34,16 +34,16 @@ public void accept(ShockContext context, List list, DestroyMode mode) for (BlockPos destroyLayer : list) { BlockState blockState = level.getBlockState(destroyLayer); if (blockState.isAir()) continue; - if (isFellingApplicableBlock(blockState)) { + if (this.isFellingApplicableBlock(blockState)) { BlockPos.breadthFirstTraversal( destroyLayer, - TRAVERSE_DEPTH, - VISIT_LIMIT, + DestroyType.TRAVERSE_DEPTH, + DestroyType.VISIT_LIMIT, Util::acceptDirections, it -> { if (it.getY() < destroyLayer.getY()) return BlockPos.TraversalNodeStatus.SKIP; BlockState state = level.getBlockState(it); - if (isFellingApplicableBlock(state)) { + if (this.isFellingApplicableBlock(state)) { List itemStack = mode.apply(state, it, context); level.setBlockAndUpdate(it, Blocks.AIR.defaultBlockState()); mode.dropItems(itemStack, it, context); @@ -56,7 +56,7 @@ public void accept(ShockContext context, List list, DestroyMode mode) } } - private static boolean isFellingApplicableBlock(BlockState blockState) { + private boolean isFellingApplicableBlock(BlockState blockState) { return (blockState.is(BlockTags.LEAVES) && !blockState.getValue(LeavesBlock.PERSISTENT)) || blockState.is(ModBlockTags.FELLING_APPLICABLE); } @@ -88,8 +88,8 @@ public void accept(ShockContext context, List list, DestroyMode mode) if (state.is(Blocks.COCOA) || state.is(BlockTags.JUNGLE_LOGS)) { BlockPos.breadthFirstTraversal( destroyLayer, - TRAVERSE_DEPTH, - VISIT_LIMIT, + DestroyType.TRAVERSE_DEPTH, + DestroyType.VISIT_LIMIT, Util::acceptDirections, it -> { if (it.getY() < destroyLayer.getY()) return BlockPos.TraversalNodeStatus.SKIP; @@ -150,8 +150,8 @@ public void accept(ShockContext context, List list, DestroyMode mode) if (found) { BlockPos.breadthFirstTraversal( destroyLayer, - TRAVERSE_DEPTH, - VISIT_LIMIT, + DestroyType.TRAVERSE_DEPTH, + DestroyType.VISIT_LIMIT, (it, c) -> c.accept(it.below()), it -> { if (it.getY() > pos.getY()) return BlockPos.TraversalNodeStatus.SKIP; @@ -173,7 +173,7 @@ public void accept(ShockContext context, List list, DestroyMode mode) } }; public static final DestroyType CLEANING = new DestroyType() { - public static final ItemStack TOOL = Items.SHEARS.getDefaultInstance(); + public final ItemStack tool = Items.SHEARS.getDefaultInstance(); @Override public void accept(ShockContext context, List list, DestroyMode mode) { @@ -186,7 +186,7 @@ public void accept(ShockContext context, List list, DestroyMode mode) if (state.is(Blocks.SNOW)) { drops = mode.apply(state, pos, context); } else { - drops = mode.apply(state, pos, context, TOOL); + drops = mode.apply(state, pos, context, this.tool); } mode.dropItems(drops, pos, context); diff --git a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/FakePlayerSupport.java b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/FakePlayerSupport.java index 131685494e..ef7f8648a3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/FakePlayerSupport.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/FakePlayerSupport.java @@ -22,13 +22,13 @@ public class FakePlayerSupport { private static final Map FAKE_PLAYERS = new HashMap<>(); public static FakePlayer get(ServerLevel level) { - return FAKE_PLAYERS.computeIfAbsent(level, key -> FakePlayerFactory.get(key, GAME_PROFILE)); + return FakePlayerSupport.FAKE_PLAYERS.computeIfAbsent(level, key -> FakePlayerFactory.get(key, FakePlayerSupport.GAME_PROFILE)); } @SubscribeEvent public static void onLevelUnload(LevelEvent.Unload event) { if (event.getLevel() instanceof ServerLevel level) { - FAKE_PLAYERS.remove(level); + FakePlayerSupport.FAKE_PLAYERS.remove(level); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/GiantAnvilShockEventListener.java b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/GiantAnvilShockEventListener.java index 9d47e3ec7c..d519a227f7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/GiantAnvilShockEventListener.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/GiantAnvilShockEventListener.java @@ -11,8 +11,11 @@ import dev.dubhe.anvilcraft.init.block.ModBlocks; import dev.dubhe.anvilcraft.init.entity.ModDamageTypes; import dev.dubhe.anvilcraft.network.GiantAnvilShockEffectPacket; +import dev.dubhe.anvilcraft.network.ScreenShakePacket; +import dev.dubhe.anvilcraft.util.EntityUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.server.TickTask; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundSource; import net.minecraft.tags.BlockTags; @@ -53,9 +56,9 @@ public class GiantAnvilShockEventListener { ).then( // break mode TreeNode.executes(it -> { - if (it.has(DESTROY_MODE) && it.has(DESTROY_TYPE)) { - DestroyMode mode = it.getAttachment(DESTROY_MODE, DestroyMode.class); - DestroyType type = it.getAttachment(DESTROY_TYPE, DestroyType.class); + if (it.has(GiantAnvilShockEventListener.DESTROY_MODE) && it.has(GiantAnvilShockEventListener.DESTROY_TYPE)) { + DestroyMode mode = it.getAttachment(GiantAnvilShockEventListener.DESTROY_MODE, DestroyMode.class); + DestroyType type = it.getAttachment(GiantAnvilShockEventListener.DESTROY_TYPE, DestroyType.class); type.accept(it.unwrap(), it.unwrap().rangePosList(), mode); } }).then( @@ -64,28 +67,28 @@ public class GiantAnvilShockEventListener { it -> it.unwrap().getBorderAnvilBehavior().isPresent() ).executes(it -> { ShockAnvilBehavior behavior = it.unwrap().getBorderAnvilBehavior().orElseThrow(); - it.putAttachment(DESTROY_MODE, DestroyMode.fromAnvilBehavior(behavior)); + it.putAttachment(GiantAnvilShockEventListener.DESTROY_MODE, DestroyMode.fromAnvilBehavior(behavior)); }) ).then( // test block type TreeNode.multiple( TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(BlockTags.LOGS) - ).executes(it -> it.putAttachment(DESTROY_TYPE, DestroyType.FELLING)), + ).executes(it -> it.putAttachment(GiantAnvilShockEventListener.DESTROY_TYPE, DestroyType.FELLING)), TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(Blocks.HAY_BLOCK) - ).executes(it -> it.putAttachment(DESTROY_TYPE, DestroyType.HARVESTING)), + ).executes(it -> it.putAttachment(GiantAnvilShockEventListener.DESTROY_TYPE, DestroyType.HARVESTING)), TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(Blocks.GRASS_BLOCK) || it.unwrap().testCorner(Blocks.MYCELIUM) || it.unwrap().testCorner(Blocks.PODZOL) - ).executes(it -> it.putAttachment(DESTROY_TYPE, DestroyType.CLEANING)), + ).executes(it -> it.putAttachment(GiantAnvilShockEventListener.DESTROY_TYPE, DestroyType.CLEANING)), TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(Blocks.OBSIDIAN) - ).executes(it -> it.putAttachment(DESTROY_TYPE, DestroyType.GENERAL)), + ).executes(it -> it.putAttachment(GiantAnvilShockEventListener.DESTROY_TYPE, DestroyType.GENERAL)), TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(Blocks.AMETHYST_BLOCK) - ).executes(it -> it.putAttachment(DESTROY_TYPE, DestroyType.BROKEN_CRYSTALS)) + ).executes(it -> it.putAttachment(GiantAnvilShockEventListener.DESTROY_TYPE, DestroyType.BROKEN_CRYSTALS)) ) ) ).then( @@ -94,16 +97,16 @@ public class GiantAnvilShockEventListener { it -> it.unwrap().testBorder(ModBlocks.CURSED_GOLD_BLOCK) ).then( TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(ModBlocks.RUBY_BLOCK)) - .executes(it -> it.putAttachment(HURT_TYPE, HurtType.FIRE)) + .executes(it -> it.putAttachment(GiantAnvilShockEventListener.HURT_TYPE, HurtType.FIRE)) ).then( TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(ModBlocks.SAPPHIRE_BLOCK)) - .executes(it -> it.putAttachment(HURT_TYPE, HurtType.FROZEN)) + .executes(it -> it.putAttachment(GiantAnvilShockEventListener.HURT_TYPE, HurtType.FROZEN)) ).then( TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(ModBlocks.TOPAZ_BLOCK)) - .executes(it -> it.putAttachment(HURT_TYPE, HurtType.SHOCK)) + .executes(it -> it.putAttachment(GiantAnvilShockEventListener.HURT_TYPE, HurtType.SHOCK)) ).then( TreeNode.predicatedExecutable(it -> it.unwrap().testCorner(ModBlocks.VOID_MATTER_BLOCK)) - .executes(it -> it.putAttachment(HURT_TYPE, HurtType.VOID)) + .executes(it -> it.putAttachment(GiantAnvilShockEventListener.HURT_TYPE, HurtType.VOID)) ) ).then( TreeNode.predicatedExecutable(it -> @@ -169,7 +172,7 @@ public class GiantAnvilShockEventListener { // 下车后延迟弹起,等待客户端同步位置 if (level instanceof ServerLevel sl) { final double finalSpeed = upwardSpeed; - sl.getServer().schedule(new net.minecraft.server.TickTask( + sl.getServer().schedule(new TickTask( sl.getServer().getTickCount() + 4, () -> { if (living.isAlive()) { @@ -184,10 +187,10 @@ public class GiantAnvilShockEventListener { living.hurtMarked = true; } } - it.putAttachment(NO_HURT, true); + it.putAttachment(GiantAnvilShockEventListener.NO_HURT, true); }) ).executes(it -> { - if (it.has(NO_HURT)) return; + if (it.has(GiantAnvilShockEventListener.NO_HURT)) return; int radius = (int) Math.min(Math.ceil(it.unwrap().fallDistance()), AnvilCraft.CONFIG.giantAnvilMaxShockRadius); AABB aabb = AABB.ofSize( Vec3.atCenterOf(it.unwrap().centerPos().above()), @@ -198,13 +201,14 @@ public class GiantAnvilShockEventListener { Level level = it.unwrap().level(); List e = level.getEntitiesOfClass(LivingEntity.class, aabb); for (LivingEntity l : e) { - if (it.has(HURT_TYPE)) { - HurtType hurtType = it.getAttachment(HURT_TYPE, HurtType.class); - l.hurt(hurtType.damageSource(l.level()), it.unwrap().fallDistance() * 2 * 2); + if (it.has(GiantAnvilShockEventListener.HURT_TYPE)) { + HurtType hurtType = it.getAttachment(GiantAnvilShockEventListener.HURT_TYPE, HurtType.class); + EntityUtil.hurt(l, hurtType.damageSource(l.level()), it.unwrap().fallDistance() * 2 * 2); hurtType.postApply(l.level(), l, it.unwrap().fallDistance()); } else { if (l.getItemBySlot(EquipmentSlot.FEET).is(Items.AIR)) { - l.hurt( + EntityUtil.hurt( + l, ModDamageTypes.fallingGiantAnvil(it.unwrap().level(), it.unwrap().fallingGiantAnvil()), it.unwrap().fallDistance() * 2 ); @@ -218,7 +222,7 @@ public class GiantAnvilShockEventListener { @SubscribeEvent public static void onLand(AnvilEvent.GiantOnLand event) { ShockContext context = ShockContext.inflate(event); - behaviorTree.run(context); + GiantAnvilShockEventListener.behaviorTree.run(context); // 仅当冲击机制实际触发(中心为重型铁块)时才生成撼地效果 if (event.getLevel() .getBlockState(event.getPos().below(2)) @@ -238,10 +242,10 @@ public static void onLand(AnvilEvent.GiantOnLand event) { PacketDistributor.sendToPlayersTrackingChunk( serverLevel, ChunkPos.containing(event.getPos()), - dev.dubhe.anvilcraft.network.ScreenShakePacket.of( + ScreenShakePacket.of( Vec3.atCenterOf(shockCenter), radius, - dev.dubhe.anvilcraft.network.ScreenShakePacket.ShakeType.GIANT_ANVIL_SHOCK + ScreenShakePacket.ShakeType.GIANT_ANVIL_SHOCK ) ); } @@ -257,7 +261,7 @@ public static void onLand(AnvilEvent.GiantOnLand event) { event.getLevel().playSound(null, event.getPos(), ModSoundEvents.GIANT_ANVIL_SHOCK.get(), SoundSource.BLOCKS, 1.8f, 1.2f + event.getLevel().getRandom().nextFloat() * 0.2f); } - spawnGroundHeave(event); + GiantAnvilShockEventListener.spawnGroundHeave(event); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/ShockContext.java b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/ShockContext.java index 9114d2ae01..b306a5fdf5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/ShockContext.java +++ b/src/main/java/dev/dubhe/anvilcraft/event/giantanvil/shock/ShockContext.java @@ -58,8 +58,8 @@ public static ShockContext inflate(AnvilEvent.GiantOnLand event) { } public boolean testCorner(TagKey tagKey) { - for (Direction direction1 : HORIZONTAL_X) { - for (Direction direction2 : HORIZONTAL_Z) { + for (Direction direction1 : ShockContext.HORIZONTAL_X) { + for (Direction direction2 : ShockContext.HORIZONTAL_Z) { if (!this.matchesShockBase(this.centerPos.relative(direction1).relative(direction2), tagKey)) { return false; } @@ -73,8 +73,8 @@ public boolean testCorner(Holder block) { } public boolean testCorner(Block block) { - for (Direction direction1 : HORIZONTAL_X) { - for (Direction direction2 : HORIZONTAL_Z) { + for (Direction direction1 : ShockContext.HORIZONTAL_X) { + for (Direction direction2 : ShockContext.HORIZONTAL_Z) { if (!this.matchesShockBase(this.centerPos.relative(direction1).relative(direction2), block)) { return false; } @@ -88,7 +88,7 @@ public boolean testBorder(Holder block) { } public boolean testBorder(TagKey tagKey) { - for (Direction direction : HORIZONTAL) { + for (Direction direction : ShockContext.HORIZONTAL) { if (!this.matchesShockBase(this.centerPos.relative(direction), tagKey)) { return false; } @@ -97,7 +97,7 @@ public boolean testBorder(TagKey tagKey) { } public boolean testBorder(Block block) { - for (Direction direction : HORIZONTAL) { + for (Direction direction : ShockContext.HORIZONTAL) { if (!this.matchesShockBase(this.centerPos.relative(direction), block)) { return false; } @@ -106,7 +106,7 @@ public boolean testBorder(Block block) { } public boolean testBorder(Class block) { - for (Direction direction : HORIZONTAL) { + for (Direction direction : ShockContext.HORIZONTAL) { BlockPos pos = this.centerPos.relative(direction); if (block.isInstance(this.level.getBlockState(pos).getBlock())) continue; boolean entityMatches = this.shockEntitiesAt(pos).stream() @@ -127,7 +127,7 @@ public Optional getBorderMiningEffect() { /** 返回四个边框铁砧共同提供的完整撼地行为。 */ public Optional getBorderAnvilBehavior() { ShockAnvilBehavior behavior = null; - for (Direction direction : HORIZONTAL) { + for (Direction direction : ShockContext.HORIZONTAL) { Optional current = this.getAnvilBehaviorAt(this.centerPos.relative(direction)); if (current.isEmpty()) return Optional.empty(); if (behavior == null) { @@ -174,7 +174,7 @@ public int getShockRadius() { /** 按目标高度倍率计算与本体方块铁砧一致重力下的弹起速度。 */ public static double bounceVelocityForHeight(double heightMultiplier) { if (!Double.isFinite(heightMultiplier) || heightMultiplier <= 0.0D) return 0.0D; - return DEFAULT_BOUNCE_VELOCITY * Math.sqrt(heightMultiplier); + return ShockContext.DEFAULT_BOUNCE_VELOCITY * Math.sqrt(heightMultiplier); } private Optional getAnvilBehaviorAt(BlockPos pos) { diff --git a/src/main/java/dev/dubhe/anvilcraft/fluid/LiquidEnchantmentFluid.java b/src/main/java/dev/dubhe/anvilcraft/fluid/LiquidEnchantmentFluid.java index 082b527458..3b4d41bed1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/fluid/LiquidEnchantmentFluid.java +++ b/src/main/java/dev/dubhe/anvilcraft/fluid/LiquidEnchantmentFluid.java @@ -96,6 +96,6 @@ public VoxelShape getShape(FluidState state, BlockGetter level, BlockPos pos) { @Override public FluidType getFluidType() { - return TYPE; + return LiquidEnchantmentFluid.TYPE; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModAttachments.java b/src/main/java/dev/dubhe/anvilcraft/init/ModAttachments.java index 532936a057..6a03542ed3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModAttachments.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModAttachments.java @@ -14,11 +14,11 @@ public class ModAttachments { NeoForgeRegistries.ATTACHMENT_TYPES, AnvilCraft.MOD_ID ); - public static final Supplier> DFU = ATTACHMENT_TYPES.register( + public static final Supplier> DFU = ModAttachments.ATTACHMENT_TYPES.register( "dfu_metadata", () -> AttachmentType.builder(() -> DfuMetadata.DEFAULT).serialize(DfuMetadata.CODEC.fieldOf("value")).build() ); public static void register(IEventBus eventBus) { - ATTACHMENT_TYPES.register(eventBus); + ModAttachments.ATTACHMENT_TYPES.register(eventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModBuiltinPacks.java b/src/main/java/dev/dubhe/anvilcraft/init/ModBuiltinPacks.java index 36654b62a7..ace1f8b934 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModBuiltinPacks.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModBuiltinPacks.java @@ -14,7 +14,7 @@ @EventBusSubscriber(modid = AnvilCraft.MOD_ID) public class ModBuiltinPacks { - public static final PackSource BUILT_IN = PackSource.create(decorateWithSource("pack.result.builtin"), false); + public static final PackSource BUILT_IN = PackSource.create(ModBuiltinPacks.decorateWithSource("pack.result.builtin"), false); @SubscribeEvent public static void packSetup(AddPackFindersEvent event) { diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModColorHandlers.java b/src/main/java/dev/dubhe/anvilcraft/init/ModColorHandlers.java index 3cf0a1a3f6..c0031ccbe8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModColorHandlers.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModColorHandlers.java @@ -36,7 +36,7 @@ public static void registerBlockColorHandlersEvent(RegisterColorHandlersEvent.Bl @SubscribeEvent public static void registerItemColorHandlersEvent(RegisterColorHandlersEvent.ItemTintSources event) { - event.register(PILL, Pill.MAP_CODEC); + event.register(ModColorHandlers.PILL, Pill.MAP_CODEC); } /// 复用原版红石粉的强度到颜色映射,功率取自 [RedstoneWireClientPowerCache] @@ -67,7 +67,7 @@ public int calculate(ItemStack itemStack, @Nullable ClientLevel level, @Nullable @Override public MapCodec type() { - return MAP_CODEC; + return Pill.MAP_CODEC; } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModCriterionTriggers.java b/src/main/java/dev/dubhe/anvilcraft/init/ModCriterionTriggers.java index f386d9bae3..82bc8438a2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModCriterionTriggers.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModCriterionTriggers.java @@ -35,118 +35,131 @@ public class ModCriterionTriggers { private static final DeferredRegister> REGISTER = DeferredRegister.create(Registries.TRIGGER_TYPE, AnvilCraft.MOD_ID); - public static final DeferredHolder, PlacerPlaceTrigger> PLACER_PLACE_BLOCK = REGISTER.register( + public static final DeferredHolder, PlacerPlaceTrigger> PLACER_PLACE_BLOCK = ModCriterionTriggers.REGISTER.register( "placer_place_block", PlacerPlaceTrigger::new ); - public static final DeferredHolder, PlacerShuttleTrigger> PLACER_SHUTTLE = REGISTER.register( + public static final DeferredHolder, PlacerShuttleTrigger> PLACER_SHUTTLE = ModCriterionTriggers.REGISTER.register( "placer_shuttle", PlacerShuttleTrigger::new ); - public static final DeferredHolder, DevourerDevourTrigger> DEVOURER_DEVOUR_BLOCK = REGISTER.register( + public static final DeferredHolder, DevourerDevourTrigger> DEVOURER_DEVOUR_BLOCK = + ModCriterionTriggers.REGISTER.register( "devourer_devour_block", DevourerDevourTrigger::new ); - public static final DeferredHolder, MagnetLiftingAnvilTrigger> LIFTING_ANVIL = REGISTER.register( + public static final DeferredHolder, MagnetLiftingAnvilTrigger> LIFTING_ANVIL = + ModCriterionTriggers.REGISTER.register( "lifting_anvil", MagnetLiftingAnvilTrigger::new ); - public static final DeferredHolder, AnvilOnGroundTrigger> ANVIL_ON_GROUND = REGISTER.register( + public static final DeferredHolder, AnvilOnGroundTrigger> ANVIL_ON_GROUND = ModCriterionTriggers.REGISTER.register( "anvil_on_ground", AnvilOnGroundTrigger::new ); - public static final DeferredHolder, MilkTrigger> MILK = REGISTER.register("milk", MilkTrigger::new); + public static final DeferredHolder, MilkTrigger> MILK = + ModCriterionTriggers.REGISTER.register("milk", MilkTrigger::new); - public static final DeferredHolder, AnvilLootingTrigger> ANVIL_LOOTING = REGISTER.register( + public static final DeferredHolder, AnvilLootingTrigger> ANVIL_LOOTING = ModCriterionTriggers.REGISTER.register( "anvil_looting", AnvilLootingTrigger::new ); - public static final DeferredHolder, DispenserRepairIronGolem> REPAIR_IRON_GOLEM = REGISTER.register( + public static final DeferredHolder, DispenserRepairIronGolem> REPAIR_IRON_GOLEM = + ModCriterionTriggers.REGISTER.register( "repair_iron_golem", DispenserRepairIronGolem::new ); - public static final DeferredHolder, InWorldRecipeTrigger> IN_WORLD_RECIPE = REGISTER.register( + public static final DeferredHolder, InWorldRecipeTrigger> IN_WORLD_RECIPE = ModCriterionTriggers.REGISTER.register( "in_world_recipe", InWorldRecipeTrigger::new ); - public static final DeferredHolder, AnvilHammerClickBlockTrigger> ANVIL_HAMMER_CLICK_BLOCK = REGISTER.register( + public static final DeferredHolder, AnvilHammerClickBlockTrigger> ANVIL_HAMMER_CLICK_BLOCK = + ModCriterionTriggers.REGISTER.register( "anvil_hammer_click_block", AnvilHammerClickBlockTrigger::new ); - public static final DeferredHolder, AnvilHammerChangeBlockTrigger> ANVIL_HAMMER_CHANGE_BLOCK = REGISTER.register( + public static final DeferredHolder, AnvilHammerChangeBlockTrigger> ANVIL_HAMMER_CHANGE_BLOCK = + ModCriterionTriggers.REGISTER.register( "anvil_hammer_change_block", AnvilHammerChangeBlockTrigger::new ); - public static final DeferredHolder, AnvilHammerHurtEntityTrigger> ANVIL_HAMMER_HURT_ENTITY = REGISTER.register( + public static final DeferredHolder, AnvilHammerHurtEntityTrigger> ANVIL_HAMMER_HURT_ENTITY = + ModCriterionTriggers.REGISTER.register( "anvil_hammer_hurt_entity", AnvilHammerHurtEntityTrigger::new ); public static final DeferredHolder, PlayerKilledEntityByAnvilHammerTrigger> PLAYER_KILLED_ENTITY_BY_ANVIL_HAMMER = - REGISTER.register("player_killed_entity_by_anvil_hammer", PlayerKilledEntityByAnvilHammerTrigger::new); + ModCriterionTriggers.REGISTER.register("player_killed_entity_by_anvil_hammer", PlayerKilledEntityByAnvilHammerTrigger::new); public static final DeferredHolder, AnvilHitPiezoelectricCrystalTrigger> ANVIL_HIT_PIEZOELECTRIC_CRYSTAL = - REGISTER.register("anvil_hit_piezoelectric_crystal", AnvilHitPiezoelectricCrystalTrigger::new); + ModCriterionTriggers.REGISTER.register("anvil_hit_piezoelectric_crystal", AnvilHitPiezoelectricCrystalTrigger::new); - public static final DeferredHolder, EnterPowerGridTrigger> ENTER_POWER_GRID = REGISTER.register( + public static final DeferredHolder, EnterPowerGridTrigger> ENTER_POWER_GRID = + ModCriterionTriggers.REGISTER.register( "enter_power_grid", EnterPowerGridTrigger::new ); - public static final DeferredHolder, ConvertBeaconTrigger> CONVERT_BEACON = REGISTER.register( + public static final DeferredHolder, ConvertBeaconTrigger> CONVERT_BEACON = ModCriterionTriggers.REGISTER.register( "convert_beacon", ConvertBeaconTrigger::new ); - public static final DeferredHolder, FireReforgeTrigger> FIRE_REFORGE = REGISTER.register( + public static final DeferredHolder, FireReforgeTrigger> FIRE_REFORGE = ModCriterionTriggers.REGISTER.register( "fire_reforge", FireReforgeTrigger::new ); - public static final DeferredHolder, ElectricAllergyTrigger> ELECTRIC_ALLERGY = REGISTER.register( + public static final DeferredHolder, ElectricAllergyTrigger> ELECTRIC_ALLERGY = + ModCriterionTriggers.REGISTER.register( "electric_allergy", ElectricAllergyTrigger::new ); - public static final DeferredHolder, ConnectFluidContainersTrigger> CONNECT_FLUID_CONTAINERS = REGISTER.register( + public static final DeferredHolder, ConnectFluidContainersTrigger> CONNECT_FLUID_CONTAINERS = + ModCriterionTriggers.REGISTER.register( "connect_fluid_containers", ConnectFluidContainersTrigger::new ); - public static final DeferredHolder, HeatCollectorTrigger> HEAT_COLLECTOR_COLLECT = REGISTER.register( + public static final DeferredHolder, HeatCollectorTrigger> HEAT_COLLECTOR_COLLECT = + ModCriterionTriggers.REGISTER.register( "heat_collector_collect", HeatCollectorTrigger::new ); - public static final DeferredHolder, VoidCollectorTrigger> VOID_COLLECTOR_COLLECT = REGISTER.register( + public static final DeferredHolder, VoidCollectorTrigger> VOID_COLLECTOR_COLLECT = + ModCriterionTriggers.REGISTER.register( "void_collector_collect", VoidCollectorTrigger::new ); - public static final DeferredHolder, MineralFountainCreateTrigger> MINERAL_FOUNTAIN_CREATE = REGISTER.register( + public static final DeferredHolder, MineralFountainCreateTrigger> MINERAL_FOUNTAIN_CREATE = + ModCriterionTriggers.REGISTER.register( "mineral_fountain_crate", MineralFountainCreateTrigger::new ); - public static final DeferredHolder, UseItemTrigger> USE_ITEM = REGISTER.register( + public static final DeferredHolder, UseItemTrigger> USE_ITEM = ModCriterionTriggers.REGISTER.register( "use_item", UseItemTrigger::new ); public static final DeferredHolder, BlockComparatorTurnOverTrigger> BLOCK_COMPARATOR_TURN_OVER = - REGISTER.register("block_comparator_turn_over", BlockComparatorTurnOverTrigger::new); + ModCriterionTriggers.REGISTER.register("block_comparator_turn_over", BlockComparatorTurnOverTrigger::new); public static void register(IEventBus eventBus) { - REGISTER.register(eventBus); + ModCriterionTriggers.REGISTER.register(eventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModDataAttachments.java b/src/main/java/dev/dubhe/anvilcraft/init/ModDataAttachments.java index 13e323a9c2..417ee9a7ad 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModDataAttachments.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModDataAttachments.java @@ -15,7 +15,8 @@ public class ModDataAttachments { private static final DeferredRegister> ATTACHMENT_TYPES = DeferredRegister.create(NeoForgeRegistries.ATTACHMENT_TYPES, AnvilCraft.MOD_ID); - public static final Supplier> AMULET_RAFFLE_PROBABILITY = ATTACHMENT_TYPES.register( + public static final Supplier> AMULET_RAFFLE_PROBABILITY = + ModDataAttachments.ATTACHMENT_TYPES.register( "amulet_raffle_probability", () -> AttachmentType.builder(() -> AmuletRaffleProbability.EMPTY) .serialize(AmuletRaffleProbability.CODEC) @@ -23,7 +24,7 @@ public class ModDataAttachments { .build() ); - public static final Supplier> ZOMBIFICATED_BY_CURSE = ATTACHMENT_TYPES.register( + public static final Supplier> ZOMBIFICATED_BY_CURSE = ModDataAttachments.ATTACHMENT_TYPES.register( "zombificated_by_curse", () -> AttachmentType.builder(() -> false) .serialize(Codec.BOOL.fieldOf("zombificated_by_curse")) @@ -31,7 +32,7 @@ public class ModDataAttachments { ); public static final Supplier> SMITHING_TEMPLATE_FAVORITES = - ATTACHMENT_TYPES.register( + ModDataAttachments.ATTACHMENT_TYPES.register( "smithing_template_favorites", () -> AttachmentType.builder(() -> SmithingTemplateFavorites.EMPTY) .serialize(SmithingTemplateFavorites.CODEC) @@ -40,6 +41,6 @@ public class ModDataAttachments { ); public static void register(IEventBus eventBus) { - ATTACHMENT_TYPES.register(eventBus); + ModDataAttachments.ATTACHMENT_TYPES.register(eventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModDispenserBehavior.java b/src/main/java/dev/dubhe/anvilcraft/init/ModDispenserBehavior.java index 31b4cb0077..18e49ae381 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModDispenserBehavior.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModDispenserBehavior.java @@ -2,6 +2,7 @@ import dev.anvilcraft.lib.v2.registrum.util.entry.ItemEntry; import dev.dubhe.anvilcraft.block.storage.MagnetBlock; +import dev.dubhe.anvilcraft.fluid.HoneyFluid; import dev.dubhe.anvilcraft.init.block.ModBlocks; import dev.dubhe.anvilcraft.init.item.ModItems; import dev.dubhe.anvilcraft.item.block.HasMobBlockItem; @@ -74,7 +75,7 @@ public ItemStack execute(BlockSource source, ItemStack stack) { int filled = target.insert(resource, available, transaction); if (filled < available) continue; transaction.commit(); - return this.consumeWithRemainder(source, stack, emptyContainerFor(stack)); + return this.consumeWithRemainder(source, stack, ModDispenserBehavior.emptyContainerFor(stack)); } } } @@ -108,7 +109,7 @@ public ItemStack execute(BlockSource source, ItemStack stack) { int drained = target.extract(i, resource, amount, transaction); if (drained < amount) continue; ItemStack result; - if (isBottle && resource.getFluid() instanceof dev.dubhe.anvilcraft.fluid.HoneyFluid) { + if (isBottle && resource.getFluid() instanceof HoneyFluid) { result = new ItemStack(Items.HONEY_BOTTLE); } else if (!isBottle && resource.getFluid().getBucket() != Items.AIR) { result = new ItemStack(resource.getFluid().getBucket()); @@ -144,13 +145,13 @@ public static void register() { DispenserBlock.registerBehavior(Items.BOWL, ModDispenserBehavior::bowl); DispenserBlock.registerBehavior(Items.GOLDEN_APPLE, ModDispenserBehavior::goldenApple); DispenserBlock.registerBehavior(ModBlocks.RESIN_BLOCK, ModDispenserBehavior::resinBlock); - DispenserBlock.registerBehavior(Items.MILK_BUCKET, FLUID_BUCKET); - DispenserBlock.registerBehavior(Items.HONEY_BOTTLE, FLUID_BUCKET); - DispenserBlock.registerBehavior(ModItems.OIL_BUCKET, BUCKET); - DispenserBlock.registerBehavior(ModItems.MELT_GEM_BUCKET, BUCKET); + DispenserBlock.registerBehavior(Items.MILK_BUCKET, ModDispenserBehavior.FLUID_BUCKET); + DispenserBlock.registerBehavior(Items.HONEY_BOTTLE, ModDispenserBehavior.FLUID_BUCKET); + DispenserBlock.registerBehavior(ModItems.OIL_BUCKET, ModDispenserBehavior.BUCKET); + DispenserBlock.registerBehavior(ModItems.MELT_GEM_BUCKET, ModDispenserBehavior.BUCKET); DispenserBlock.registerBehavior(ModBlocks.MENGER_SPONGE, ModDispenserBehavior::mengerSponge); for (ItemEntry cementBucket : ModItems.CEMENT_BUCKETS.values()) { - DispenserBlock.registerBehavior(cementBucket, BUCKET); + DispenserBlock.registerBehavior(cementBucket, ModDispenserBehavior.BUCKET); } // 空桶:优先尝试从目标方块的流体能力抽取液体生成对应桶物品,未命中时降级到原版行为 @@ -178,7 +179,7 @@ public ItemStack execute(BlockSource source, ItemStack stack) { return originalBucket.dispense(source, stack); } }); - DispenserBlock.registerBehavior(Items.GLASS_BOTTLE, EMPTY_FLUID_CONTAINER); + DispenserBlock.registerBehavior(Items.GLASS_BOTTLE, ModDispenserBehavior.EMPTY_FLUID_CONTAINER); } private static ItemStack mengerSponge(BlockSource source, ItemStack stack) { @@ -229,7 +230,7 @@ private static ItemStack bowl(BlockSource blockSource, ItemStack bowlStack) { m -> !m.isBaby() ); - if (mushroomCow == null) return DEFAULT_BEHAVIOUR.dispense(blockSource, bowlStack); + if (mushroomCow == null) return ModDispenserBehavior.DEFAULT_BEHAVIOUR.dispense(blockSource, bowlStack); ItemStack stewItem; SoundEvent sound; @@ -248,7 +249,7 @@ private static ItemStack bowl(BlockSource blockSource, ItemStack bowlStack) { if (bowlStack.isEmpty()) return stewItem; ItemStack remainedStewItem = blockSource.blockEntity().insertItem(stewItem); - if (!remainedStewItem.isEmpty()) DEFAULT_BEHAVIOUR.dispense(blockSource, remainedStewItem); + if (!remainedStewItem.isEmpty()) ModDispenserBehavior.DEFAULT_BEHAVIOUR.dispense(blockSource, remainedStewItem); return bowlStack; } @@ -258,8 +259,8 @@ private static ItemStack goldenApple(BlockSource blockSource, ItemStack stack) { new AABB(blockSource.pos().relative(blockSource.state().getValue(DirectionalBlock.FACING))), z -> z.hasEffect(MobEffects.WEAKNESS) && !z.isConverting() ); - if (zombieVillager == null) return DEFAULT_BEHAVIOUR.dispense(blockSource, stack); - zombieVillager.startConverting(ANVILCRAFT_DISPENSER, zombieVillager.getRandom().nextInt(2401) + 3600); + if (zombieVillager == null) return ModDispenserBehavior.DEFAULT_BEHAVIOUR.dispense(blockSource, stack); + zombieVillager.startConverting(ModDispenserBehavior.ANVILCRAFT_DISPENSER, zombieVillager.getRandom().nextInt(2401) + 3600); stack.shrink(1); return stack; } @@ -281,7 +282,7 @@ private static ItemStack resinBlock(BlockSource blockSource, ItemStack resinBloc new AABB(blockSource.pos().relative(blockSource.state().getValue(DirectionalBlock.FACING))), HasMobBlockItem::canMobBeSaved ); - if (mob == null) return DEFAULT_BEHAVIOUR.dispense(blockSource, resinBlockItem); + if (mob == null) return ModDispenserBehavior.DEFAULT_BEHAVIOUR.dispense(blockSource, resinBlockItem); ItemStack mobResin = ResinBlockItem.saveMobInItem(blockSource.level(), mob, resinBlockItem); if (resinBlockItem.isEmpty()) return mobResin; diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModHammerInits.java b/src/main/java/dev/dubhe/anvilcraft/init/ModHammerInits.java index ee68316f17..e9e32ba6b8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModHammerInits.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModHammerInits.java @@ -10,8 +10,7 @@ public class ModHammerInits { /// 初始化铁砧锤处理器 public static void init() { for (Block block : BuiltInRegistries.BLOCK) { - // noinspection deprecation - if (!block.builtInRegistryHolder().is(ModBlockTags.HAMMER_CHANGEABLE)) continue; + if (!BuiltInRegistries.BLOCK.wrapAsHolder(block).is(ModBlockTags.HAMMER_CHANGEABLE)) continue; HammerManager.registerChange(() -> block, HammerRotateBehavior.DEFAULT); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModHeaterInfos.java b/src/main/java/dev/dubhe/anvilcraft/init/ModHeaterInfos.java index fb002802e6..12ef69ab89 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModHeaterInfos.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModHeaterInfos.java @@ -24,7 +24,9 @@ public class ModHeaterInfos { public static final HeaterInfo HELIOSTATS = HeatRecorder.registerProducerInfo( HeaterInfo.blockEntity( ModBlockEntities.HELIOSTATS, - heliostats -> Set.of(heliostats.getIrritatePos(), heliostats.getIrritatePos().above()), + heliostats -> Optional.ofNullable(heliostats.getIrritatePos()) + .map(pos -> Set.of(pos, pos.above())) + .orElse(Set.of()), HeatTierLine.builder() .addPoint(4, HeatTier.NORMAL) .addPoint(12, HeatTier.HEATED, 4) diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModInspections.java b/src/main/java/dev/dubhe/anvilcraft/init/ModInspections.java index 2d6e05dc76..5b2004f99d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModInspections.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModInspections.java @@ -23,7 +23,7 @@ public class ModInspections { private final List inspectionOptions = new ArrayList<>(); public static void initialize() { - INSTANCE.registerActionServer(AnvilCraft.of("silencer")); + ModInspections.INSTANCE.registerActionServer(AnvilCraft.of("silencer")); } /// 注册检查项 @@ -34,7 +34,7 @@ public static void initialize() { /// /// @see InspectionSupport public void registerActionServer(Identifier id) { - INSTANCE.inspectionOptions.add(id); + ModInspections.INSTANCE.inspectionOptions.add(id); } private int changeStateServer(ServerPlayer player, Identifier id, boolean state) { diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModMobEffects.java b/src/main/java/dev/dubhe/anvilcraft/init/ModMobEffects.java index 1dad0e1e36..4e1cf07c4b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModMobEffects.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModMobEffects.java @@ -12,16 +12,16 @@ public class ModMobEffects { private static final DeferredRegister EFFECTS = DeferredRegister.create(Registries.MOB_EFFECT, AnvilCraft.MOD_ID); - public static final DeferredHolder RAGE = EFFECTS.register( + public static final DeferredHolder RAGE = ModMobEffects.EFFECTS.register( "rage", () -> new InstantenousMobEffect(MobEffectCategory.BENEFICIAL, 0xFF0000) ); - public static final DeferredHolder INVULNERABLE = EFFECTS.register( + public static final DeferredHolder INVULNERABLE = ModMobEffects.EFFECTS.register( "invulnerable", () -> new InstantenousMobEffect(MobEffectCategory.BENEFICIAL, 0xFF0000) ); public static void register(IEventBus eventBus) { - EFFECTS.register(eventBus); + ModMobEffects.EFFECTS.register(eventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModParticles.java b/src/main/java/dev/dubhe/anvilcraft/init/ModParticles.java index 44a53b601b..c74f3ebeb3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModParticles.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModParticles.java @@ -12,35 +12,35 @@ public class ModParticles { private static final DeferredRegister> REGISTER = DeferredRegister.create(Registries.PARTICLE_TYPE, AnvilCraft.MOD_ID); - public static final Supplier PLASMA_JETS = REGISTER.register( + public static final Supplier PLASMA_JETS = ModParticles.REGISTER.register( "plasma_jets", () -> new SimpleParticleType(false) ); - public static final Supplier ANVILON_ENERGY = REGISTER.register( + public static final Supplier ANVILON_ENERGY = ModParticles.REGISTER.register( "anvilon_energy", () -> new SimpleParticleType(false) ); - public static final Supplier ANVILON_MASS = REGISTER.register( + public static final Supplier ANVILON_MASS = ModParticles.REGISTER.register( "anvilon_mass", () -> new SimpleParticleType(false) ); - public static final Supplier ANVILON_SPACE = REGISTER.register( + public static final Supplier ANVILON_SPACE = ModParticles.REGISTER.register( "anvilon_space", () -> new SimpleParticleType(false) ); - public static final Supplier ANVILON_TIME = REGISTER.register( + public static final Supplier ANVILON_TIME = ModParticles.REGISTER.register( "anvilon_time", () -> new SimpleParticleType(false) ); - public static final Supplier IONOCRAFT_BACKPACK_EXHAUST = REGISTER.register( + public static final Supplier IONOCRAFT_BACKPACK_EXHAUST = ModParticles.REGISTER.register( "ionocraft_backpack_exhaust", () -> new SimpleParticleType(false) ); - public static final Supplier OVERSEER_TRAIL = REGISTER.register( + public static final Supplier OVERSEER_TRAIL = ModParticles.REGISTER.register( "overseer_trail", () -> new SimpleParticleType(false) ); public static void register(IEventBus modBus) { - REGISTER.register(modBus); + ModParticles.REGISTER.register(modBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModSoundEvents.java b/src/main/java/dev/dubhe/anvilcraft/init/ModSoundEvents.java index a46569d425..e14c961841 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModSoundEvents.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModSoundEvents.java @@ -12,54 +12,54 @@ public class ModSoundEvents { private static final DeferredRegister REGISTER = DeferredRegister.create(Registries.SOUND_EVENT, AnvilCraft.MOD_ID); - public static final Supplier PLASMA_JET = REGISTER.register( + public static final Supplier PLASMA_JET = ModSoundEvents.REGISTER.register( "plasma_jet", () -> SoundEvent.createFixedRangeEvent(AnvilCraft.of("plasma_jet"), 16.0f) ); - public static final Supplier BURNING_HEATER = REGISTER.register( + public static final Supplier BURNING_HEATER = ModSoundEvents.REGISTER.register( "burning_heater", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("burning_heater")) ); - public static final Supplier PLASMA_JET_LAVA = REGISTER.register( + public static final Supplier PLASMA_JET_LAVA = ModSoundEvents.REGISTER.register( "plasma_jet_lava", () -> SoundEvent.createFixedRangeEvent(AnvilCraft.of("plasma_jet_lava"), 12.0f) ); - public static final Supplier GIANT_ANVIL_LAND = REGISTER.register( + public static final Supplier GIANT_ANVIL_LAND = ModSoundEvents.REGISTER.register( "giant_anvil_land", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("giant_anvil_land")) ); - public static final Supplier GIANT_ANVIL_SHOCK = REGISTER.register( + public static final Supplier GIANT_ANVIL_SHOCK = ModSoundEvents.REGISTER.register( "giant_anvil_shock", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("giant_anvil_shock")) ); - public static final Supplier GIANT_ANVIL_RESIN_SHOCK = REGISTER.register( + public static final Supplier GIANT_ANVIL_RESIN_SHOCK = ModSoundEvents.REGISTER.register( "giant_anvil_resin_shock", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("giant_anvil_resin_shock")) ); - public static final Supplier NEOFORGE_LAND = REGISTER.register( + public static final Supplier NEOFORGE_LAND = ModSoundEvents.REGISTER.register( "neoforge_land", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("neoforge_land")) ); - public static final Supplier TESLA_TOWER_STRIKE = REGISTER.register( + public static final Supplier TESLA_TOWER_STRIKE = ModSoundEvents.REGISTER.register( "tesla_tower_strike", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("tesla_tower_strike")) ); - public static final Supplier SMART_BLOCK_PLACER_EXTEND = REGISTER.register( + public static final Supplier SMART_BLOCK_PLACER_EXTEND = ModSoundEvents.REGISTER.register( "smart_block_placer_extend", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("smart_block_placer_extend")) ); - public static final Supplier SMART_BLOCK_PLACER_RETRACT = REGISTER.register( + public static final Supplier SMART_BLOCK_PLACER_RETRACT = ModSoundEvents.REGISTER.register( "smart_block_placer_retract", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("smart_block_placer_retract")) ); - public static final Supplier SMART_BLOCK_PLACER_SHULKER_OPEN = REGISTER.register( + public static final Supplier SMART_BLOCK_PLACER_SHULKER_OPEN = ModSoundEvents.REGISTER.register( "smart_block_placer_shulker_open", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("smart_block_placer_shulker_open")) ); - public static final Supplier ANVIL_HAMMER_ROTATE_BLOCK = REGISTER.register( + public static final Supplier ANVIL_HAMMER_ROTATE_BLOCK = ModSoundEvents.REGISTER.register( "anvil_hammer_rotate_block", () -> SoundEvent.createVariableRangeEvent(AnvilCraft.of("anvil_hammer_rotate_block")) ); public static void register(IEventBus modBus) { - REGISTER.register(modBus); + ModSoundEvents.REGISTER.register(modBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/ModStats.java b/src/main/java/dev/dubhe/anvilcraft/init/ModStats.java index 1e0215a7a5..a5487e6b20 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/ModStats.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/ModStats.java @@ -19,6 +19,6 @@ public static void register(IEventBus modEventBus) { } private static Identifier register(String id) { - return REGISTER.register(id, Function.identity()).getId(); + return ModStats.REGISTER.register(id, Function.identity()).getId(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlockTags.java b/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlockTags.java index 21728cf399..5b47f2c512 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlockTags.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlockTags.java @@ -14,121 +14,121 @@ public class ModBlockTags { private static final String MEKANISM_MODID = "mekanism"; private static final String AE2_MODID = "ae2"; // mod tags - public static final TagKey UNDER_CAULDRON = bind("under_cauldron"); - public static final TagKey MAGNET = bind("magnet"); - public static final TagKey REDSTONE_TORCH = bind("redstone_torch"); - public static final TagKey MUSHROOM_BLOCK = bind("mushroom_block"); - public static final TagKey CANT_BROKEN_ANVIL = bind("cant_broken_anvil"); - public static final TagKey NON_MAGNETIC = bind("non_magnetic"); - public static final TagKey HAMMER_REMOVABLE = bind("hammer_removable"); - public static final TagKey HAMMER_CHANGEABLE = bind("hammer_changeable"); - public static final TagKey OVERSEER_BASE = bind("overseer_base"); - public static final TagKey OVERSEER_BASE_TIER_0 = bind("overseer_base_tier_0"); - public static final TagKey OVERSEER_BASE_TIER_1 = bind("overseer_base_tier_1"); - public static final TagKey OVERSEER_BASE_TIER_2 = bind("overseer_base_tier_2"); - public static final TagKey OVERSEER_BASE_TIER_3 = bind("overseer_base_tier_3"); - public static final TagKey ROYAL_SERIES = bind("royal_series"); - public static final TagKey EMBER_SERIES = bind("ember_series"); - public static final TagKey FROST_SERIES = bind("frost_series"); - public static final TagKey BLOCK_DEVOURER_CHAIN_DEVOURING = bind("block_devourer_chain_devouring"); - public static final TagKey BLOCK_DEVOURER_PROBABILITY_DROPPING = bind("block_devourer_probability_dropping"); - public static final TagKey LASER_CAN_PASS_THROUGH = bind("laser_can_pass_though"); - public static final TagKey END_PORTAL_UNABLE_CHANGE = bind("end_portal_unable_change"); - public static final TagKey NEUTRONIUM_CANNOT_PASS_THROUGH = bind("neutronium_cannot_pass_through"); - public static final TagKey VOID_DECAY_PRODUCTS = bind("void_decay_products"); - public static final TagKey CRAFTING_MATRIX_ELEMENT = bind("crafting_matrix_element"); - public static final TagKey SPECTRAL_CAN_THROUGH = bind("spectral_can_through"); - public static final TagKey HEATABLE_BLOCKS = bind("heatable_blocks"); - public static final TagKey HEATED_BLOCKS = bind("heated_blocks"); - public static final TagKey REDHOT_BLOCKS = bind("redhot_blocks"); - public static final TagKey GLOWING_BLOCKS = bind("glowing_blocks"); - public static final TagKey INCANDESCENT_BLOCKS = bind("incandescent_blocks"); - public static final TagKey OVERHEATED_BLOCKS = bind("overheated_blocks"); - public static final TagKey SLIDING_RAILS = bind("sliding_rails"); - public static final TagKey STICKABLE_WITH_SLIDING_RAILS = bind("stickable_with_sliding_rails"); - public static final TagKey OVERHEATABLE = bind("overheatable"); - public static final TagKey ANVIL_TIER_0 = bind("anvil_tier_0"); - public static final TagKey ANVIL_TIER_1 = bind("anvil_tier_1"); - public static final TagKey ANVIL_TIER_2 = bind("anvil_tier_2"); - public static final TagKey ANVIL_TIER_3 = bind("anvil_tier_3"); - public static final TagKey GIANT_ANVIL = bind("giant_anvil"); - public static final TagKey SLIDING_RAIL_STOP_LIKE = bind("sliding_rail_stop_like"); + public static final TagKey UNDER_CAULDRON = ModBlockTags.bind("under_cauldron"); + public static final TagKey MAGNET = ModBlockTags.bind("magnet"); + public static final TagKey REDSTONE_TORCH = ModBlockTags.bind("redstone_torch"); + public static final TagKey MUSHROOM_BLOCK = ModBlockTags.bind("mushroom_block"); + public static final TagKey CANT_BROKEN_ANVIL = ModBlockTags.bind("cant_broken_anvil"); + public static final TagKey NON_MAGNETIC = ModBlockTags.bind("non_magnetic"); + public static final TagKey HAMMER_REMOVABLE = ModBlockTags.bind("hammer_removable"); + public static final TagKey HAMMER_CHANGEABLE = ModBlockTags.bind("hammer_changeable"); + public static final TagKey OVERSEER_BASE = ModBlockTags.bind("overseer_base"); + public static final TagKey OVERSEER_BASE_TIER_0 = ModBlockTags.bind("overseer_base_tier_0"); + public static final TagKey OVERSEER_BASE_TIER_1 = ModBlockTags.bind("overseer_base_tier_1"); + public static final TagKey OVERSEER_BASE_TIER_2 = ModBlockTags.bind("overseer_base_tier_2"); + public static final TagKey OVERSEER_BASE_TIER_3 = ModBlockTags.bind("overseer_base_tier_3"); + public static final TagKey ROYAL_SERIES = ModBlockTags.bind("royal_series"); + public static final TagKey EMBER_SERIES = ModBlockTags.bind("ember_series"); + public static final TagKey FROST_SERIES = ModBlockTags.bind("frost_series"); + public static final TagKey BLOCK_DEVOURER_CHAIN_DEVOURING = ModBlockTags.bind("block_devourer_chain_devouring"); + public static final TagKey BLOCK_DEVOURER_PROBABILITY_DROPPING = ModBlockTags.bind("block_devourer_probability_dropping"); + public static final TagKey LASER_CAN_PASS_THROUGH = ModBlockTags.bind("laser_can_pass_though"); + public static final TagKey END_PORTAL_UNABLE_CHANGE = ModBlockTags.bind("end_portal_unable_change"); + public static final TagKey NEUTRONIUM_CANNOT_PASS_THROUGH = ModBlockTags.bind("neutronium_cannot_pass_through"); + public static final TagKey VOID_DECAY_PRODUCTS = ModBlockTags.bind("void_decay_products"); + public static final TagKey CRAFTING_MATRIX_ELEMENT = ModBlockTags.bind("crafting_matrix_element"); + public static final TagKey SPECTRAL_CAN_THROUGH = ModBlockTags.bind("spectral_can_through"); + public static final TagKey HEATABLE_BLOCKS = ModBlockTags.bind("heatable_blocks"); + public static final TagKey HEATED_BLOCKS = ModBlockTags.bind("heated_blocks"); + public static final TagKey REDHOT_BLOCKS = ModBlockTags.bind("redhot_blocks"); + public static final TagKey GLOWING_BLOCKS = ModBlockTags.bind("glowing_blocks"); + public static final TagKey INCANDESCENT_BLOCKS = ModBlockTags.bind("incandescent_blocks"); + public static final TagKey OVERHEATED_BLOCKS = ModBlockTags.bind("overheated_blocks"); + public static final TagKey SLIDING_RAILS = ModBlockTags.bind("sliding_rails"); + public static final TagKey STICKABLE_WITH_SLIDING_RAILS = ModBlockTags.bind("stickable_with_sliding_rails"); + public static final TagKey OVERHEATABLE = ModBlockTags.bind("overheatable"); + public static final TagKey ANVIL_TIER_0 = ModBlockTags.bind("anvil_tier_0"); + public static final TagKey ANVIL_TIER_1 = ModBlockTags.bind("anvil_tier_1"); + public static final TagKey ANVIL_TIER_2 = ModBlockTags.bind("anvil_tier_2"); + public static final TagKey ANVIL_TIER_3 = ModBlockTags.bind("anvil_tier_3"); + public static final TagKey GIANT_ANVIL = ModBlockTags.bind("giant_anvil"); + public static final TagKey SLIDING_RAIL_STOP_LIKE = ModBlockTags.bind("sliding_rail_stop_like"); // common tags - public static final TagKey ORES_TUNGSTEN = bindC("ores/tungsten"); - public static final TagKey ORES_TITANIUM = bindC("ores/titanium"); - public static final TagKey ORES_ZINC = bindC("ores/zinc"); - public static final TagKey ORES_TIN = bindC("ores/tin"); - public static final TagKey ORES_LEAD = bindC("ores/lead"); - public static final TagKey ORES_SILVER = bindC("ores/silver"); - public static final TagKey ORES_URANIUM = bindC("ores/uranium"); - public static final TagKey ORES_VOID_MATTER = bindC("ores/void_matter"); - public static final TagKey ORES_EARTH_CORE_SHARD = bindC("ores/earth_core_shard"); - - public static final TagKey STORAGE_BLOCKS_RAW_TUNGSTEN = bindC("storage_blocks/raw_tungsten"); - public static final TagKey STORAGE_BLOCKS_RAW_TITANIUM = bindC("storage_blocks/raw_titanium"); - public static final TagKey STORAGE_BLOCKS_RAW_ZINC = bindC("storage_blocks/raw_zinc"); - public static final TagKey STORAGE_BLOCKS_RAW_TIN = bindC("storage_blocks/raw_tin"); - public static final TagKey STORAGE_BLOCKS_RAW_LEAD = bindC("storage_blocks/raw_lead"); - public static final TagKey STORAGE_BLOCKS_RAW_SILVER = bindC("storage_blocks/raw_silver"); - public static final TagKey STORAGE_BLOCKS_RAW_URANIUM = bindC("storage_blocks/raw_uranium"); - - public static final TagKey STORAGE_BLOCKS_VOID_MATTER = bindC("storage_blocks/void_matter"); - public static final TagKey STORAGE_BLOCKS_EARTH_CORE_SHARD = bindC("storage_blocks/earth_core_shard"); - public static final TagKey STORAGE_BLOCKS_MULTIPHASE_MATTER = bindC("storage_blocks/multiphase_matter"); - - public static final TagKey STORAGE_BLOCKS_TUNGSTEN = bindC("storage_blocks/tungsten"); - public static final TagKey STORAGE_BLOCKS_TITANIUM = bindC("storage_blocks/titanium"); - public static final TagKey STORAGE_BLOCKS_ZINC = bindC("storage_blocks/zinc"); - public static final TagKey STORAGE_BLOCKS_TIN = bindC("storage_blocks/tin"); - public static final TagKey STORAGE_BLOCKS_LEAD = bindC("storage_blocks/lead"); - public static final TagKey STORAGE_BLOCKS_SILVER = bindC("storage_blocks/silver"); - public static final TagKey STORAGE_BLOCKS_URANIUM = bindC("storage_blocks/uranium"); - public static final TagKey STORAGE_BLOCKS_PLUTONIUM = bindC("storage_blocks/plutonium"); - public static final TagKey STORAGE_BLOCKS_BRONZE = bindC("storage_blocks/bronze"); - public static final TagKey STORAGE_BLOCKS_BRASS = bindC("storage_blocks/brass"); - public static final TagKey STORAGE_BLOCKS_MAGNET = bindC("storage_blocks/magnet"); - public static final TagKey STORAGE_BLOCKS_TOPAZ = bindC("storage_blocks/topaz"); - public static final TagKey STORAGE_BLOCKS_SAPPHIRE = bindC("storage_blocks/sapphire"); - public static final TagKey STORAGE_BLOCKS_RUBY = bindC("storage_blocks/ruby"); - public static final TagKey STORAGE_BLOCKS_EXP_GEM = bindC("storage_blocks/exp_gem"); - public static final TagKey STORAGE_BLOCKS_AMBER = bindC("storage_blocks/amber"); - public static final TagKey STORAGE_BLOCKS_RESIN = bindC("storage_blocks/resin"); - public static final TagKey STORAGE_BLOCKS_TRANSCENDIUM = bindC("storage_blocks/transcendium"); - public static final TagKey STORAGE_BLOCKS_FROST_METAL = bindC("storage_blocks/frost_metal"); - - public static final TagKey STORAGE_BLOCKS_SUGAR = bindC("storage_blocks/sugar"); - public static final TagKey STORAGE_BLOCKS_GUNPOWDER = bindC("storage_blocks/gunpowder"); - public static final TagKey STORAGE_BLOCKS_ROTTEN_FLESH = bindC("storage_blocks/rotten_flesh"); - public static final TagKey STORAGE_BLOCKS_FLINT = bindC("storage_blocks/flint"); - - public static final TagKey INCORRECT_FOR_EMBER_TOOL = bind("incorrect_for_ember_tool"); - public static final TagKey INCORRECT_FOR_TRANSCENDIUM_TOOL = bind("incorrect_for_transcendium_tool"); - - public static final TagKey NEEDS_EMBER_TOOL = bind("needs_ember_tool"); - public static final TagKey NEEDS_NETHERITE_TOOL = bind("needs_netherite_tool"); - public static final TagKey NEEDS_TRANSCENDIUM_TOOL = bind("needs_transcendium_tool"); - - public static final TagKey ANVIL_HAMMER_BLACKLIST = bind("anvil_hammer_blacklist"); - public static final TagKey DEVOUR_BLACKLIST = bind("devour_blacklist"); - - public static final TagKey FELLING_APPLICABLE = bind("felling_applicable"); - public static final TagKey CLEANING_APPLICABLE = bind("cleaning_applicable"); - public static final TagKey BROKEN_CRYSTALS_CLUSTERS = bind("broken_crystals_clusters"); - - public static final TagKey COLLISION_IMMUNE = bind("collision_immune"); - - public static final TagKey AE2_GLASS_CABLE = bindAe2("glass_cable"); - public static final TagKey AE2_COVERED_CABLE = bindAe2("covered_cable"); - public static final TagKey AE2_SMART_CABLE = bindAe2("smart_cable"); - public static final TagKey AE2_COVERED_DENSE_CABLE = bindAe2("covered_dense_cable"); - public static final TagKey AE2_SMART_DENSE_CABLE = bindAe2("smart_dense_cable"); + public static final TagKey ORES_TUNGSTEN = ModBlockTags.bindC("ores/tungsten"); + public static final TagKey ORES_TITANIUM = ModBlockTags.bindC("ores/titanium"); + public static final TagKey ORES_ZINC = ModBlockTags.bindC("ores/zinc"); + public static final TagKey ORES_TIN = ModBlockTags.bindC("ores/tin"); + public static final TagKey ORES_LEAD = ModBlockTags.bindC("ores/lead"); + public static final TagKey ORES_SILVER = ModBlockTags.bindC("ores/silver"); + public static final TagKey ORES_URANIUM = ModBlockTags.bindC("ores/uranium"); + public static final TagKey ORES_VOID_MATTER = ModBlockTags.bindC("ores/void_matter"); + public static final TagKey ORES_EARTH_CORE_SHARD = ModBlockTags.bindC("ores/earth_core_shard"); + + public static final TagKey STORAGE_BLOCKS_RAW_TUNGSTEN = ModBlockTags.bindC("storage_blocks/raw_tungsten"); + public static final TagKey STORAGE_BLOCKS_RAW_TITANIUM = ModBlockTags.bindC("storage_blocks/raw_titanium"); + public static final TagKey STORAGE_BLOCKS_RAW_ZINC = ModBlockTags.bindC("storage_blocks/raw_zinc"); + public static final TagKey STORAGE_BLOCKS_RAW_TIN = ModBlockTags.bindC("storage_blocks/raw_tin"); + public static final TagKey STORAGE_BLOCKS_RAW_LEAD = ModBlockTags.bindC("storage_blocks/raw_lead"); + public static final TagKey STORAGE_BLOCKS_RAW_SILVER = ModBlockTags.bindC("storage_blocks/raw_silver"); + public static final TagKey STORAGE_BLOCKS_RAW_URANIUM = ModBlockTags.bindC("storage_blocks/raw_uranium"); + + public static final TagKey STORAGE_BLOCKS_VOID_MATTER = ModBlockTags.bindC("storage_blocks/void_matter"); + public static final TagKey STORAGE_BLOCKS_EARTH_CORE_SHARD = ModBlockTags.bindC("storage_blocks/earth_core_shard"); + public static final TagKey STORAGE_BLOCKS_MULTIPHASE_MATTER = ModBlockTags.bindC("storage_blocks/multiphase_matter"); + + public static final TagKey STORAGE_BLOCKS_TUNGSTEN = ModBlockTags.bindC("storage_blocks/tungsten"); + public static final TagKey STORAGE_BLOCKS_TITANIUM = ModBlockTags.bindC("storage_blocks/titanium"); + public static final TagKey STORAGE_BLOCKS_ZINC = ModBlockTags.bindC("storage_blocks/zinc"); + public static final TagKey STORAGE_BLOCKS_TIN = ModBlockTags.bindC("storage_blocks/tin"); + public static final TagKey STORAGE_BLOCKS_LEAD = ModBlockTags.bindC("storage_blocks/lead"); + public static final TagKey STORAGE_BLOCKS_SILVER = ModBlockTags.bindC("storage_blocks/silver"); + public static final TagKey STORAGE_BLOCKS_URANIUM = ModBlockTags.bindC("storage_blocks/uranium"); + public static final TagKey STORAGE_BLOCKS_PLUTONIUM = ModBlockTags.bindC("storage_blocks/plutonium"); + public static final TagKey STORAGE_BLOCKS_BRONZE = ModBlockTags.bindC("storage_blocks/bronze"); + public static final TagKey STORAGE_BLOCKS_BRASS = ModBlockTags.bindC("storage_blocks/brass"); + public static final TagKey STORAGE_BLOCKS_MAGNET = ModBlockTags.bindC("storage_blocks/magnet"); + public static final TagKey STORAGE_BLOCKS_TOPAZ = ModBlockTags.bindC("storage_blocks/topaz"); + public static final TagKey STORAGE_BLOCKS_SAPPHIRE = ModBlockTags.bindC("storage_blocks/sapphire"); + public static final TagKey STORAGE_BLOCKS_RUBY = ModBlockTags.bindC("storage_blocks/ruby"); + public static final TagKey STORAGE_BLOCKS_EXP_GEM = ModBlockTags.bindC("storage_blocks/exp_gem"); + public static final TagKey STORAGE_BLOCKS_AMBER = ModBlockTags.bindC("storage_blocks/amber"); + public static final TagKey STORAGE_BLOCKS_RESIN = ModBlockTags.bindC("storage_blocks/resin"); + public static final TagKey STORAGE_BLOCKS_TRANSCENDIUM = ModBlockTags.bindC("storage_blocks/transcendium"); + public static final TagKey STORAGE_BLOCKS_FROST_METAL = ModBlockTags.bindC("storage_blocks/frost_metal"); + + public static final TagKey STORAGE_BLOCKS_SUGAR = ModBlockTags.bindC("storage_blocks/sugar"); + public static final TagKey STORAGE_BLOCKS_GUNPOWDER = ModBlockTags.bindC("storage_blocks/gunpowder"); + public static final TagKey STORAGE_BLOCKS_ROTTEN_FLESH = ModBlockTags.bindC("storage_blocks/rotten_flesh"); + public static final TagKey STORAGE_BLOCKS_FLINT = ModBlockTags.bindC("storage_blocks/flint"); + + public static final TagKey INCORRECT_FOR_EMBER_TOOL = ModBlockTags.bind("incorrect_for_ember_tool"); + public static final TagKey INCORRECT_FOR_TRANSCENDIUM_TOOL = ModBlockTags.bind("incorrect_for_transcendium_tool"); + + public static final TagKey NEEDS_EMBER_TOOL = ModBlockTags.bind("needs_ember_tool"); + public static final TagKey NEEDS_NETHERITE_TOOL = ModBlockTags.bind("needs_netherite_tool"); + public static final TagKey NEEDS_TRANSCENDIUM_TOOL = ModBlockTags.bind("needs_transcendium_tool"); + + public static final TagKey ANVIL_HAMMER_BLACKLIST = ModBlockTags.bind("anvil_hammer_blacklist"); + public static final TagKey DEVOUR_BLACKLIST = ModBlockTags.bind("devour_blacklist"); + + public static final TagKey FELLING_APPLICABLE = ModBlockTags.bind("felling_applicable"); + public static final TagKey CLEANING_APPLICABLE = ModBlockTags.bind("cleaning_applicable"); + public static final TagKey BROKEN_CRYSTALS_CLUSTERS = ModBlockTags.bind("broken_crystals_clusters"); + + public static final TagKey COLLISION_IMMUNE = ModBlockTags.bind("collision_immune"); + + public static final TagKey AE2_GLASS_CABLE = ModBlockTags.bindAe2("glass_cable"); + public static final TagKey AE2_COVERED_CABLE = ModBlockTags.bindAe2("covered_cable"); + public static final TagKey AE2_SMART_CABLE = ModBlockTags.bindAe2("smart_cable"); + public static final TagKey AE2_COVERED_DENSE_CABLE = ModBlockTags.bindAe2("covered_dense_cable"); + public static final TagKey AE2_SMART_DENSE_CABLE = ModBlockTags.bindAe2("smart_dense_cable"); // vanilla tags public static final TagKey LIGHTNING_RODS = TagKey.create(Registries.BLOCK, Identifier.withDefaultNamespace("lightning_rods")); // mekanism tags - public static final TagKey MEKANISM_CARDBOARD_BOX_BLACKLIST = bindMekanism("cardboard_blacklist"); + public static final TagKey MEKANISM_CARDBOARD_BOX_BLACKLIST = ModBlockTags.bindMekanism("cardboard_blacklist"); private static TagKey bindC(String id) { return TagKey.create(Registries.BLOCK, Identifier.fromNamespaceAndPath("c", id)); @@ -136,24 +136,24 @@ private static TagKey bindC(String id) { @SuppressWarnings("SameParameterValue") private static TagKey bindMekanism(String id) { - return TagKey.create(Registries.BLOCK, Identifier.fromNamespaceAndPath(MEKANISM_MODID, id)); + return TagKey.create(Registries.BLOCK, Identifier.fromNamespaceAndPath(ModBlockTags.MEKANISM_MODID, id)); } @SuppressWarnings("SameParameterValue") private static TagKey bindAe2(String id) { - return TagKey.create(Registries.BLOCK, Identifier.fromNamespaceAndPath(AE2_MODID, id)); + return TagKey.create(Registries.BLOCK, Identifier.fromNamespaceAndPath(ModBlockTags.AE2_MODID, id)); } private static TagKey bind(String id) { return TagKey.create(Registries.BLOCK, AnvilCraft.of(id)); } - public static final Object2ObjectMap> DYED_COLORS = initDyedTags(); + public static final Object2ObjectMap> DYED_COLORS = ModBlockTags.initDyedTags(); public static Object2ObjectMap> initDyedTags() { Object2ObjectMap> map = new Object2ObjectOpenHashMap<>(); for (Color color : Color.values()) { - map.put(color, bindC("dyed/" + color)); + map.put(color, ModBlockTags.bindC("dyed/" + color)); } return map; } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlocks.java b/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlocks.java index 35313725d0..e88c3cab86 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlocks.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/block/ModBlocks.java @@ -44,6 +44,7 @@ import dev.dubhe.anvilcraft.block.cfa.interfaces.CelestialForgingAnvilLaserInterfaceBlock; import dev.dubhe.anvilcraft.block.cfa.interfaces.CelestialForgingAnvilLogisticsInterfaceBlock; import dev.dubhe.anvilcraft.block.cfa.item.CelestialForgingAnvilAmplifierBlockItem; +import dev.dubhe.anvilcraft.block.cfa.item.CelestialForgingAnvilBlockItem; import dev.dubhe.anvilcraft.block.cfa.item.CelestialForgingAnvilInterfaceBlockItem; import dev.dubhe.anvilcraft.block.cfa.item.CelestialForgingAnvilPortalBlockItem; import dev.dubhe.anvilcraft.block.container.CreativeCrateBlock; @@ -213,6 +214,7 @@ import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.init.item.ModItemTags; import dev.dubhe.anvilcraft.init.item.ModItems; +import dev.dubhe.anvilcraft.item.SingularityCrystalItem; import dev.dubhe.anvilcraft.item.block.ChuteBlockItem; import dev.dubhe.anvilcraft.item.block.CreativeContainerBlockItem; import dev.dubhe.anvilcraft.item.block.CursedBlockItem; @@ -1397,7 +1399,7 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry LARGE_LASER = REGISTRUM .block("large_laser", LargeLaserBlock::new) - .initialProperties(RUBY_LASER::get) + .initialProperties(ModBlocks.RUBY_LASER::get) .properties(properties -> properties .isSuffocating(ModBlocks::never) .noOcclusion() @@ -1733,7 +1735,7 @@ public void accept( .emissiveRendering(ModBlocks::always)) .blockstate(DataGenUtil::noExtraModelOrState) .tag((BlockTags.MINEABLE_WITH_PICKAXE)) - .item(dev.dubhe.anvilcraft.block.cfa.item.CelestialForgingAnvilBlockItem::new) + .item(CelestialForgingAnvilBlockItem::new) .properties(properties -> properties.stacksTo(16)) .model(DataGenUtil::oversizedItem) .build() @@ -2600,14 +2602,14 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CUT_BRONZE_BLOCK = REGISTRUM .block("cut_bronze_block", Block::new) .lang("Cut Bronze") - .initialProperties(BRONZE_BLOCK::get) + .initialProperties(ModBlocks.BRONZE_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .simpleItem() .register(); public static final BlockEntry CUT_BRONZE_STAIRS = REGISTRUM .block("cut_bronze_stairs", (properties) -> new StairBlock(ModBlocks.CUT_BRONZE_BLOCK.getDefaultState(), properties)) - .initialProperties(BRONZE_BLOCK::get) + .initialProperties(ModBlocks.BRONZE_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .blockstate(() -> DataGenUtil.stairsBlock(AnvilCraft.of("block/cut_bronze_block"))) .simpleItem() @@ -2615,7 +2617,7 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CUT_BRONZE_SLAB = REGISTRUM .block("cut_bronze_slab", SlabBlock::new) - .initialProperties(BRONZE_BLOCK::get) + .initialProperties(ModBlocks.BRONZE_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .blockstate(() -> DataGenUtil.slabBlock(AnvilCraft.of("block/cut_bronze_block"))) .simpleItem() @@ -2623,7 +2625,7 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CUT_BRONZE_PILLAR = REGISTRUM .block("cut_bronze_pillar", RotatedPillarBlock::new) - .initialProperties(BRONZE_BLOCK::get) + .initialProperties(ModBlocks.BRONZE_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .blockstate(() -> DataGenUtil.columnBlock(AnvilCraft.of("block/cut_bronze_pillar"), AnvilCraft.of("block/cut_bronze_pillar_top"))) .simpleItem() @@ -2631,7 +2633,7 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CHISELED_BRONZE_BLOCK = REGISTRUM .block("chiseled_bronze_block", Block::new) - .initialProperties(BRONZE_BLOCK::get) + .initialProperties(ModBlocks.BRONZE_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .simpleItem() .register(); @@ -2648,14 +2650,14 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CUT_BRASS_BLOCK = REGISTRUM .block("cut_brass_block", Block::new) .lang("Cut Brass") - .initialProperties(BRASS_BLOCK::get) + .initialProperties(ModBlocks.BRASS_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .simpleItem() .register(); public static final BlockEntry CUT_BRASS_STAIRS = REGISTRUM .block("cut_brass_stairs", (properties) -> new StairBlock(ModBlocks.CUT_BRASS_BLOCK.getDefaultState(), properties)) - .initialProperties(BRASS_BLOCK::get) + .initialProperties(ModBlocks.BRASS_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .blockstate(() -> DataGenUtil.stairsBlock(AnvilCraft.of("block/cut_brass_block"))) .simpleItem() @@ -2663,7 +2665,7 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CUT_BRASS_SLAB = REGISTRUM .block("cut_brass_slab", SlabBlock::new) - .initialProperties(BRASS_BLOCK::get) + .initialProperties(ModBlocks.BRASS_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .blockstate(() -> DataGenUtil.slabBlock(AnvilCraft.of("block/cut_brass_block"))) .simpleItem() @@ -2671,7 +2673,7 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CUT_BRASS_PILLAR = REGISTRUM .block("cut_brass_pillar", RotatedPillarBlock::new) - .initialProperties(BRASS_BLOCK::get) + .initialProperties(ModBlocks.BRASS_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .blockstate(() -> DataGenUtil.columnBlock(AnvilCraft.of("block/cut_brass_pillar"), AnvilCraft.of("block/cut_brass_pillar_top"))) .simpleItem() @@ -2679,7 +2681,7 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera public static final BlockEntry CHISELED_BRASS_BLOCK = REGISTRUM .block("chiseled_brass_block", Block::new) - .initialProperties(BRASS_BLOCK::get) + .initialProperties(ModBlocks.BRASS_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .simpleItem() .register(); @@ -3172,10 +3174,14 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera .recipe(RegistrumBlockRecipeLoader::whiteChocolateStairs) .register(); - public static final Object2ObjectMap> REINFORCED_CONCRETES = registerReinforcedConcretes(); - public static final Object2ObjectMap> REINFORCED_CONCRETE_SLABS = registerReinforcedConcreteSlabs(); - public static final Object2ObjectMap> REINFORCED_CONCRETE_STAIRS = registerReinforcedConcreteStairs(); - public static final Object2ObjectMap> REINFORCED_CONCRETE_WALLS = registerReinforcedConcreteWalls(); + public static final Object2ObjectMap> REINFORCED_CONCRETES = + ModBlocks.registerReinforcedConcretes(); + public static final Object2ObjectMap> REINFORCED_CONCRETE_SLABS = + ModBlocks.registerReinforcedConcreteSlabs(); + public static final Object2ObjectMap> REINFORCED_CONCRETE_STAIRS = + ModBlocks.registerReinforcedConcreteStairs(); + public static final Object2ObjectMap> REINFORCED_CONCRETE_WALLS = + ModBlocks.registerReinforcedConcreteWalls(); public static final BlockEntry HEATED_NETHERITE_BLOCK = REGISTRUM.block("heated_netherite_block", HeatedBlock::new) .lang("Heated Block of Netherite") @@ -3642,12 +3648,12 @@ public void accept(DataGenContext ctx, RegistrumItemModelGenera .onRegister(block -> Item.BY_BLOCK.put(block, Items.CAULDRON)) .register(); - public static final Object2ObjectMap> CEMENT_CAULDRONS = registerAllCementCauldrons(); + public static final Object2ObjectMap> CEMENT_CAULDRONS = ModBlocks.registerAllCementCauldrons(); private static Object2ObjectMap> registerReinforcedConcretes() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var entry = registerReinforcedConcreteBlock(color); + var entry = ModBlocks.registerReinforcedConcreteBlock(color); map.put(color, entry); } return map; @@ -3706,7 +3712,7 @@ public void accept( private static Object2ObjectMap> registerReinforcedConcreteSlabs() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var entry = registerReinforcedConcreteSlabBlock(color, REINFORCED_CONCRETES.get(color)); + var entry = ModBlocks.registerReinforcedConcreteSlabBlock(color, ModBlocks.REINFORCED_CONCRETES.get(color)); map.put(color, entry); } return map; @@ -3729,7 +3735,7 @@ private static BlockEntry registerReinforcedConcreteSlabBlock(Color c private static Object2ObjectMap> registerReinforcedConcreteStairs() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var entry = registerReinforcedConcreteStairBlock(color, REINFORCED_CONCRETES.get(color)); + var entry = ModBlocks.registerReinforcedConcreteStairBlock(color, ModBlocks.REINFORCED_CONCRETES.get(color)); map.put(color, entry); } return map; @@ -3754,7 +3760,7 @@ private static BlockEntry registerReinforcedConcreteStairBlock(Color private static Object2ObjectMap> registerReinforcedConcreteWalls() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var entry = registerReinforcedConcreteWallBlock(color, REINFORCED_CONCRETES.get(color)); + var entry = ModBlocks.registerReinforcedConcreteWallBlock(color, ModBlocks.REINFORCED_CONCRETES.get(color)); map.put(color, entry); } return map; @@ -3776,7 +3782,7 @@ private static BlockEntry registerReinforcedConcreteWallBlock(Color c private static Object2ObjectMap> registerAllCementCauldrons() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var entry = registerCementCauldron(color); + var entry = ModBlocks.registerCementCauldron(color); map.put(color, entry); } return map; @@ -3922,12 +3928,12 @@ private static BlockEntry registerPressu .blockstate(ModelProviderUtil::liquid) .register(); - public static final Object2ObjectMap> CEMENTS = registerAllCementLiquidBlock(); + public static final Object2ObjectMap> CEMENTS = ModBlocks.registerAllCementLiquidBlock(); private static Object2ObjectMap> registerAllCementLiquidBlock() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var entry = registerCementLiquidBlock(color); + var entry = ModBlocks.registerCementLiquidBlock(color); map.put(color, entry); } return map; @@ -4050,7 +4056,7 @@ private static BlockEntry registerCementLiquidBlock(Color color) { .strength(50F, 1200.0F) .requiresCorrectToolForDrops()) .tag(BlockTags.MINEABLE_WITH_PICKAXE, ModBlockTags.NEEDS_TRANSCENDIUM_TOOL, ModBlockTags.COLLISION_IMMUNE) - .item(dev.dubhe.anvilcraft.item.SingularityCrystalItem::new) + .item(SingularityCrystalItem::new) .initialProperties(() -> new Item.Properties().fireResistant().stacksTo(1)) .tag(ModItemTags.EXPLOSION_PROOF) .build() @@ -4135,21 +4141,21 @@ public void accept(DataGenContext ctx, RegistrumBlockModelGen .register(); public static final BlockEntry POLISHED_FLINT_BLOCK = REGISTRUM.block("polished_flint_block", Block::new) - .initialProperties(FLINT_BLOCK::get) + .initialProperties(ModBlocks.FLINT_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .simpleItem() .recipe(RegistrumBlockRecipeLoader::polishedFlintBlock) .register(); public static final BlockEntry CUT_FLINT_BLOCK = REGISTRUM.block("cut_flint_block", Block::new) - .initialProperties(FLINT_BLOCK::get) + .initialProperties(ModBlocks.FLINT_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .simpleItem() .recipe(RegistrumBlockRecipeLoader::cutFlintBlock) .register(); public static final BlockEntry CUT_FLINT_SLAB_BLOCK = REGISTRUM.block("cut_flint_slab", SlabBlock::new) - .initialProperties(FLINT_BLOCK::get) + .initialProperties(ModBlocks.FLINT_BLOCK::get) .blockstate(() -> DataGenUtil.slabBlock( _ -> new Material(AnvilCraft.of("block/cut_flint_block")), _ -> new Material(AnvilCraft.of("block/cut_flint_block")), @@ -4165,9 +4171,9 @@ public void accept(DataGenContext ctx, RegistrumBlockModelGen public static final BlockEntry CUT_FLINT_STAIRS_BLOCK = REGISTRUM.block( "cut_flint_stairs", - properties -> new StairBlock(FLINT_BLOCK.getDefaultState(), properties) + properties -> new StairBlock(ModBlocks.FLINT_BLOCK.getDefaultState(), properties) ) - .initialProperties(FLINT_BLOCK::get) + .initialProperties(ModBlocks.FLINT_BLOCK::get) .blockstate(() -> DataGenUtil.stairsBlock(AnvilCraft.of("block/cut_flint_block"))) .tag(BlockTags.MINEABLE_WITH_PICKAXE, BlockTags.STAIRS) .item() @@ -4182,7 +4188,7 @@ public void accept(DataGenContext ctx, RegistrumBlockModelGen ) .tag(BlockTags.MINEABLE_WITH_PICKAXE) .simpleItem() - .initialProperties(FLINT_BLOCK::get) + .initialProperties(ModBlocks.FLINT_BLOCK::get) .blockstate(() -> DataGenUtil.columnBlock(AnvilCraft.of("block/cut_flint_pillar"), AnvilCraft.of("block/cut_flint_pillar_top"))) .recipe(RegistrumBlockRecipeLoader::cutFlintPillarBlock) .register(); @@ -4200,7 +4206,7 @@ public void accept(DataGenContext ctx, RegistrumBlockModelGen public static final BlockEntry PLYWOOD_STAIRS = REGISTRUM .block("plywood_stairs", (properties) -> new StairBlock(ModBlocks.PLYWOOD_BLOCK.getDefaultState(), properties)) - .initialProperties(PLYWOOD_BLOCK::get) + .initialProperties(ModBlocks.PLYWOOD_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_AXE) .blockstate(() -> DataGenUtil .stairsBlock( @@ -4214,7 +4220,7 @@ public void accept(DataGenContext ctx, RegistrumBlockModelGen public static final BlockEntry PLYWOOD_SLAB = REGISTRUM .block("plywood_slab", SlabBlock::new) - .initialProperties(PLYWOOD_BLOCK::get) + .initialProperties(ModBlocks.PLYWOOD_BLOCK::get) .tag(BlockTags.MINEABLE_WITH_AXE) .blockstate(() -> DataGenUtil .slabBlock( @@ -4352,68 +4358,68 @@ public void accept(DataGenContext ctx, RegistrumBlockModelGen .register(); public static final BlockEntry EXPOSED_COPPER_PRESSURE_PLATE = - registerOtherCopperPressurePlate("exposed_", Blocks.EXPOSED_COPPER, 20); + ModBlocks.registerOtherCopperPressurePlate("exposed_", Blocks.EXPOSED_COPPER, 20); public static final BlockEntry WEATHERED_COPPER_PRESSURE_PLATE = - registerOtherCopperPressurePlate("weathered_", Blocks.WEATHERED_COPPER, 40); + ModBlocks.registerOtherCopperPressurePlate("weathered_", Blocks.WEATHERED_COPPER, 40); public static final BlockEntry OXIDIZED_COPPER_PRESSURE_PLATE = - registerOtherCopperPressurePlate("oxidized_", Blocks.OXIDIZED_COPPER, 80); - public static final BlockEntry TUNGSTEN_PRESSURE_PLATE = registerPressurePlate( + ModBlocks.registerOtherCopperPressurePlate("oxidized_", Blocks.OXIDIZED_COPPER, 80); + public static final BlockEntry TUNGSTEN_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "tungsten", - TUNGSTEN_BLOCK, + ModBlocks.TUNGSTEN_BLOCK, FireImmunePressurePlateBlock::new, ModItemTags.TUNGSTEN_INGOTS ); - public static final BlockEntry TITANIUM_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry TITANIUM_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "titanium", - TITANIUM_BLOCK, + ModBlocks.TITANIUM_BLOCK, properties -> new ItemDurabilityPressurePlateBlock(properties, false), ModItemTags.TITANIUM_INGOTS ); - public static final BlockEntry ZINC_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry ZINC_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "zinc", - ZINC_BLOCK, + ModBlocks.ZINC_BLOCK, properties -> new HealthPercentPressurePlateBlock(properties, false), ModItemTags.ZINC_INGOTS ); - public static final BlockEntry TIN_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry TIN_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "tin", - TIN_BLOCK, + ModBlocks.TIN_BLOCK, properties -> new HealthPercentPressurePlateBlock(properties, true), ModItemTags.TIN_INGOTS ); - public static final BlockEntry LEAD_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry LEAD_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "lead", - LEAD_BLOCK, + ModBlocks.LEAD_BLOCK, EntityTypePressurePlateBlock::new, ModItemTags.LEAD_INGOTS ); - public static final BlockEntry SILVER_PRESSURE_PLATE = registerPressurePlate( - "silver", SILVER_BLOCK, properties -> new EntityCountPressurePlateBlock( + public static final BlockEntry SILVER_PRESSURE_PLATE = ModBlocks.registerPressurePlate( + "silver", ModBlocks.SILVER_BLOCK, properties -> new EntityCountPressurePlateBlock( properties, entity -> entity.typeHolder().is(TagKey.create(Registries.ENTITY_TYPE, Identifier.withDefaultNamespace("undead"))) ), ModItemTags.SILVER_INGOTS ); - public static final BlockEntry URANIUM_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry URANIUM_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "uranium", - URANIUM_BLOCK, + ModBlocks.URANIUM_BLOCK, properties -> new ItemDurabilityPressurePlateBlock(properties, true), ModItemTags.URANIUM_INGOTS ); - public static final BlockEntry PLUTONIUM_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry PLUTONIUM_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "plutonium", - PLUTONIUM_BLOCK, + ModBlocks.PLUTONIUM_BLOCK, PlayerInHandItemDurabilityPressurePlateBlock::new, ModItemTags.PLUTONIUM_INGOTS ); - public static final BlockEntry BRASS_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry BRASS_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "brass", - BRASS_BLOCK, + ModBlocks.BRASS_BLOCK, PlayerInventoryPressurePlateBlock::new, ModItemTags.BRASS_INGOTS ); - public static final BlockEntry BRONZE_PRESSURE_PLATE = registerPressurePlate( + public static final BlockEntry BRONZE_PRESSURE_PLATE = ModBlocks.registerPressurePlate( "bronze", - BRONZE_BLOCK, + ModBlocks.BRONZE_BLOCK, PlayerHungerPressurePlateBlock::new, ModItemTags.BRONZE_INGOTS ); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluidTags.java b/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluidTags.java index 5724a97ad0..0b3d123985 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluidTags.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluidTags.java @@ -8,12 +8,12 @@ public class ModFluidTags { - public static final TagKey OIL = bindC("oil"); - public static final TagKey CEMENT = bindC("cement"); - public static final TagKey EXPERIENCE = bindC("experience"); - public static final TagKey IGNITABLE = bind("ignitable"); + public static final TagKey OIL = ModFluidTags.bindC("oil"); + public static final TagKey CEMENT = ModFluidTags.bindC("cement"); + public static final TagKey EXPERIENCE = ModFluidTags.bindC("experience"); + public static final TagKey IGNITABLE = ModFluidTags.bind("ignitable"); - public static final TagKey MENGER_SPONGE_CAN_ABSORB = bind("menger_sponge_can_absorb"); + public static final TagKey MENGER_SPONGE_CAN_ABSORB = ModFluidTags.bind("menger_sponge_can_absorb"); public static TagKey bindC(String id) { return TagKey.create(Registries.FLUID, Identifier.fromNamespaceAndPath("c", id)); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluids.java b/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluids.java index 7931e39e72..bdf510a358 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluids.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/block/ModFluids.java @@ -45,7 +45,7 @@ public class ModFluids { ); public static final DeferredRegister FLUIDS = DeferredRegister.create(Registries.FLUID, AnvilCraft.MOD_ID); - public static final DeferredHolder EXP_FLUID_TYPE = FLUID_TYPES.register( + public static final DeferredHolder EXP_FLUID_TYPE = ModFluids.FLUID_TYPES.register( "exp_fluid", () -> new FluidType(FluidType.Properties.create() .descriptionId("block.anvilcraft.exp_fluid") @@ -59,20 +59,20 @@ public class ModFluids { ) ); - public static final DeferredHolder EXP_FLUID = FLUIDS.register( + public static final DeferredHolder EXP_FLUID = ModFluids.FLUIDS.register( "exp_fluid", () -> new BaseFlowingFluid.Source(ModFluids.EXP_FLUID_PROPERTIES) ); - public static final DeferredHolder FLOWING_EXP_FLUID = FLUIDS.register( + public static final DeferredHolder FLOWING_EXP_FLUID = ModFluids.FLUIDS.register( "flowing_exp_fluid", () -> new BaseFlowingFluid.Flowing(ModFluids.EXP_FLUID_PROPERTIES) ); public static final BaseFlowingFluid.Properties EXP_FLUID_PROPERTIES = new BaseFlowingFluid.Properties( - EXP_FLUID_TYPE, - EXP_FLUID, - FLOWING_EXP_FLUID + ModFluids.EXP_FLUID_TYPE, + ModFluids.EXP_FLUID, + ModFluids.FLOWING_EXP_FLUID ) .bucket(() -> ModItems.EXP_BUCKET.asItem()) .block(ModBlocks.EXP_FLUID) @@ -81,7 +81,7 @@ public class ModFluids { .levelDecreasePerBlock(3) .explosionResistance(100); - public static final DeferredHolder OIL_TYPE = FLUID_TYPES.register( + public static final DeferredHolder OIL_TYPE = ModFluids.FLUID_TYPES.register( "oil", () -> new FluidType(FluidType.Properties.create() .descriptionId("block.anvilcraft.oil") @@ -94,40 +94,43 @@ public class ModFluids { .sound(SoundActions.FLUID_VAPORIZE, SoundEvents.FIRE_EXTINGUISH) ) ); - public static final DeferredHolder OIL = FLUIDS + public static final DeferredHolder OIL = ModFluids.FLUIDS .register( "oil", () -> new BaseFlowingFluid.Source(ModFluids.OIL_PROPERTIES) ); - public static final DeferredHolder FLOWING_OIL = FLUIDS + public static final DeferredHolder FLOWING_OIL = ModFluids.FLUIDS .register( "flowing_oil", () -> new BaseFlowingFluid.Flowing(ModFluids.OIL_PROPERTIES) ); - public static final BaseFlowingFluid.Properties OIL_PROPERTIES = new BaseFlowingFluid.Properties(OIL_TYPE, OIL, FLOWING_OIL) + public static final BaseFlowingFluid.Properties OIL_PROPERTIES = new BaseFlowingFluid.Properties( + ModFluids.OIL_TYPE, ModFluids.OIL, ModFluids.FLOWING_OIL) .bucket(() -> ModItems.OIL_BUCKET.asItem()) .block(ModBlocks.OIL) .tickRate(10) .slopeFindDistance(3) .explosionResistance(100); - public static final Object2ObjectMap> CEMENT_TYPES = registerAllCementTypes(); - public static final Object2ObjectMap> SOURCE_CEMENTS = registerAllSourceCement(); - public static final Object2ObjectMap> FLOWING_CEMENTS = registerAllFlowingCement(); - public static final Object2ObjectMap CEMENT_PROPERTIES = createAllCementProperties(); + public static final Object2ObjectMap> CEMENT_TYPES = ModFluids.registerAllCementTypes(); + public static final Object2ObjectMap> SOURCE_CEMENTS = + ModFluids.registerAllSourceCement(); + public static final Object2ObjectMap> FLOWING_CEMENTS = + ModFluids.registerAllFlowingCement(); + public static final Object2ObjectMap CEMENT_PROPERTIES = ModFluids.createAllCementProperties(); private static Object2ObjectMap> registerAllCementTypes() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var type = registerCementType(color); + var type = ModFluids.registerCementType(color); map.put(color, type); } return map; } private static DeferredHolder registerCementType(Color color) { - return FLUID_TYPES.register( + return ModFluids.FLUID_TYPES.register( "%s_cement".formatted(color), () -> new FluidType(FluidType.Properties.create() .descriptionId("block.anvilcraft.%s_cement".formatted(color)) .fallDistanceModifier(0) @@ -143,27 +146,28 @@ private static DeferredHolder registerCementType(Color col private static Object2ObjectMap> registerAllSourceCement() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var holder = registerSourceCement(color); + var holder = ModFluids.registerSourceCement(color); map.put(color, holder); } return map; } private static DeferredHolder registerSourceCement(Color color) { - return FLUIDS.register("%s_cement".formatted(color), () -> new BaseFlowingFluid.Source(ModFluids.CEMENT_PROPERTIES.get(color))); + return ModFluids.FLUIDS.register( + "%s_cement".formatted(color), () -> new BaseFlowingFluid.Source(ModFluids.CEMENT_PROPERTIES.get(color))); } private static Object2ObjectMap> registerAllFlowingCement() { Object2ObjectMap> map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var holder = registerFlowingCement(color); + var holder = ModFluids.registerFlowingCement(color); map.put(color, holder); } return map; } private static DeferredHolder registerFlowingCement(Color color) { - return FLUIDS.register( + return ModFluids.FLUIDS.register( "flowing_%s_cement".formatted(color), () -> new BaseFlowingFluid.Flowing(ModFluids.CEMENT_PROPERTIES.get(color)) ); @@ -172,20 +176,21 @@ private static DeferredHolder registerFlowingCement(Col private static Object2ObjectMap createAllCementProperties() { Object2ObjectMap map = new Object2ObjectLinkedOpenHashMap<>(); for (Color color : Color.values()) { - var properties = createCementProperties(color); + var properties = ModFluids.createCementProperties(color); map.put(color, properties); } return map; } private static BaseFlowingFluid.Properties createCementProperties(Color color) { - return new BaseFlowingFluid.Properties(CEMENT_TYPES.get(color), SOURCE_CEMENTS.get(color), FLOWING_CEMENTS.get(color)) + return new BaseFlowingFluid.Properties( + ModFluids.CEMENT_TYPES.get(color), ModFluids.SOURCE_CEMENTS.get(color), ModFluids.FLOWING_CEMENTS.get(color)) .bucket(() -> ModItems.CEMENT_BUCKETS.get(color).asItem()) .block(ModBlocks.CEMENTS.get(color)) .explosionResistance(100); } - public static final DeferredHolder MELT_GEM_TYPE = FLUID_TYPES.register( + public static final DeferredHolder MELT_GEM_TYPE = ModFluids.FLUID_TYPES.register( "melt_gem", () -> new FluidType(FluidType.Properties.create() .descriptionId("block.anvilcraft.melt_gem") @@ -201,18 +206,18 @@ private static BaseFlowingFluid.Properties createCementProperties(Color color) { .temperature(1300) ) ); - public static final DeferredHolder MELT_GEM = FLUIDS.register( + public static final DeferredHolder MELT_GEM = ModFluids.FLUIDS.register( "melt_gem", () -> new MeltGemFluid.Source(ModFluids.MELT_GEM_PROPERTIES) ); - public static final DeferredHolder FLOWING_MELT_GEM = FLUIDS.register( + public static final DeferredHolder FLOWING_MELT_GEM = ModFluids.FLUIDS.register( "flowing_melt_gem", () -> new MeltGemFluid.Flowing(ModFluids.MELT_GEM_PROPERTIES) ); public static final BaseFlowingFluid.Properties MELT_GEM_PROPERTIES = new BaseFlowingFluid.Properties( - MELT_GEM_TYPE, - MELT_GEM, - FLOWING_MELT_GEM + ModFluids.MELT_GEM_TYPE, + ModFluids.MELT_GEM, + ModFluids.FLOWING_MELT_GEM ) .block(ModBlocks.MELT_GEM) .bucket(() -> ModItems.MELT_GEM_BUCKET.asItem()) @@ -220,26 +225,26 @@ private static BaseFlowingFluid.Properties createCementProperties(Color color) { .explosionResistance(100); // === Honey(不可放置流体,仅存在于储罐/管道中) === - public static final DeferredHolder HONEY_TYPE = FLUID_TYPES.register( + public static final DeferredHolder HONEY_TYPE = ModFluids.FLUID_TYPES.register( "honey", () -> HoneyFluid.TYPE ); - public static final DeferredHolder HONEY = FLUIDS.register( + public static final DeferredHolder HONEY = ModFluids.FLUIDS.register( "honey", HoneyFluid::new ); // === Primordial Matter(不可放置流体,仅存在于储罐/管道中) === - public static final DeferredHolder PRIMORDIAL_MATTER_TYPE = FLUID_TYPES.register( + public static final DeferredHolder PRIMORDIAL_MATTER_TYPE = ModFluids.FLUID_TYPES.register( "primordial_matter", () -> PrimordialMatterFluid.TYPE ); - public static final DeferredHolder PRIMORDIAL_MATTER = FLUIDS.register( + public static final DeferredHolder PRIMORDIAL_MATTER = ModFluids.FLUIDS.register( "primordial_matter", PrimordialMatterFluid::new ); - public static final DeferredHolder LIQUID_ENCHANTMENT_TYPE = FLUID_TYPES.register( + public static final DeferredHolder LIQUID_ENCHANTMENT_TYPE = ModFluids.FLUID_TYPES.register( "liquid_enchantment", () -> LiquidEnchantmentFluid.TYPE ); - public static final DeferredHolder LIQUID_ENCHANTMENT = FLUIDS.register( + public static final DeferredHolder LIQUID_ENCHANTMENT = ModFluids.FLUIDS.register( "liquid_enchantment", LiquidEnchantmentFluid::new ); @@ -253,8 +258,8 @@ private static BaseFlowingFluid.Properties createCementProperties(Color color) { ); public static void register(IEventBus eventBus) { - FLUID_TYPES.register(eventBus); - FLUIDS.register(eventBus); + ModFluids.FLUID_TYPES.register(eventBus); + ModFluids.FLUIDS.register(eventBus); } public static final Block[] FLOWING_MELT_GEM_CONVERTIBLE = { @@ -265,7 +270,7 @@ public static void register(IEventBus eventBus) { public static void registerFluidInteractions(FMLCommonSetupEvent ignored) { FluidInteractionRegistry.addInteraction( - MELT_GEM.get().getFluidType(), + ModFluids.MELT_GEM.get().getFluidType(), new InteractionInformation( (level, _, relativePos, _) -> level.getFluidState(relativePos).getFluidType() == Fluids.WATER.getFluidType(), @@ -274,7 +279,7 @@ public static void registerFluidInteractions(FMLCommonSetupEvent ignored) { if (level.getFluidState(currentPos).isSource()) { block = ModBlocks.CHROMATIC_STONE.get(); } else { - block = FLOWING_MELT_GEM_CONVERTIBLE[level.getRandom().nextInt(3)]; + block = ModFluids.FLOWING_MELT_GEM_CONVERTIBLE[level.getRandom().nextInt(3)]; } level.setBlockAndUpdate( currentPos, @@ -302,24 +307,24 @@ public static void registerVanilla(RegisterEvent event) { } public static void onRegisterFluidType(RegisterClientExtensionsEvent e) { - e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xC1E8A9, 1.0F), EXP_FLUID_TYPE); - e.registerFluidType(new ModClientFluidTypeExtensionImpl(0x1B061F, 1.0F), OIL_TYPE); + e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xC1E8A9, 1.0F), ModFluids.EXP_FLUID_TYPE); + e.registerFluidType(new ModClientFluidTypeExtensionImpl(0x1B061F, 1.0F), ModFluids.OIL_TYPE); for (Color color : Color.values()) { e.registerFluidType( new ModClientFluidTypeExtensionImpl( ColorUtil.mulValue(color.color().getTextColor(), 0.6F), 1.0F - ), CEMENT_TYPES.get(color) + ), ModFluids.CEMENT_TYPES.get(color) ); } - e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xB7EEDE, 2.0F), MELT_GEM_TYPE); - e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xFFC200, 1.0F), HONEY_TYPE); - e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xE6CFFF, 0.5F), PRIMORDIAL_MATTER_TYPE); + e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xB7EEDE, 2.0F), ModFluids.MELT_GEM_TYPE); + e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xFFC200, 1.0F), ModFluids.HONEY_TYPE); + e.registerFluidType(new ModClientFluidTypeExtensionImpl(0xE6CFFF, 0.5F), ModFluids.PRIMORDIAL_MATTER_TYPE); e.registerFluidType( new LiquidEnchantmentClientFluidTypeExtension(), - LIQUID_ENCHANTMENT_TYPE + ModFluids.LIQUID_ENCHANTMENT_TYPE ); - e.registerFluidType(new ModClientFluidTypeExtensionImpl(), POWDER_SNOW_TYPE); + e.registerFluidType(new ModClientFluidTypeExtensionImpl(), ModFluids.POWDER_SNOW_TYPE); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/block/ModMultiblockDefinitions.java b/src/main/java/dev/dubhe/anvilcraft/init/block/ModMultiblockDefinitions.java index eb4253aac4..f8d3c143d1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/block/ModMultiblockDefinitions.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/block/ModMultiblockDefinitions.java @@ -12,9 +12,10 @@ import net.minecraft.resources.ResourceKey; public class ModMultiblockDefinitions { - public static final ResourceKey CELESTIAL_FORGING_ANVIL = key(AnvilCraft.of("cfa")); - public static final ResourceKey FLUID_TANK = key(AnvilCraft.of("fluid_tank")); - public static final ResourceKey LARGE_FLUID_TANK = key(AnvilCraft.of("large_fluid_tank")); + public static final ResourceKey CELESTIAL_FORGING_ANVIL = ModMultiblockDefinitions.key(AnvilCraft.of("cfa")); + public static final ResourceKey FLUID_TANK = ModMultiblockDefinitions.key(AnvilCraft.of("fluid_tank")); + public static final ResourceKey LARGE_FLUID_TANK = ModMultiblockDefinitions.key( + AnvilCraft.of("large_fluid_tank")); public static void bootstrap(BootstrapContext ctx) { ctx.register( diff --git a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffectComponents.java b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffectComponents.java index 94074964c2..cb6b3a7682 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffectComponents.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffectComponents.java @@ -16,7 +16,8 @@ public class ModEnchantmentEffectComponents { private static final DeferredRegister> REGISTER = DeferredRegister.create(Registries.ENCHANTMENT_EFFECT_COMPONENT_TYPE, AnvilCraft.MOD_ID); - public static final DataComponentType>> USE_ON_BLOCK = register( + public static final DataComponentType>> USE_ON_BLOCK = + ModEnchantmentEffectComponents.register( "use_on_block", it -> it.persistent( ConditionalEffect.codec( @@ -25,7 +26,8 @@ public class ModEnchantmentEffectComponents { ) ); - public static final DataComponentType>> POST_BREAK_BLOCK = register( + public static final DataComponentType>> POST_BREAK_BLOCK = + ModEnchantmentEffectComponents.register( "post_break_block", it -> it.persistent( ConditionalEffect.codec( @@ -36,11 +38,11 @@ public class ModEnchantmentEffectComponents { private static DataComponentType register(String name, UnaryOperator> operator) { DataComponentType dct = operator.apply(DataComponentType.builder()).build(); - REGISTER.register(name, () -> dct); + ModEnchantmentEffectComponents.REGISTER.register(name, () -> dct); return dct; } public static void register(IEventBus bus) { - REGISTER.register(bus); + ModEnchantmentEffectComponents.REGISTER.register(bus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffects.java b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffects.java index 283c6ab3fb..e214580ed2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffects.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentEffects.java @@ -19,26 +19,26 @@ public class ModEnchantmentEffects { DeferredRegister.create(Registries.ENCHANTMENT_VALUE_EFFECT_TYPE, AnvilCraft.MOD_ID); static { - ENTITY_REGISTER.register( + ModEnchantmentEffects.ENTITY_REGISTER.register( "haevest_left_click", () -> HarvestLeftClickEffect.CODEC ); - ENTITY_REGISTER.register( + ModEnchantmentEffects.ENTITY_REGISTER.register( "harvest_right_click", () -> HarvestRightClickEffect.CODEC ); - ENTITY_REGISTER.register( + ModEnchantmentEffects.ENTITY_REGISTER.register( "felling", () -> FellingEffect.CODEC ); - VALUE_REGISTER.register( + ModEnchantmentEffects.VALUE_REGISTER.register( "in_range_modify", () -> InRangeModifyEffect.CODEC ); } public static void register(IEventBus eventBus) { - ENTITY_REGISTER.register(eventBus); - VALUE_REGISTER.register(eventBus); + ModEnchantmentEffects.ENTITY_REGISTER.register(eventBus); + ModEnchantmentEffects.VALUE_REGISTER.register(eventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentTags.java b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentTags.java index fc8cd18c05..e24b1e949e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentTags.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantmentTags.java @@ -7,8 +7,8 @@ import net.minecraft.world.item.enchantment.Enchantment; public class ModEnchantmentTags { - public static final TagKey DISABLED_PASSED = bind("disabled_passed"); - public static final TagKey PROVIDENCE_BONUS = bind("providence_bonus"); + public static final TagKey DISABLED_PASSED = ModEnchantmentTags.bind("disabled_passed"); + public static final TagKey PROVIDENCE_BONUS = ModEnchantmentTags.bind("providence_bonus"); public static TagKey bindC(String id) { return TagKey.create(Registries.ENCHANTMENT, Identifier.fromNamespaceAndPath("c", id)); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantments.java b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantments.java index c8433bbe04..6c4f720fe1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantments.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/enchantment/ModEnchantments.java @@ -26,11 +26,11 @@ public class ModEnchantments { - public static final ResourceKey FELLING_KEY = key("felling"); - public static final ResourceKey HARVEST_KEY = key("harvest"); - public static final ResourceKey BEHEADING_KEY = key("beheading"); - public static final ResourceKey SMELTING_KEY = key("smelting"); - public static final ResourceKey DISINTEGRATION_KEY = key("disintegration"); + public static final ResourceKey FELLING_KEY = ModEnchantments.key("felling"); + public static final ResourceKey HARVEST_KEY = ModEnchantments.key("harvest"); + public static final ResourceKey BEHEADING_KEY = ModEnchantments.key("beheading"); + public static final ResourceKey SMELTING_KEY = ModEnchantments.key("smelting"); + public static final ResourceKey DISINTEGRATION_KEY = ModEnchantments.key("disintegration"); public static ResourceKey key(String name) { return ResourceKey.create(Registries.ENCHANTMENT, AnvilCraft.of(name)); @@ -41,9 +41,9 @@ public static void bootstrap(BootstrapContext context) { HolderGetter enchantmentHolderGetter = context.lookup(Registries.ENCHANTMENT); HolderGetter itemHolderGetter = context.lookup(Registries.ITEM); HolderGetter blockHolderGetter = context.lookup(Registries.BLOCK); - register( + ModEnchantments.register( context, - FELLING_KEY, + ModEnchantments.FELLING_KEY, Enchantment.enchantment( Enchantment.definition( itemHolderGetter.getOrThrow(ItemTags.AXES), @@ -63,9 +63,9 @@ public static void bootstrap(BootstrapContext context) { ) ) ); - register( + ModEnchantments.register( context, - HARVEST_KEY, + ModEnchantments.HARVEST_KEY, Enchantment.enchantment( Enchantment.definition( itemHolderGetter.getOrThrow(ItemTags.HOES), @@ -86,9 +86,9 @@ public static void bootstrap(BootstrapContext context) { MatchTool.toolMatches(ItemPredicate.Builder.item().of(itemHolderGetter, ItemTags.HOES)) ) ); - register( + ModEnchantments.register( context, - BEHEADING_KEY, + ModEnchantments.BEHEADING_KEY, Enchantment.enchantment( Enchantment.definition( itemHolderGetter.getOrThrow(ItemTags.SWORDS), @@ -101,9 +101,9 @@ public static void bootstrap(BootstrapContext context) { ) ) ); - register( + ModEnchantments.register( context, - SMELTING_KEY, + ModEnchantments.SMELTING_KEY, Enchantment.enchantment( Enchantment.definition( itemHolderGetter.getOrThrow(ModItemTags.SMELTING_SUPPORTED), @@ -116,9 +116,9 @@ public static void bootstrap(BootstrapContext context) { ) ) ); - register( + ModEnchantments.register( context, - DISINTEGRATION_KEY, + ModEnchantments.DISINTEGRATION_KEY, Enchantment.enchantment( Enchantment.definition( itemHolderGetter.getOrThrow(ModItemTags.DISINTEGRATION_SUPPORTED), diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypeTags.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypeTags.java index 6d6e10b34e..9d44fd92bc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypeTags.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypeTags.java @@ -7,15 +7,15 @@ import net.minecraft.world.damagesource.DamageType; public class ModDamageTypeTags { - public static final TagKey AMULET_VALID = bind("amulet_valid"); - public static final TagKey TOPAZ_AMULET_VALID = bind("amulet_valid/topaz"); - public static final TagKey RUBY_AMULET_VALID = bind("amulet_valid/ruby"); - public static final TagKey SAPPHIRE_AMULET_VALID = bind("amulet_valid/sapphire"); - public static final TagKey ANVIL_AMULET_VALID = bind("amulet_valid/anvil"); - public static final TagKey FEATHER_AMULET_VALID = bind("amulet_valid/feather"); - public static final TagKey ABNORMAL_AMULET_VALID = bind("amulet_valid/abnormal"); + public static final TagKey AMULET_VALID = ModDamageTypeTags.bind("amulet_valid"); + public static final TagKey TOPAZ_AMULET_VALID = ModDamageTypeTags.bind("amulet_valid/topaz"); + public static final TagKey RUBY_AMULET_VALID = ModDamageTypeTags.bind("amulet_valid/ruby"); + public static final TagKey SAPPHIRE_AMULET_VALID = ModDamageTypeTags.bind("amulet_valid/sapphire"); + public static final TagKey ANVIL_AMULET_VALID = ModDamageTypeTags.bind("amulet_valid/anvil"); + public static final TagKey FEATHER_AMULET_VALID = ModDamageTypeTags.bind("amulet_valid/feather"); + public static final TagKey ABNORMAL_AMULET_VALID = ModDamageTypeTags.bind("amulet_valid/abnormal"); - public static final TagKey IS_FALLING_GIANT_ANVIL = bind("is_falling_giant_anvil"); + public static final TagKey IS_FALLING_GIANT_ANVIL = ModDamageTypeTags.bind("is_falling_giant_anvil"); @SuppressWarnings("unused") private static TagKey bindC(String id) { diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypes.java index e4f37b4564..bb4d12bd47 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModDamageTypes.java @@ -42,12 +42,12 @@ public class ModDamageTypes { @ApiStatus.Internal public static void bootstrap(BootstrapContext ctx) { - ctx.register(LASER, new DamageType("anvilcraft.laser", 0.1F, DamageEffects.BURNING)); - ctx.register(LOST_IN_TIME, new DamageType("anvilcraft.lost_in_time", 0.1F)); - ctx.register(FALLING_GIANT_ANVIL, new DamageType("anvilcraft.falling_giant_anvil", 0.1F)); - ctx.register(HEATER_BURN, new DamageType("anvilcraft.heater_burn", 0.1F, DamageEffects.BURNING)); - ctx.register(GAMMA_LASER, new DamageType("anvilcraft.gamma_laser", 0.1F, DamageEffects.BURNING)); - ctx.register(PLASMA_JET, new DamageType("anvilcraft.plasma_jet", 0.1F, DamageEffects.BURNING)); + ctx.register(ModDamageTypes.LASER, new DamageType("anvilcraft.laser", 0.1F, DamageEffects.BURNING)); + ctx.register(ModDamageTypes.LOST_IN_TIME, new DamageType("anvilcraft.lost_in_time", 0.1F)); + ctx.register(ModDamageTypes.FALLING_GIANT_ANVIL, new DamageType("anvilcraft.falling_giant_anvil", 0.1F)); + ctx.register(ModDamageTypes.HEATER_BURN, new DamageType("anvilcraft.heater_burn", 0.1F, DamageEffects.BURNING)); + ctx.register(ModDamageTypes.GAMMA_LASER, new DamageType("anvilcraft.gamma_laser", 0.1F, DamageEffects.BURNING)); + ctx.register(ModDamageTypes.PLASMA_JET, new DamageType("anvilcraft.plasma_jet", 0.1F, DamageEffects.BURNING)); } public static DamageSource laser(Level level) { diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntities.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntities.java index 9731c5f249..f3eb55aae1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntities.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntities.java @@ -39,13 +39,13 @@ public class ModEntities { public static final EntityEntry RAILGUN_ANVIL = AnvilCraft.REGISTRUM - .entity("railgun_anvil", RailgunAnvilEntity::new, MobCategory.MISC) + .entity("railgun_anvil", RailgunAnvilEntity::new, MobCategory.MISC) .properties(builder -> builder.sized(0.98F, 0.98F).clientTrackingRange(80).updateInterval(1).noLootTable()) .renderer(() -> RailgunAnvilRenderer::new) .register(); public static final EntityEntry WEAPON_BEAM = AnvilCraft.REGISTRUM - .entity("weapon_beam", WeaponBeamEntity::new, MobCategory.MISC) + .entity("weapon_beam", WeaponBeamEntity::new, MobCategory.MISC) .properties(builder -> builder.sized(0.01F, 0.01F).clientTrackingRange(80).updateInterval(1).noLootTable()) .renderer(() -> WeaponBeamRenderer::new) .register(); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntitySubPredicates.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntitySubPredicates.java index a7c2fb81e4..1b8488a860 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntitySubPredicates.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntitySubPredicates.java @@ -15,7 +15,9 @@ public class ModEntitySubPredicates { AnvilCraft.MOD_ID ); - public static final DeferredHolder, MapCodec> FALLING_BLOCK = REGISTER + public static final DeferredHolder< + MapCodec, MapCodec + > FALLING_BLOCK = ModEntitySubPredicates.REGISTER .register("falling_block", () -> FallingBlockPredicate.CODEC); public static void register(IEventBus modEventBus) { diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntityTypeTags.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntityTypeTags.java index 542bcdc1f7..8c4470838a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntityTypeTags.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModEntityTypeTags.java @@ -7,15 +7,17 @@ import net.minecraft.world.entity.EntityType; public class ModEntityTypeTags { - public static final TagKey> AMULET_VALID = bind("amulet_valid"); - public static final TagKey> EMERALD_AMULET_VALID = bind("amulet_valid/emerald"); - public static final TagKey> SAPPHIRE_AMULET_VALID = bind("amulet_valid/sapphire"); - public static final TagKey> ANVIL_AMULET_VALID = bind("amulet_valid/anvil"); - public static final TagKey> CAT_AMULET_VALID = bind("amulet_valid/cat"); - public static final TagKey> DOG_AMULET_VALID = bind("amulet_valid/dog"); - public static final TagKey> SILENCE_AMULET_VALID = bind("amulet_valid/silence"); + public static final TagKey> AMULET_VALID = ModEntityTypeTags.bind("amulet_valid"); + public static final TagKey> EMERALD_AMULET_VALID = ModEntityTypeTags.bind("amulet_valid/emerald"); + public static final TagKey> SAPPHIRE_AMULET_VALID = ModEntityTypeTags.bind("amulet_valid/sapphire"); + public static final TagKey> ANVIL_AMULET_VALID = ModEntityTypeTags.bind("amulet_valid/anvil"); + public static final TagKey> CAT_AMULET_VALID = ModEntityTypeTags.bind("amulet_valid/cat"); + public static final TagKey> DOG_AMULET_VALID = ModEntityTypeTags.bind("amulet_valid/dog"); + public static final TagKey> SILENCE_AMULET_VALID = ModEntityTypeTags.bind("amulet_valid/silence"); - public static final TagKey> FALLING_GIANT_ANVIL_DAMAGE_IMMUNE = bind("falling_giant_anvil_damage_immune"); + public static final TagKey> FALLING_GIANT_ANVIL_DAMAGE_IMMUNE = ModEntityTypeTags.bind( + "falling_giant_anvil_damage_immune" + ); @SuppressWarnings("unused") private static TagKey> bindC(String id) { diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModTradeSets.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModTradeSets.java index c6dbea1349..2c54fb365a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModTradeSets.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModTradeSets.java @@ -13,11 +13,11 @@ public class ModTradeSets { - public static final ResourceKey JEWELER_LEVEL_1 = key("jeweler/level_1"); - public static final ResourceKey JEWELER_LEVEL_2 = key("jeweler/level_2"); - public static final ResourceKey JEWELER_LEVEL_3 = key("jeweler/level_3"); - public static final ResourceKey JEWELER_LEVEL_4 = key("jeweler/level_4"); - public static final ResourceKey JEWELER_LEVEL_5 = key("jeweler/level_5"); + public static final ResourceKey JEWELER_LEVEL_1 = ModTradeSets.key("jeweler/level_1"); + public static final ResourceKey JEWELER_LEVEL_2 = ModTradeSets.key("jeweler/level_2"); + public static final ResourceKey JEWELER_LEVEL_3 = ModTradeSets.key("jeweler/level_3"); + public static final ResourceKey JEWELER_LEVEL_4 = ModTradeSets.key("jeweler/level_4"); + public static final ResourceKey JEWELER_LEVEL_5 = ModTradeSets.key("jeweler/level_5"); public static ResourceKey key(String name) { return ResourceKey.create(Registries.TRADE_SET, AnvilCraft.of(name)); @@ -25,33 +25,33 @@ public static ResourceKey key(String name) { public static void bootstrap(BootstrapContext context) { // Level 1: 2 trades - register(context, JEWELER_LEVEL_1, HolderSet.direct( + ModTradeSets.register(context, ModTradeSets.JEWELER_LEVEL_1, HolderSet.direct( context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.AMETHYST_SHARD_FOR_EMERALD), context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.EMERALD_FOR_TINTED_GLASS) )); // Level 2: 2 trades - register(context, JEWELER_LEVEL_2, HolderSet.direct( + ModTradeSets.register(context, ModTradeSets.JEWELER_LEVEL_2, HolderSet.direct( context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.SEA_LANTERN_FOR_EMERALD), context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.AMBER_FOR_EMERALD) )); // Level 3: 2 random gem trades; the template trade is added separately - register(context, JEWELER_LEVEL_3, HolderSet.direct( + ModTradeSets.register(context, ModTradeSets.JEWELER_LEVEL_3, HolderSet.direct( context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.TOPAZ_BLOCK_FOR_EMERALD), context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.SAPPHIRE_BLOCK_FOR_EMERALD), context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.RUBY_BLOCK_FOR_EMERALD) )); // Level 4: 3 trades - register(context, JEWELER_LEVEL_4, HolderSet.direct( + ModTradeSets.register(context, ModTradeSets.JEWELER_LEVEL_4, HolderSet.direct( context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.NAUTILUS_SHELL_FOR_EMERALD), context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.MOB_AMBER_FOR_EMERALD), context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.RESENTFUL_AMBER_FOR_EMERALD) )); // Level 5: 2 trades - register(context, JEWELER_LEVEL_5, HolderSet.direct( + ModTradeSets.register(context, ModTradeSets.JEWELER_LEVEL_5, HolderSet.direct( context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.EMERALD_FOR_GEODE), context.lookup(Registries.VILLAGER_TRADE).getOrThrow(ModVillagerTrades.EMERALD_FOR_AMULET_BOX) )); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagerTrades.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagerTrades.java index 924b1ad464..b35078ba17 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagerTrades.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagerTrades.java @@ -17,27 +17,31 @@ public class ModVillagerTrades { // Level 1 - public static final ResourceKey AMETHYST_SHARD_FOR_EMERALD = key("jeweler/amethyst_shard_for_emerald"); - public static final ResourceKey EMERALD_FOR_TINTED_GLASS = key("jeweler/emerald_for_tinted_glass"); + public static final ResourceKey AMETHYST_SHARD_FOR_EMERALD = ModVillagerTrades.key("jeweler/amethyst_shard_for_emerald"); + public static final ResourceKey EMERALD_FOR_TINTED_GLASS = ModVillagerTrades.key("jeweler/emerald_for_tinted_glass"); // Level 2 - public static final ResourceKey SEA_LANTERN_FOR_EMERALD = key("jeweler/sea_lantern_for_emerald"); - public static final ResourceKey AMBER_FOR_EMERALD = key("jeweler/amber_for_emerald"); + public static final ResourceKey SEA_LANTERN_FOR_EMERALD = ModVillagerTrades.key("jeweler/sea_lantern_for_emerald"); + public static final ResourceKey AMBER_FOR_EMERALD = ModVillagerTrades.key("jeweler/amber_for_emerald"); // Level 3 - public static final ResourceKey TOPAZ_BLOCK_FOR_EMERALD = key("jeweler/topaz_block_for_emerald"); - public static final ResourceKey SAPPHIRE_BLOCK_FOR_EMERALD = key("jeweler/sapphire_block_for_emerald"); - public static final ResourceKey RUBY_BLOCK_FOR_EMERALD = key("jeweler/ruby_block_for_emerald"); - public static final ResourceKey EMERALD_FOR_ROYAL_STEEL_TEMPLATE = key("jeweler/emerald_for_royal_steel_template"); + public static final ResourceKey TOPAZ_BLOCK_FOR_EMERALD = ModVillagerTrades.key("jeweler/topaz_block_for_emerald"); + public static final ResourceKey SAPPHIRE_BLOCK_FOR_EMERALD = ModVillagerTrades.key("jeweler/sapphire_block_for_emerald"); + public static final ResourceKey RUBY_BLOCK_FOR_EMERALD = ModVillagerTrades.key("jeweler/ruby_block_for_emerald"); + public static final ResourceKey EMERALD_FOR_ROYAL_STEEL_TEMPLATE = ModVillagerTrades.key( + "jeweler/emerald_for_royal_steel_template" + ); // Level 4 - public static final ResourceKey NAUTILUS_SHELL_FOR_EMERALD = key("jeweler/nautilus_shell_for_emerald"); - public static final ResourceKey MOB_AMBER_FOR_EMERALD = key("jeweler/mob_amber_for_emerald"); - public static final ResourceKey RESENTFUL_AMBER_FOR_EMERALD = key("jeweler/resentful_amber_for_emerald"); + public static final ResourceKey NAUTILUS_SHELL_FOR_EMERALD = ModVillagerTrades.key("jeweler/nautilus_shell_for_emerald"); + public static final ResourceKey MOB_AMBER_FOR_EMERALD = ModVillagerTrades.key("jeweler/mob_amber_for_emerald"); + public static final ResourceKey RESENTFUL_AMBER_FOR_EMERALD = ModVillagerTrades.key( + "jeweler/resentful_amber_for_emerald" + ); // Level 5 - public static final ResourceKey EMERALD_FOR_GEODE = key("jeweler/emerald_for_geode"); - public static final ResourceKey EMERALD_FOR_AMULET_BOX = key("jeweler/emerald_for_amulet_box"); + public static final ResourceKey EMERALD_FOR_GEODE = ModVillagerTrades.key("jeweler/emerald_for_geode"); + public static final ResourceKey EMERALD_FOR_AMULET_BOX = ModVillagerTrades.key("jeweler/emerald_for_amulet_box"); public static ResourceKey key(String name) { return ResourceKey.create(Registries.VILLAGER_TRADE, AnvilCraft.of(name)); @@ -45,66 +49,66 @@ public static ResourceKey key(String name) { public static void bootstrap(BootstrapContext context) { // Level 1 - register(context, AMETHYST_SHARD_FOR_EMERALD, - new TradeCost(Items.AMETHYST_SHARD, 4), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD), 16, 2, 0.05F); - register(context, EMERALD_FOR_TINTED_GLASS, - new TradeCost(Items.EMERALD, 1), - Optional.empty(), - new ItemStackTemplate(Items.TINTED_GLASS), 12, 4, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.AMETHYST_SHARD_FOR_EMERALD, + new TradeCost(Items.AMETHYST_SHARD, 4), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD), 16, 2, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.EMERALD_FOR_TINTED_GLASS, + new TradeCost(Items.EMERALD, 1), + Optional.empty(), + new ItemStackTemplate(Items.TINTED_GLASS), 12, 4, 0.05F); // Level 2 - register(context, SEA_LANTERN_FOR_EMERALD, - new TradeCost(Items.SEA_LANTERN, 8), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD), 12, 10, 0.05F); - register(context, AMBER_FOR_EMERALD, - new TradeCost(ModItems.AMBER, 4), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD), 16, 5, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.SEA_LANTERN_FOR_EMERALD, + new TradeCost(Items.SEA_LANTERN, 8), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD), 12, 10, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.AMBER_FOR_EMERALD, + new TradeCost(ModItems.AMBER, 4), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD), 16, 5, 0.05F); // Level 3 - register(context, TOPAZ_BLOCK_FOR_EMERALD, - new TradeCost(ModBlocks.TOPAZ_BLOCK.get().asItem(), 1), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD, 8), 8, 10, 0.05F); - register(context, SAPPHIRE_BLOCK_FOR_EMERALD, - new TradeCost(ModBlocks.SAPPHIRE_BLOCK.get().asItem(), 1), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD, 8), 8, 10, 0.05F); - register(context, RUBY_BLOCK_FOR_EMERALD, - new TradeCost(ModBlocks.RUBY_BLOCK.get().asItem(), 1), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD, 8), 8, 10, 0.05F); - register(context, EMERALD_FOR_ROYAL_STEEL_TEMPLATE, - new TradeCost(Items.EMERALD, 40), - Optional.of(new TradeCost(ModItems.ROYAL_STEEL_INGOT, 4)), - new ItemStackTemplate(ModItems.ROYAL_STEEL_UPGRADE_SMITHING_TEMPLATE.get()), 2, 10, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.TOPAZ_BLOCK_FOR_EMERALD, + new TradeCost(ModBlocks.TOPAZ_BLOCK.get().asItem(), 1), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD, 8), 8, 10, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.SAPPHIRE_BLOCK_FOR_EMERALD, + new TradeCost(ModBlocks.SAPPHIRE_BLOCK.get().asItem(), 1), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD, 8), 8, 10, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.RUBY_BLOCK_FOR_EMERALD, + new TradeCost(ModBlocks.RUBY_BLOCK.get().asItem(), 1), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD, 8), 8, 10, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.EMERALD_FOR_ROYAL_STEEL_TEMPLATE, + new TradeCost(Items.EMERALD, 40), + Optional.of(new TradeCost(ModItems.ROYAL_STEEL_INGOT, 4)), + new ItemStackTemplate(ModItems.ROYAL_STEEL_UPGRADE_SMITHING_TEMPLATE.get()), 2, 10, 0.05F); // Level 4 - register(context, NAUTILUS_SHELL_FOR_EMERALD, - new TradeCost(Items.NAUTILUS_SHELL, 1), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD, 2), 12, 10, 0.05F); - register(context, MOB_AMBER_FOR_EMERALD, - new TradeCost(ModBlocks.MOB_AMBER_BLOCK.get().asItem(), 1), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD, 8), 2, 10, 0.05F); - register(context, RESENTFUL_AMBER_FOR_EMERALD, - new TradeCost(ModBlocks.RESENTFUL_AMBER_BLOCK.get().asItem(), 1), - Optional.empty(), - new ItemStackTemplate(Items.EMERALD, 24), 2, 30, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.NAUTILUS_SHELL_FOR_EMERALD, + new TradeCost(Items.NAUTILUS_SHELL, 1), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD, 2), 12, 10, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.MOB_AMBER_FOR_EMERALD, + new TradeCost(ModBlocks.MOB_AMBER_BLOCK.get().asItem(), 1), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD, 8), 2, 10, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.RESENTFUL_AMBER_FOR_EMERALD, + new TradeCost(ModBlocks.RESENTFUL_AMBER_BLOCK.get().asItem(), 1), + Optional.empty(), + new ItemStackTemplate(Items.EMERALD, 24), 2, 30, 0.05F); // Level 5 - register(context, EMERALD_FOR_GEODE, - new TradeCost(Items.EMERALD, 64), - Optional.of(new TradeCost(Items.SMOOTH_BASALT.asItem(), 32)), - new ItemStackTemplate(ModItems.GEODE.get()), 4, 30, 0.05F); - register(context, EMERALD_FOR_AMULET_BOX, - new TradeCost(Items.EMERALD, 64), - Optional.of(new TradeCost(Items.TOTEM_OF_UNDYING, 1)), - new ItemStackTemplate(ModItems.AMULET_BOX.get()), 1, 30, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.EMERALD_FOR_GEODE, + new TradeCost(Items.EMERALD, 64), + Optional.of(new TradeCost(Items.SMOOTH_BASALT.asItem(), 32)), + new ItemStackTemplate(ModItems.GEODE.get()), 4, 30, 0.05F); + ModVillagerTrades.register(context, ModVillagerTrades.EMERALD_FOR_AMULET_BOX, + new TradeCost(Items.EMERALD, 64), + Optional.of(new TradeCost(Items.TOTEM_OF_UNDYING, 1)), + new ItemStackTemplate(ModItems.AMULET_BOX.get()), 1, 30, 0.05F); } private static void register( diff --git a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagers.java b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagers.java index 8d962d8363..96faffb707 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagers.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/entity/ModVillagers.java @@ -22,7 +22,7 @@ public class ModVillagers { public static final DeferredRegister VILLAGER_PROFESSIONS = DeferredRegister.create(Registries.VILLAGER_PROFESSION, AnvilCraft.MOD_ID); - public static final DeferredHolder JEWELER_POI = POI_TYPES.register( + public static final DeferredHolder JEWELER_POI = ModVillagers.POI_TYPES.register( "jeweler_poi", () -> new PoiType( ImmutableSet.copyOf(ModBlocks.JEWEL_CRAFTING_TABLE @@ -32,7 +32,7 @@ public class ModVillagers { 1, 1)); - public static final DeferredHolder TRADING_STATION_POI = POI_TYPES.register( + public static final DeferredHolder TRADING_STATION_POI = ModVillagers.POI_TYPES.register( "trading_station_poi", () -> new PoiType(ImmutableSet.copyOf(ModBlocks.TRADING_STATION.get().getBottomStates()), 1, 1) ); @@ -42,12 +42,12 @@ public class ModVillagers { AnvilCraft.of("jeweler") ); - public static final DeferredHolder JEWELER = VILLAGER_PROFESSIONS.register( + public static final DeferredHolder JEWELER = ModVillagers.VILLAGER_PROFESSIONS.register( "jeweler", () -> new VillagerProfession( Component.translatable("entity.anvilcraft.villager.jeweler"), - entry -> entry.is(JEWELER_POI.getKey()), - entry -> entry.is(JEWELER_POI.getKey()), + entry -> entry.is(ModVillagers.JEWELER_POI.getKey()), + entry -> entry.is(ModVillagers.JEWELER_POI.getKey()), ImmutableSet.of(), ImmutableSet.of(), SoundEvents.VILLAGER_WORK_TOOLSMITH, @@ -61,7 +61,7 @@ public class ModVillagers { )); public static void register(IEventBus eventBus) { - POI_TYPES.register(eventBus); - VILLAGER_PROFESSIONS.register(eventBus); + ModVillagers.POI_TYPES.register(eventBus); + ModVillagers.VILLAGER_PROFESSIONS.register(eventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletDefinitionTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletDefinitionTypes.java index 3c705b4fac..de40673df9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletDefinitionTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletDefinitionTypes.java @@ -16,15 +16,18 @@ public class ModAmuletDefinitionTypes { AnvilCraft.MOD_ID ); - public static final DeferredHolder, AmuletDefinition.Type> NORMAL = REGISTER.register( + public static final DeferredHolder, AmuletDefinition.Type> NORMAL = + ModAmuletDefinitionTypes.REGISTER.register( "normal", AmuletDefinition.Type::new ); - public static final DeferredHolder, ComradeAmuletDefinition.Type> COMRADE = REGISTER.register( + public static final DeferredHolder, ComradeAmuletDefinition.Type> COMRADE = + ModAmuletDefinitionTypes.REGISTER.register( "comrade", ComradeAmuletDefinition.Type::new ); - public static final DeferredHolder, AbnormalAmuletDefinition.Type> ABNORMAL = REGISTER.register( + public static final DeferredHolder, AbnormalAmuletDefinition.Type> ABNORMAL = + ModAmuletDefinitionTypes.REGISTER.register( "abnormal", AbnormalAmuletDefinition.Type::new ); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletTypes.java index 0612da638f..5d7c365f0d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModAmuletTypes.java @@ -21,40 +21,40 @@ public class ModAmuletTypes { AnvilCraft.MOD_ID ); - public static final DeferredHolder, DiscountAmulet.Type> DISCOUNT = REGISTER.register( + public static final DeferredHolder, DiscountAmulet.Type> DISCOUNT = ModAmuletTypes.REGISTER.register( "discount", DiscountAmulet.Type::new ); - public static final DeferredHolder, ImmuneDamageAmulet.Type> IMMUNE_DAMAGE = REGISTER.register( + public static final DeferredHolder, ImmuneDamageAmulet.Type> IMMUNE_DAMAGE = ModAmuletTypes.REGISTER.register( "immune_damage", ImmuneDamageAmulet.Type::new ); - public static final DeferredHolder, ImmuneEntityAmulet.Type> IMMUNE_ENTITY = REGISTER.register( + public static final DeferredHolder, ImmuneEntityAmulet.Type> IMMUNE_ENTITY = ModAmuletTypes.REGISTER.register( "immune_entity", ImmuneEntityAmulet.Type::new ); - public static final DeferredHolder, GiveEffectAmulet.Type> GIVE_EFFECT = REGISTER.register( + public static final DeferredHolder, GiveEffectAmulet.Type> GIVE_EFFECT = ModAmuletTypes.REGISTER.register( "give_effect", GiveEffectAmulet.Type::new ); - public static final DeferredHolder, WrappedOthersAmulet.Type> WRAPPED_OTHERS = REGISTER.register( + public static final DeferredHolder, WrappedOthersAmulet.Type> WRAPPED_OTHERS = ModAmuletTypes.REGISTER.register( "wrapped_others", WrappedOthersAmulet.Type::new ); - public static final DeferredHolder, ComradeAmulet.Type> COMRADE = REGISTER.register( + public static final DeferredHolder, ComradeAmulet.Type> COMRADE = ModAmuletTypes.REGISTER.register( "comrade", ComradeAmulet.Type::new ); - public static final DeferredHolder, AnvilAmulet.Type> ANVIL = REGISTER.register( + public static final DeferredHolder, AnvilAmulet.Type> ANVIL = ModAmuletTypes.REGISTER.register( "anvil", AnvilAmulet.Type::new ); - public static final DeferredHolder, DoNothingAmulet.Type> DO_NOTHING = REGISTER.register( + public static final DeferredHolder, DoNothingAmulet.Type> DO_NOTHING = ModAmuletTypes.REGISTER.register( "do_nothing", DoNothingAmulet.Type::new ); public static void register(IEventBus modEventBus) { - REGISTER.register(modEventBus); + ModAmuletTypes.REGISTER.register(modEventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModComponents.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModComponents.java index 2eb70b63c9..1e639b4b0d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModComponents.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModComponents.java @@ -47,161 +47,161 @@ public class ModComponents { Registries.DATA_COMPONENT_TYPE, AnvilCraft.MOD_ID ); - public static final DataComponentType DISK_DATA = register( + public static final DataComponentType DISK_DATA = ModComponents.register( "disk_data", b -> b.persistent(DiskData.CODEC).networkSynchronized(DiskData.STREAM_CODEC) ); - public static final DataComponentType SAVED_ENTITY = register( + public static final DataComponentType SAVED_ENTITY = ModComponents.register( "saved_entity", b -> b.persistent(SavedEntity.CODEC).networkSynchronized(SavedEntity.STREAM_CODEC) ); - public static final DataComponentType HELIOSTATS_DATA = register( + public static final DataComponentType HELIOSTATS_DATA = ModComponents.register( "heliostats_data", b -> b.persistent(HeliostatsData.CODEC).networkSynchronized(HeliostatsData.STREAM_CODEC) ); - public static final DataComponentType STRUCTURE_DATA = register( + public static final DataComponentType STRUCTURE_DATA = ModComponents.register( "structure_data", b -> b.persistent(StructureData.CODEC).networkSynchronized(StructureData.STREAM_CODEC) ); - public static final DataComponentType STRUCTURE_DISK_DATA = register( + public static final DataComponentType STRUCTURE_DISK_DATA = ModComponents.register( "structure_disk_data", b -> b.persistent(StructureDiskData.CODEC).networkSynchronized(StructureDiskData.STREAM_CODEC) ); - public static final DataComponentType DISPLAY_ITEM = register( + public static final DataComponentType DISPLAY_ITEM = ModComponents.register( "display_item", b -> b.persistent(StoredItem.CODEC).networkSynchronized(StoredItem.STREAM_CODEC) ); - public static final DataComponentType FLIGHT_TIME = register( + public static final DataComponentType FLIGHT_TIME = ModComponents.register( "flight_time", it -> it.persistent(FlightTime.CODEC.codec()).networkSynchronized(FlightTime.STREAM_CODEC) ); - public static final DataComponentType STORED_ENERGY = register( + public static final DataComponentType STORED_ENERGY = ModComponents.register( "stored_energy", builder -> builder.persistent(StoredEnergy.CODEC.codec()).networkSynchronized(StoredEnergy.STREAM_CODEC) ); - public static final DataComponentType RAILGUN_AMMO = register( + public static final DataComponentType RAILGUN_AMMO = ModComponents.register( "railgun_ammo", builder -> builder.persistent(ChargedProjectiles.CODEC).networkSynchronized(ChargedProjectiles.STREAM_CODEC) ); - public static final DataComponentType RAILGUN_INFINITE_AMMO_MASK = register( + public static final DataComponentType RAILGUN_INFINITE_AMMO_MASK = ModComponents.register( "railgun_infinite_ammo_mask", builder -> builder.persistent(Codec.INT).networkSynchronized(ByteBufCodecs.INT) ); - public static final DataComponentType FIRE_REFORGING = registerEmpty("reforging"); + public static final DataComponentType FIRE_REFORGING = ModComponents.registerEmpty("reforging"); - public static final DataComponentType MULTIPHASE = register( + public static final DataComponentType MULTIPHASE = ModComponents.register( "multiphase", b -> b.persistent(Multiphase.CODEC.codec()).networkSynchronized(Multiphase.STREAM_CODEC) ); - public static final DataComponentType MERCILESS = register( + public static final DataComponentType MERCILESS = ModComponents.register( "merciless", b -> b.persistent(Merciless.CODEC.codec()).networkSynchronized(Merciless.STREAM_CODEC) ); - public static final DataComponentType FEROCIOUS = register( + public static final DataComponentType FEROCIOUS = ModComponents.register( "ferocious", b -> b.persistent(Ferocious.CODEC.codec()).networkSynchronized(Ferocious.STREAM_CODEC) ); - public static final DataComponentType DEVOUR_RANGE = register( + public static final DataComponentType DEVOUR_RANGE = ModComponents.register( "devour_range", b -> b.persistent(DevourRange.CODEC).networkSynchronized(DevourRange.STREAM_CODEC) ); - public static final DataComponentType BOX_CONTENTS = register( + public static final DataComponentType BOX_CONTENTS = ModComponents.register( "box_contents", b -> b.persistent(BoxContents.CODEC).networkSynchronized(BoxContents.STREAM_CODEC) ); - public static final DataComponentType ETERNAL = register( + public static final DataComponentType ETERNAL = ModComponents.register( "eternal", b -> b.persistent(Eternal.CODEC.codec()).networkSynchronized(Eternal.STREAM_CODEC) ); - public static final DataComponentType PROVIDENCE = registerEmpty("providence"); + public static final DataComponentType PROVIDENCE = ModComponents.registerEmpty("providence"); - public static final DataComponentType FILTER_CONTENT = register( + public static final DataComponentType FILTER_CONTENT = ModComponents.register( "filter_contents", b -> b.persistent(FilterContent.CODEC.codec()).networkSynchronized(FilterContent.STREAM_CODEC) ); - public static final DataComponentType MERCILESS_ENCHANTMENTS = register( + public static final DataComponentType MERCILESS_ENCHANTMENTS = ModComponents.register( "merciless_enchantments", b -> b.persistent(ItemEnchantments.CODEC).networkSynchronized(ItemEnchantments.STREAM_CODEC) ); - public static final DataComponentType DISABLED_ENCHANTMENTS = register( + public static final DataComponentType DISABLED_ENCHANTMENTS = ModComponents.register( "disabled_enchantments", b -> b.persistent(ItemEnchantments.CODEC).networkSynchronized(ItemEnchantments.STREAM_CODEC) ); - public static final DataComponentType> LIQUID_ENCHANTMENT = register( + public static final DataComponentType> LIQUID_ENCHANTMENT = ModComponents.register( "liquid_enchantment", b -> b.persistent(Enchantment.CODEC).networkSynchronized(Enchantment.STREAM_CODEC) ); - public static final DataComponentType CAN_TAKE_OUT_AMMO = register( + public static final DataComponentType CAN_TAKE_OUT_AMMO = ModComponents.register( "can_take_out_ammo", it -> it.persistent(CanTakeOutAmmo.CODEC).networkSynchronized(CanTakeOutAmmo.STREAM_CODEC) ); - public static final DataComponentType WEAKENING = register( + public static final DataComponentType WEAKENING = ModComponents.register( "weakening", b -> b.persistent(Codec.BOOL).networkSynchronized(ByteBufCodecs.BOOL) ); - public static final DataComponentType PILL_BOX_CONTENTS = register( + public static final DataComponentType PILL_BOX_CONTENTS = ModComponents.register( "pill_box_contents", builder -> builder.persistent(PillBoxContents.CODEC).networkSynchronized(PillBoxContents.STREAM_CODEC) ); - public static final DataComponentType OVER_LIMIT_CONTAINER = register( + public static final DataComponentType OVER_LIMIT_CONTAINER = ModComponents.register( "over_limit_item_container_contents", b -> b.persistent(OverLimitItemContainerContents.CODEC).networkSynchronized(OverLimitItemContainerContents.STREAM_CODEC) ); - public static final DataComponentType RESONATE_MODE = register( + public static final DataComponentType RESONATE_MODE = ModComponents.register( "resonate_mode", b -> b.persistent(ResonateMode.CODEC).networkSynchronized(ResonateMode.STREAM_CODEC) ); - public static final DataComponentType MULTITOOL_MODE = register( + public static final DataComponentType MULTITOOL_MODE = ModComponents.register( "multitool_mode", b -> b.persistent(MultitoolMode.CODEC).networkSynchronized(MultitoolMode.STREAM_CODEC) ); - public static final DataComponentType HEAVY_HALBERD_MODE = register( + public static final DataComponentType HEAVY_HALBERD_MODE = ModComponents.register( "heavy_halberd_mode", b -> b.persistent(HeavyHalberdMode.CODEC).networkSynchronized(HeavyHalberdMode.STREAM_CODEC) ); - public static final DataComponentType BURNING_HEATER_CONTENTS = register( + public static final DataComponentType BURNING_HEATER_CONTENTS = ModComponents.register( "burning_heater_contents", b -> b.persistent(ItemContainerContents.CODEC).networkSynchronized(ItemContainerContents.STREAM_CODEC) ); - public static final DataComponentType CREATIVE_TANK_FLUIDS = register( + public static final DataComponentType CREATIVE_TANK_FLUIDS = ModComponents.register( "creative_tank_fluids", b -> b.persistent(StoredFluids.CODEC).networkSynchronized(StoredFluids.STREAM_CODEC) ); - public static final DataComponentType AMULET = register( + public static final DataComponentType AMULET = ModComponents.register( "amulet", b -> b.persistent(IAmulet.CODEC).networkSynchronized(IAmulet.STREAM_CODEC) ); - public static final DataComponentType STORAGE = register( + public static final DataComponentType STORAGE = ModComponents.register( "storage", b -> b.persistent(StorageRef.CODEC.codec()).networkSynchronized(StorageRef.STREAM_CODEC) ); @@ -210,17 +210,17 @@ private static DataComponentType register(String name, Consumerbuilder(); customizer.accept(builder); var componentType = builder.build(); - DR.register(name, () -> componentType); + ModComponents.DR.register(name, () -> componentType); return componentType; } public static void register(IEventBus bus) { - DR.register(bus); + ModComponents.DR.register(bus); } @SuppressWarnings("SameParameterValue") private static DataComponentType registerEmpty(String name) { - return register( + return ModComponents.register( name, b -> b.persistent(MapCodec.unit(Unit.INSTANCE).codec()).networkSynchronized(StreamCodec.unit(Unit.INSTANCE)) ); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModConsumeEffects.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModConsumeEffects.java index 9e6b30aa97..d674e46622 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModConsumeEffects.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModConsumeEffects.java @@ -18,37 +18,37 @@ public class ModConsumeEffects { AnvilCraft.MOD_ID ); - public static final DeferredHolder, ConsumeEffect.Type> TP_TO_RESPAWN = DF - .register("tp_to_respawn", () -> new ConsumeEffect.Type<>( + public static final DeferredHolder, ConsumeEffect.Type> + TP_TO_RESPAWN = ModConsumeEffects.DF.register("tp_to_respawn", () -> new ConsumeEffect.Type<>( TeleportToRespawnPointConsumeEffect.CODEC, TeleportToRespawnPointConsumeEffect.STREAM_CODEC.cast() )); - public static final DeferredHolder, ConsumeEffect.Type> SET_FOOD_LEVEL = DF - .register("set_food_level", () -> new ConsumeEffect.Type<>( + public static final DeferredHolder, ConsumeEffect.Type> + SET_FOOD_LEVEL = ModConsumeEffects.DF.register("set_food_level", () -> new ConsumeEffect.Type<>( SetFoodLevelConsumeEffect.CODEC, SetFoodLevelConsumeEffect.STREAM_CODEC.cast() )); - public static final DeferredHolder, ConsumeEffect.Type> TRY_TOTEMS_IN_BOX = DF - .register("try_totems_in_box", () -> new ConsumeEffect.Type<>( + public static final DeferredHolder, ConsumeEffect.Type> + TRY_TOTEMS_IN_BOX = ModConsumeEffects.DF.register("try_totems_in_box", () -> new ConsumeEffect.Type<>( TryTotemsInBoxConsumeEffect.CODEC, TryTotemsInBoxConsumeEffect.STREAM_CODEC.cast() )); - public static final DeferredHolder, ConsumeEffect.Type> PREVENT_SHRINKING = DF - .register("prevent_shrinking", () -> new ConsumeEffect.Type<>( + public static final DeferredHolder, ConsumeEffect.Type> + PREVENT_SHRINKING = ModConsumeEffects.DF.register("prevent_shrinking", () -> new ConsumeEffect.Type<>( PreventShrinkingConsumeEffect.CODEC, PreventShrinkingConsumeEffect.STREAM_CODEC.cast() )); - public static final DeferredHolder, ConsumeEffect.Type> SET_RAGED = DF + public static final DeferredHolder, ConsumeEffect.Type> SET_RAGED = ModConsumeEffects.DF .register("set_raged", () -> new ConsumeEffect.Type<>( SetRagedConsumeEffect.CODEC, SetRagedConsumeEffect.STREAM_CODEC.cast() )); public static void register(IEventBus bus) { - DF.register(bus); + ModConsumeEffects.DF.register(bus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModCustomDataComponents.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModCustomDataComponents.java index 4d0099c6bd..e598c698f3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModCustomDataComponents.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModCustomDataComponents.java @@ -14,16 +14,16 @@ public class ModCustomDataComponents { private static final DeferredRegister> DF = DeferredRegister .create(ModRegistries.CUSTOM_DATA_TYPE, AnvilCraft.MOD_ID); - public static final DeferredHolder, NormalDataComponent.Type> NORMAL = DF + public static final DeferredHolder, NormalDataComponent.Type> NORMAL = ModCustomDataComponents.DF .register("normal_data_component", NormalDataComponent.Type::new); - public static final DeferredHolder, ItemEnchantmentsData.Type> ITEM_ENCHANTMENTS = DF - .register("item_enchantments", ItemEnchantmentsData.Type::new); + public static final DeferredHolder, ItemEnchantmentsData.Type> ITEM_ENCHANTMENTS = + ModCustomDataComponents.DF.register("item_enchantments", ItemEnchantmentsData.Type::new); - public static final DeferredHolder, MultiphaseData.Type> MULTIPHASE = DF + public static final DeferredHolder, MultiphaseData.Type> MULTIPHASE = ModCustomDataComponents.DF .register("multiphase", MultiphaseData.Type::new); public static void register(IEventBus bus) { - DF.register(bus); + ModCustomDataComponents.DF.register(bus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModDataComponentPredicates.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModDataComponentPredicates.java index 7d8af39f66..7190b1bd9d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModDataComponentPredicates.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModDataComponentPredicates.java @@ -19,19 +19,19 @@ public class ModDataComponentPredicates { ); public static final DeferredHolder, DataComponentPredicate.Type> SAVED_ENTITY = - register( + ModDataComponentPredicates.register( "saved_entity", ItemSavedEntityPredicate.CODEC ); public static final DeferredHolder, DataComponentPredicate.Type> ENCH_COUNT = - register( + ModDataComponentPredicates.register( "enchantment_count", ItemEnchCountPredicate.CODEC.codec() ); public static final DeferredHolder, DataComponentPredicate.Type> INT_COMP = - register( + ModDataComponentPredicates.register( "integer_component", IntegerComponentPredicate.CODEC.codec() ); @@ -39,7 +39,7 @@ public class ModDataComponentPredicates { public static final DeferredHolder< DataComponentPredicate.Type, DataComponentPredicate.Type - > MERCILESS_ENCH = register( + > MERCILESS_ENCH = ModDataComponentPredicates.register( "merciless_enchantment", ExtraEnchantmentsPredicate.MercilessEnchantments.CODEC ); @@ -47,7 +47,7 @@ public class ModDataComponentPredicates { public static final DeferredHolder< DataComponentPredicate.Type, DataComponentPredicate.Type - > DISABLED_ENCH = register( + > DISABLED_ENCH = ModDataComponentPredicates.register( "disabled_enchantment", ExtraEnchantmentsPredicate.DisabledEnchantments.CODEC ); @@ -57,11 +57,11 @@ DeferredHolder, DataComponentPredicate.Type> r String name, Codec codec ) { - return DF.register(name, () -> new DataComponentPredicate.TypeBase<>(codec) { + return ModDataComponentPredicates.DF.register(name, () -> new DataComponentPredicate.TypeBase<>(codec) { }); } public static void initialize(IEventBus modEventBus) { - DF.register(modEventBus); + ModDataComponentPredicates.DF.register(modEventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemGroups.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemGroups.java index 81dac92a6c..841aeca06c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemGroups.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemGroups.java @@ -20,7 +20,7 @@ public class ModItemGroups { private static final DeferredRegister DF = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, AnvilCraft.MOD_ID); - public static final DeferredHolder ANVILCRAFT_TOOL = DF.register( + public static final DeferredHolder ANVILCRAFT_TOOL = ModItemGroups.DF.register( "tools_and_utilities", () -> CreativeModeTab.builder() .icon(ModItems.ANVIL_HAMMER::asStack) @@ -35,39 +35,43 @@ public class ModItemGroups { .build() ); - public static final DeferredHolder ANVILCRAFT_INGREDIENTS = DF.register( + public static final DeferredHolder ANVILCRAFT_INGREDIENTS = ModItemGroups.DF.register( "ingredients", () -> CreativeModeTab.builder() .icon(ModItems.MAGNET_INGOT::asStack) .displayItems(new Ingredients()) .title(REGISTRUM.addLang("itemGroup", AnvilCraft.of("ingredients"), "AnvilCraft: Ingredients")) - .withTabsBefore(ANVILCRAFT_TOOL.getId()) + .withTabsBefore(ModItemGroups.ANVILCRAFT_TOOL.getId()) .withTabsAfter(AnvilCraft.of("functional_blocks"), AnvilCraft.of("building_blocks")) .build() ); - public static final DeferredHolder ANVILCRAFT_FUNCTION_BLOCK = DF.register( + public static final DeferredHolder ANVILCRAFT_FUNCTION_BLOCK = ModItemGroups.DF.register( "functional_blocks", () -> CreativeModeTab.builder() .icon(ModBlocks.ROYAL_ANVIL::asStack) .displayItems(new FunctionalBlocks()) .title(REGISTRUM.addLang("itemGroup", AnvilCraft.of("functional_blocks"), "AnvilCraft: Functional Blocks")) - .withTabsBefore(ANVILCRAFT_TOOL.getId(), ANVILCRAFT_INGREDIENTS.getId()) + .withTabsBefore(ModItemGroups.ANVILCRAFT_TOOL.getId(), ModItemGroups.ANVILCRAFT_INGREDIENTS.getId()) .withTabsAfter(AnvilCraft.of("building_blocks")) .build() ); - public static final DeferredHolder ANVILCRAFT_BUILD_BLOCK = DF.register( + public static final DeferredHolder ANVILCRAFT_BUILD_BLOCK = ModItemGroups.DF.register( "building_blocks", () -> CreativeModeTab.builder() .icon(ModBlocks.REINFORCED_CONCRETES.get(Color.WHITE)::asStack) .displayItems(new BuildingBlocks()) .title(REGISTRUM.addLang("itemGroup", AnvilCraft.of("building_blocks"), "AnvilCraft: Building Blocks")) - .withTabsBefore(ANVILCRAFT_TOOL.getId(), ANVILCRAFT_INGREDIENTS.getId(), ANVILCRAFT_FUNCTION_BLOCK.getId()) + .withTabsBefore( + ModItemGroups.ANVILCRAFT_TOOL.getId(), + ModItemGroups.ANVILCRAFT_INGREDIENTS.getId(), + ModItemGroups.ANVILCRAFT_FUNCTION_BLOCK.getId() + ) .build() ); public static void register(IEventBus modEventBus) { - DF.register(modEventBus); + ModItemGroups.DF.register(modEventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemTags.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemTags.java index db55c16c2d..161d583021 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemTags.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModItemTags.java @@ -11,164 +11,164 @@ @SuppressWarnings("unused") public class ModItemTags { - public static final TagKey RESIN = bindC("resin"); - public static final TagKey WHEAT_FLOUR = bindC("flour/wheat"); - public static final TagKey WHEAT_DOUGH = bindC("dough/wheat"); - public static final TagKey CREAM = bindC("foods/cream"); - public static final TagKey FLOUR = bindC("foods/flour"); - public static final TagKey DOUGH = bindC("foods/dough"); - public static final TagKey RAW_MUTTON = bindC("foods/raw_mutton"); - public static final TagKey RAW_BEEF = bindC("foods/raw_beef"); - public static final TagKey RAW_CHICKEN = bindC("foods/raw_chicken"); - public static final TagKey RAW_PORKCHOP = bindC("foods/raw_porkchop"); - public static final TagKey RAW_RABBIT = bindC("foods/raw_rabbit"); - - public static final TagKey PLATES = bindC("plates"); - public static final TagKey GOLD_PLATES = bindC("plates/gold"); - public static final TagKey IRON_PLATES = bindC("plates/iron"); - public static final TagKey COPPER_PLATES = bindC("plates/copper"); - public static final TagKey TUNGSTEN_PLATES = bindC("plates/tungsten"); - public static final TagKey TITANIUM_PLATES = bindC("plates/titanium"); - public static final TagKey ZINC_PLATES = bindC("plates/zinc"); - public static final TagKey TIN_PLATES = bindC("plates/tin"); - public static final TagKey LEAD_PLATES = bindC("plates/lead"); - public static final TagKey SILVER_PLATES = bindC("plates/silver"); - public static final TagKey URANIUM_PLATES = bindC("plates/uranium"); - public static final TagKey BRONZE_PLATES = bindC("plates/bronze"); - public static final TagKey BRASS_PLATES = bindC("plates/brass"); - - public static final TagKey STORAGE_BLOCKS_TUNGSTEN = bindC("storage_blocks/tungsten"); - public static final TagKey STORAGE_BLOCKS_TITANIUM = bindC("storage_blocks/titanium"); - public static final TagKey STORAGE_BLOCKS_ZINC = bindC("storage_blocks/zinc"); - public static final TagKey STORAGE_BLOCKS_TIN = bindC("storage_blocks/tin"); - public static final TagKey STORAGE_BLOCKS_LEAD = bindC("storage_blocks/lead"); - public static final TagKey STORAGE_BLOCKS_SILVER = bindC("storage_blocks/silver"); - public static final TagKey STORAGE_BLOCKS_URANIUM = bindC("storage_blocks/uranium"); - public static final TagKey STORAGE_BLOCKS_PLUTONIUM = bindC("storage_blocks/plutonium"); - public static final TagKey STORAGE_BLOCKS_BRONZE = bindC("storage_blocks/bronze"); - public static final TagKey STORAGE_BLOCKS_BRASS = bindC("storage_blocks/brass"); - public static final TagKey STORAGE_BLOCKS_VOID_MATTER = bindC("storage_blocks/void_matter"); - public static final TagKey STORAGE_BLOCKS_EARTH_CORE_SHARD = bindC("storage_blocks/earth_core_shard"); - public static final TagKey STORAGE_BLOCKS_MULTIPHASE_MATTER = bindC("storage_blocks/multiphase_matter"); - public static final TagKey STORAGE_BLOCKS_MAGNET = bindC("storage_blocks/magnet"); - public static final TagKey STORAGE_BLOCKS_TOPAZ = bindC("storage_blocks/topaz"); - public static final TagKey STORAGE_BLOCKS_SAPPHIRE = bindC("storage_blocks/sapphire"); - public static final TagKey STORAGE_BLOCKS_RUBY = bindC("storage_blocks/ruby"); - public static final TagKey STORAGE_BLOCKS_EXP_GEM = bindC("storage_blocks/exp_gem"); - public static final TagKey STORAGE_BLOCKS_AMBER = bindC("storage_blocks/amber"); - public static final TagKey STORAGE_BLOCKS_RESIN = bindC("storage_blocks/resin"); - public static final TagKey STORAGE_BLOCKS_TRANSCENDIUM = bindC("storage_blocks/transcendium"); - public static final TagKey STORAGE_BLOCKS_FROST_METAL = bindC("storage_blocks/frost_metal"); - - public static final TagKey STORAGE_BLOCKS_SUGAR = bindC("storage_blocks/sugar"); - public static final TagKey STORAGE_BLOCKS_GUNPOWDER = bindC("storage_blocks/gunpowder"); - public static final TagKey STORAGE_BLOCKS_ROTTEN_FLESH = bindC("storage_blocks/rotten_flesh"); - public static final TagKey STORAGE_BLOCKS_FLINT = bindC("storage_blocks/flint"); - - public static final TagKey GEMS_TOPAZ = bindC("gems/topaz"); - public static final TagKey GEMS_SAPPHIRE = bindC("gems/sapphire"); - public static final TagKey GEMS_RUBY = bindC("gems/ruby"); - public static final TagKey GEMS_AMBER = bindC("gems/amber"); - - public static final TagKey TUNGSTEN_INGOTS = bindC("ingots/tungsten"); - public static final TagKey TITANIUM_INGOTS = bindC("ingots/titanium"); - public static final TagKey ZINC_INGOTS = bindC("ingots/zinc"); - public static final TagKey TIN_INGOTS = bindC("ingots/tin"); - public static final TagKey LEAD_INGOTS = bindC("ingots/lead"); - public static final TagKey SILVER_INGOTS = bindC("ingots/silver"); - public static final TagKey URANIUM_INGOTS = bindC("ingots/uranium"); - public static final TagKey PLUTONIUM_INGOTS = bindC("ingots/plutonium"); - public static final TagKey BRONZE_INGOTS = bindC("ingots/bronze"); - public static final TagKey BRASS_INGOTS = bindC("ingots/brass"); - public static final TagKey MAGNET_INGOTS = bindC("ingots/magnet"); - public static final TagKey TRANSCENDIUM_INGOTS = bindC("ingots/transcendium"); - public static final TagKey FROST_METAL_INGOTS = bindC("ingots/frost_metal"); - - public static final TagKey TUNGSTEN_NUGGETS = bindC("nuggets/tungsten"); - public static final TagKey TITANIUM_NUGGETS = bindC("nuggets/titanium"); - public static final TagKey ZINC_NUGGETS = bindC("nuggets/zinc"); - public static final TagKey TIN_NUGGETS = bindC("nuggets/tin"); - public static final TagKey LEAD_NUGGETS = bindC("nuggets/lead"); - public static final TagKey SILVER_NUGGETS = bindC("nuggets/silver"); - public static final TagKey URANIUM_NUGGETS = bindC("nuggets/uranium"); - public static final TagKey PLUTONIUM_NUGGETS = bindC("nuggets/plutonium"); - public static final TagKey BRONZE_NUGGETS = bindC("nuggets/bronze"); - public static final TagKey BRASS_NUGGETS = bindC("nuggets/brass"); - public static final TagKey COPPER_NUGGETS = bindC("nuggets/copper"); - public static final TagKey NETHERITE_NUGGETS = bindC("nuggets/netherite"); - public static final TagKey TRANSCENDIUM_NUGGETS = bindC("nuggets/transcendium"); - public static final TagKey FROST_METAL_NUGGETS = bindC("nuggets/frost_metal"); - - public static final TagKey ZINC_ORES = bindC("ores/zinc"); - public static final TagKey TIN_ORES = bindC("ores/tin"); - public static final TagKey TITANIUM_ORES = bindC("ores/titanium"); - public static final TagKey TUNGSTEN_ORES = bindC("ores/tungsten"); - public static final TagKey LEAD_ORES = bindC("ores/lead"); - public static final TagKey SILVER_ORES = bindC("ores/silver"); - public static final TagKey URANIUM_ORES = bindC("ores/uranium"); - public static final TagKey VOID_MATTER_ORES = bindC("ores/void_matter"); - public static final TagKey EARTH_CORE_SHARD_ORES = bindC("ores/earth_core_shard"); - - public static final TagKey STORAGE_BLOCKS_RAW_TUNGSTEN = bindC("storage_blocks/raw_tungsten"); - public static final TagKey STORAGE_BLOCKS_RAW_TITANIUM = bindC("storage_blocks/raw_titanium"); - public static final TagKey STORAGE_BLOCKS_RAW_ZINC = bindC("storage_blocks/raw_zinc"); - public static final TagKey STORAGE_BLOCKS_RAW_TIN = bindC("storage_blocks/raw_tin"); - public static final TagKey STORAGE_BLOCKS_RAW_LEAD = bindC("storage_blocks/raw_lead"); - public static final TagKey STORAGE_BLOCKS_RAW_SILVER = bindC("storage_blocks/raw_silver"); - public static final TagKey STORAGE_BLOCKS_RAW_URANIUM = bindC("storage_blocks/raw_uranium"); - - public static final TagKey RAW_ZINC = bindC("raw_materials/zinc"); - public static final TagKey RAW_TIN = bindC("raw_materials/tin"); - public static final TagKey RAW_TITANIUM = bindC("raw_materials/titanium"); - public static final TagKey RAW_TUNGSTEN = bindC("raw_materials/tungsten"); - public static final TagKey RAW_LEAD = bindC("raw_materials/lead"); - public static final TagKey RAW_SILVER = bindC("raw_materials/silver"); - public static final TagKey RAW_URANIUM = bindC("raw_materials/uranium"); - - public static final TagKey EXP_BUCKETS = bindC("buckets/exp_fluid"); - public static final TagKey OIL_BUCKETS = bindC("buckets/oil"); - public static final TagKey CEMENT_BUCKETS = bindC("buckets/cement"); - - public static final TagKey AMETHYST_TOOL_MATERIALS = bindC("amethyst_tool_materials"); - public static final TagKey ROYAL_STEEL_TOOL_MATERIALS = bindC("royal_steel_tool_materials"); - public static final TagKey FROST_METAL_TOOL_MATERIALS = bindC("frost_metal_tool_materials"); - public static final TagKey EMBER_METAL_TOOL_MATERIALS = bindC("ember_metal_tool_materials"); - public static final TagKey TRANSCENDIUM_TOOL_MATERIALS = bindC("transcendium_tool_materials"); - - public static final TagKey ROYAL_STEEL_PICKAXE_BASE = bind("royal_steel_pickaxe_base"); - public static final TagKey ROYAL_STEEL_AXE_BASE = bind("royal_steel_axe_base"); - public static final TagKey ROYAL_STEEL_HOE_BASE = bind("royal_steel_hoe_base"); - public static final TagKey ROYAL_STEEL_SHOVEL_BASE = bind("royal_steel_shovel_base"); - public static final TagKey ROYAL_STEEL_SWORD_BASE = bind("royal_steel_sword_base"); - public static final TagKey FROST_METAL_PICKAXE_BASE = bind("frost_metal_pickaxe_base"); - public static final TagKey FROST_METAL_AXE_BASE = bind("frost_metal_axe_base"); - public static final TagKey FROST_METAL_HOE_BASE = bind("frost_metal_hoe_base"); - public static final TagKey FROST_METAL_SHOVEL_BASE = bind("frost_metal_shovel_base"); - public static final TagKey FROST_METAL_SWORD_BASE = bind("frost_metal_sword_base"); - public static final TagKey EMBER_METAL_PICKAXE_BASE = bind("ember_metal_pickaxe_base"); - public static final TagKey EMBER_METAL_AXE_BASE = bind("ember_metal_axe_base"); - public static final TagKey EMBER_METAL_HOE_BASE = bind("ember_metal_hoe_base"); - public static final TagKey EMBER_METAL_SHOVEL_BASE = bind("ember_metal_shovel_base"); - public static final TagKey EMBER_METAL_SWORD_BASE = bind("ember_metal_sword_base"); - public static final TagKey CAPACITOR = bind("capacitor"); - public static final TagKey GEMS = bind("gems"); - public static final TagKey GEM_BLOCKS = bind("gem_blocks"); - public static final TagKey DEAD_CORALS = bind("dead_corals"); - public static final TagKey DEAD_CORAL_BLOCKS = bind("dead_coral_blocks"); - public static final TagKey VOID_RESISTANT = bind("void_resistant"); - public static final TagKey REINFORCED_CONCRETE = bind("reinforced_concrete"); - public static final TagKey SEEDS_PACK_CONTENT = bind("seeds_pack_content"); - public static final TagKey FIRE_STARTER = bind("fire_starter"); - public static final TagKey UNBROKEN_FIRE_STARTER = bind("unbroken_fire_starter"); - public static final TagKey NETHERITE_BLOCK = bind("netherite_block"); - public static final TagKey EXPLOSION_PROOF = bind("explosion_proof"); - public static final TagKey AMULET = bind("amulet"); - public static final TagKey ANVIL_HAMMER = bind("tools/anvil_hammer"); - public static final TagKey TEMPLATES = bind("templates"); - public static final TagKey MULTIPLE_TO_ONE_SMITHING_TEMPLATES = bind("multiple_to_one_smithing_templates"); - public static final TagKey DRAGON_ROD = bind("tools/dragon_rod"); - public static final TagKey HEAVY_HALBERD = bind("tools/heavy_halberd"); - public static final TagKey RESONATOR = bind("tools/resonator"); + public static final TagKey RESIN = ModItemTags.bindC("resin"); + public static final TagKey WHEAT_FLOUR = ModItemTags.bindC("flour/wheat"); + public static final TagKey WHEAT_DOUGH = ModItemTags.bindC("dough/wheat"); + public static final TagKey CREAM = ModItemTags.bindC("foods/cream"); + public static final TagKey FLOUR = ModItemTags.bindC("foods/flour"); + public static final TagKey DOUGH = ModItemTags.bindC("foods/dough"); + public static final TagKey RAW_MUTTON = ModItemTags.bindC("foods/raw_mutton"); + public static final TagKey RAW_BEEF = ModItemTags.bindC("foods/raw_beef"); + public static final TagKey RAW_CHICKEN = ModItemTags.bindC("foods/raw_chicken"); + public static final TagKey RAW_PORKCHOP = ModItemTags.bindC("foods/raw_porkchop"); + public static final TagKey RAW_RABBIT = ModItemTags.bindC("foods/raw_rabbit"); + + public static final TagKey PLATES = ModItemTags.bindC("plates"); + public static final TagKey GOLD_PLATES = ModItemTags.bindC("plates/gold"); + public static final TagKey IRON_PLATES = ModItemTags.bindC("plates/iron"); + public static final TagKey COPPER_PLATES = ModItemTags.bindC("plates/copper"); + public static final TagKey TUNGSTEN_PLATES = ModItemTags.bindC("plates/tungsten"); + public static final TagKey TITANIUM_PLATES = ModItemTags.bindC("plates/titanium"); + public static final TagKey ZINC_PLATES = ModItemTags.bindC("plates/zinc"); + public static final TagKey TIN_PLATES = ModItemTags.bindC("plates/tin"); + public static final TagKey LEAD_PLATES = ModItemTags.bindC("plates/lead"); + public static final TagKey SILVER_PLATES = ModItemTags.bindC("plates/silver"); + public static final TagKey URANIUM_PLATES = ModItemTags.bindC("plates/uranium"); + public static final TagKey BRONZE_PLATES = ModItemTags.bindC("plates/bronze"); + public static final TagKey BRASS_PLATES = ModItemTags.bindC("plates/brass"); + + public static final TagKey STORAGE_BLOCKS_TUNGSTEN = ModItemTags.bindC("storage_blocks/tungsten"); + public static final TagKey STORAGE_BLOCKS_TITANIUM = ModItemTags.bindC("storage_blocks/titanium"); + public static final TagKey STORAGE_BLOCKS_ZINC = ModItemTags.bindC("storage_blocks/zinc"); + public static final TagKey STORAGE_BLOCKS_TIN = ModItemTags.bindC("storage_blocks/tin"); + public static final TagKey STORAGE_BLOCKS_LEAD = ModItemTags.bindC("storage_blocks/lead"); + public static final TagKey STORAGE_BLOCKS_SILVER = ModItemTags.bindC("storage_blocks/silver"); + public static final TagKey STORAGE_BLOCKS_URANIUM = ModItemTags.bindC("storage_blocks/uranium"); + public static final TagKey STORAGE_BLOCKS_PLUTONIUM = ModItemTags.bindC("storage_blocks/plutonium"); + public static final TagKey STORAGE_BLOCKS_BRONZE = ModItemTags.bindC("storage_blocks/bronze"); + public static final TagKey STORAGE_BLOCKS_BRASS = ModItemTags.bindC("storage_blocks/brass"); + public static final TagKey STORAGE_BLOCKS_VOID_MATTER = ModItemTags.bindC("storage_blocks/void_matter"); + public static final TagKey STORAGE_BLOCKS_EARTH_CORE_SHARD = ModItemTags.bindC("storage_blocks/earth_core_shard"); + public static final TagKey STORAGE_BLOCKS_MULTIPHASE_MATTER = ModItemTags.bindC("storage_blocks/multiphase_matter"); + public static final TagKey STORAGE_BLOCKS_MAGNET = ModItemTags.bindC("storage_blocks/magnet"); + public static final TagKey STORAGE_BLOCKS_TOPAZ = ModItemTags.bindC("storage_blocks/topaz"); + public static final TagKey STORAGE_BLOCKS_SAPPHIRE = ModItemTags.bindC("storage_blocks/sapphire"); + public static final TagKey STORAGE_BLOCKS_RUBY = ModItemTags.bindC("storage_blocks/ruby"); + public static final TagKey STORAGE_BLOCKS_EXP_GEM = ModItemTags.bindC("storage_blocks/exp_gem"); + public static final TagKey STORAGE_BLOCKS_AMBER = ModItemTags.bindC("storage_blocks/amber"); + public static final TagKey STORAGE_BLOCKS_RESIN = ModItemTags.bindC("storage_blocks/resin"); + public static final TagKey STORAGE_BLOCKS_TRANSCENDIUM = ModItemTags.bindC("storage_blocks/transcendium"); + public static final TagKey STORAGE_BLOCKS_FROST_METAL = ModItemTags.bindC("storage_blocks/frost_metal"); + + public static final TagKey STORAGE_BLOCKS_SUGAR = ModItemTags.bindC("storage_blocks/sugar"); + public static final TagKey STORAGE_BLOCKS_GUNPOWDER = ModItemTags.bindC("storage_blocks/gunpowder"); + public static final TagKey STORAGE_BLOCKS_ROTTEN_FLESH = ModItemTags.bindC("storage_blocks/rotten_flesh"); + public static final TagKey STORAGE_BLOCKS_FLINT = ModItemTags.bindC("storage_blocks/flint"); + + public static final TagKey GEMS_TOPAZ = ModItemTags.bindC("gems/topaz"); + public static final TagKey GEMS_SAPPHIRE = ModItemTags.bindC("gems/sapphire"); + public static final TagKey GEMS_RUBY = ModItemTags.bindC("gems/ruby"); + public static final TagKey GEMS_AMBER = ModItemTags.bindC("gems/amber"); + + public static final TagKey TUNGSTEN_INGOTS = ModItemTags.bindC("ingots/tungsten"); + public static final TagKey TITANIUM_INGOTS = ModItemTags.bindC("ingots/titanium"); + public static final TagKey ZINC_INGOTS = ModItemTags.bindC("ingots/zinc"); + public static final TagKey TIN_INGOTS = ModItemTags.bindC("ingots/tin"); + public static final TagKey LEAD_INGOTS = ModItemTags.bindC("ingots/lead"); + public static final TagKey SILVER_INGOTS = ModItemTags.bindC("ingots/silver"); + public static final TagKey URANIUM_INGOTS = ModItemTags.bindC("ingots/uranium"); + public static final TagKey PLUTONIUM_INGOTS = ModItemTags.bindC("ingots/plutonium"); + public static final TagKey BRONZE_INGOTS = ModItemTags.bindC("ingots/bronze"); + public static final TagKey BRASS_INGOTS = ModItemTags.bindC("ingots/brass"); + public static final TagKey MAGNET_INGOTS = ModItemTags.bindC("ingots/magnet"); + public static final TagKey TRANSCENDIUM_INGOTS = ModItemTags.bindC("ingots/transcendium"); + public static final TagKey FROST_METAL_INGOTS = ModItemTags.bindC("ingots/frost_metal"); + + public static final TagKey TUNGSTEN_NUGGETS = ModItemTags.bindC("nuggets/tungsten"); + public static final TagKey TITANIUM_NUGGETS = ModItemTags.bindC("nuggets/titanium"); + public static final TagKey ZINC_NUGGETS = ModItemTags.bindC("nuggets/zinc"); + public static final TagKey TIN_NUGGETS = ModItemTags.bindC("nuggets/tin"); + public static final TagKey LEAD_NUGGETS = ModItemTags.bindC("nuggets/lead"); + public static final TagKey SILVER_NUGGETS = ModItemTags.bindC("nuggets/silver"); + public static final TagKey URANIUM_NUGGETS = ModItemTags.bindC("nuggets/uranium"); + public static final TagKey PLUTONIUM_NUGGETS = ModItemTags.bindC("nuggets/plutonium"); + public static final TagKey BRONZE_NUGGETS = ModItemTags.bindC("nuggets/bronze"); + public static final TagKey BRASS_NUGGETS = ModItemTags.bindC("nuggets/brass"); + public static final TagKey COPPER_NUGGETS = ModItemTags.bindC("nuggets/copper"); + public static final TagKey NETHERITE_NUGGETS = ModItemTags.bindC("nuggets/netherite"); + public static final TagKey TRANSCENDIUM_NUGGETS = ModItemTags.bindC("nuggets/transcendium"); + public static final TagKey FROST_METAL_NUGGETS = ModItemTags.bindC("nuggets/frost_metal"); + + public static final TagKey ZINC_ORES = ModItemTags.bindC("ores/zinc"); + public static final TagKey TIN_ORES = ModItemTags.bindC("ores/tin"); + public static final TagKey TITANIUM_ORES = ModItemTags.bindC("ores/titanium"); + public static final TagKey TUNGSTEN_ORES = ModItemTags.bindC("ores/tungsten"); + public static final TagKey LEAD_ORES = ModItemTags.bindC("ores/lead"); + public static final TagKey SILVER_ORES = ModItemTags.bindC("ores/silver"); + public static final TagKey URANIUM_ORES = ModItemTags.bindC("ores/uranium"); + public static final TagKey VOID_MATTER_ORES = ModItemTags.bindC("ores/void_matter"); + public static final TagKey EARTH_CORE_SHARD_ORES = ModItemTags.bindC("ores/earth_core_shard"); + + public static final TagKey STORAGE_BLOCKS_RAW_TUNGSTEN = ModItemTags.bindC("storage_blocks/raw_tungsten"); + public static final TagKey STORAGE_BLOCKS_RAW_TITANIUM = ModItemTags.bindC("storage_blocks/raw_titanium"); + public static final TagKey STORAGE_BLOCKS_RAW_ZINC = ModItemTags.bindC("storage_blocks/raw_zinc"); + public static final TagKey STORAGE_BLOCKS_RAW_TIN = ModItemTags.bindC("storage_blocks/raw_tin"); + public static final TagKey STORAGE_BLOCKS_RAW_LEAD = ModItemTags.bindC("storage_blocks/raw_lead"); + public static final TagKey STORAGE_BLOCKS_RAW_SILVER = ModItemTags.bindC("storage_blocks/raw_silver"); + public static final TagKey STORAGE_BLOCKS_RAW_URANIUM = ModItemTags.bindC("storage_blocks/raw_uranium"); + + public static final TagKey RAW_ZINC = ModItemTags.bindC("raw_materials/zinc"); + public static final TagKey RAW_TIN = ModItemTags.bindC("raw_materials/tin"); + public static final TagKey RAW_TITANIUM = ModItemTags.bindC("raw_materials/titanium"); + public static final TagKey RAW_TUNGSTEN = ModItemTags.bindC("raw_materials/tungsten"); + public static final TagKey RAW_LEAD = ModItemTags.bindC("raw_materials/lead"); + public static final TagKey RAW_SILVER = ModItemTags.bindC("raw_materials/silver"); + public static final TagKey RAW_URANIUM = ModItemTags.bindC("raw_materials/uranium"); + + public static final TagKey EXP_BUCKETS = ModItemTags.bindC("buckets/exp_fluid"); + public static final TagKey OIL_BUCKETS = ModItemTags.bindC("buckets/oil"); + public static final TagKey CEMENT_BUCKETS = ModItemTags.bindC("buckets/cement"); + + public static final TagKey AMETHYST_TOOL_MATERIALS = ModItemTags.bindC("amethyst_tool_materials"); + public static final TagKey ROYAL_STEEL_TOOL_MATERIALS = ModItemTags.bindC("royal_steel_tool_materials"); + public static final TagKey FROST_METAL_TOOL_MATERIALS = ModItemTags.bindC("frost_metal_tool_materials"); + public static final TagKey EMBER_METAL_TOOL_MATERIALS = ModItemTags.bindC("ember_metal_tool_materials"); + public static final TagKey TRANSCENDIUM_TOOL_MATERIALS = ModItemTags.bindC("transcendium_tool_materials"); + + public static final TagKey ROYAL_STEEL_PICKAXE_BASE = ModItemTags.bind("royal_steel_pickaxe_base"); + public static final TagKey ROYAL_STEEL_AXE_BASE = ModItemTags.bind("royal_steel_axe_base"); + public static final TagKey ROYAL_STEEL_HOE_BASE = ModItemTags.bind("royal_steel_hoe_base"); + public static final TagKey ROYAL_STEEL_SHOVEL_BASE = ModItemTags.bind("royal_steel_shovel_base"); + public static final TagKey ROYAL_STEEL_SWORD_BASE = ModItemTags.bind("royal_steel_sword_base"); + public static final TagKey FROST_METAL_PICKAXE_BASE = ModItemTags.bind("frost_metal_pickaxe_base"); + public static final TagKey FROST_METAL_AXE_BASE = ModItemTags.bind("frost_metal_axe_base"); + public static final TagKey FROST_METAL_HOE_BASE = ModItemTags.bind("frost_metal_hoe_base"); + public static final TagKey FROST_METAL_SHOVEL_BASE = ModItemTags.bind("frost_metal_shovel_base"); + public static final TagKey FROST_METAL_SWORD_BASE = ModItemTags.bind("frost_metal_sword_base"); + public static final TagKey EMBER_METAL_PICKAXE_BASE = ModItemTags.bind("ember_metal_pickaxe_base"); + public static final TagKey EMBER_METAL_AXE_BASE = ModItemTags.bind("ember_metal_axe_base"); + public static final TagKey EMBER_METAL_HOE_BASE = ModItemTags.bind("ember_metal_hoe_base"); + public static final TagKey EMBER_METAL_SHOVEL_BASE = ModItemTags.bind("ember_metal_shovel_base"); + public static final TagKey EMBER_METAL_SWORD_BASE = ModItemTags.bind("ember_metal_sword_base"); + public static final TagKey CAPACITOR = ModItemTags.bind("capacitor"); + public static final TagKey GEMS = ModItemTags.bind("gems"); + public static final TagKey GEM_BLOCKS = ModItemTags.bind("gem_blocks"); + public static final TagKey DEAD_CORALS = ModItemTags.bind("dead_corals"); + public static final TagKey DEAD_CORAL_BLOCKS = ModItemTags.bind("dead_coral_blocks"); + public static final TagKey VOID_RESISTANT = ModItemTags.bind("void_resistant"); + public static final TagKey REINFORCED_CONCRETE = ModItemTags.bind("reinforced_concrete"); + public static final TagKey SEEDS_PACK_CONTENT = ModItemTags.bind("seeds_pack_content"); + public static final TagKey FIRE_STARTER = ModItemTags.bind("fire_starter"); + public static final TagKey UNBROKEN_FIRE_STARTER = ModItemTags.bind("unbroken_fire_starter"); + public static final TagKey NETHERITE_BLOCK = ModItemTags.bind("netherite_block"); + public static final TagKey EXPLOSION_PROOF = ModItemTags.bind("explosion_proof"); + public static final TagKey AMULET = ModItemTags.bind("amulet"); + public static final TagKey ANVIL_HAMMER = ModItemTags.bind("tools/anvil_hammer"); + public static final TagKey TEMPLATES = ModItemTags.bind("templates"); + public static final TagKey MULTIPLE_TO_ONE_SMITHING_TEMPLATES = ModItemTags.bind("multiple_to_one_smithing_templates"); + public static final TagKey DRAGON_ROD = ModItemTags.bind("tools/dragon_rod"); + public static final TagKey HEAVY_HALBERD = ModItemTags.bind("tools/heavy_halberd"); + public static final TagKey RESONATOR = ModItemTags.bind("tools/resonator"); public static final TagKey DISINTEGRATION_SUPPORTED = TagKey.create( Registries.ITEM, Identifier.fromNamespaceAndPath("minecraft", "enchantable/anvilcraft_disintegration") @@ -177,22 +177,22 @@ public class ModItemTags { Registries.ITEM, Identifier.fromNamespaceAndPath("minecraft", "enchantable/anvilcraft_smelting") ); - public static final TagKey UNCHARGED_NEUTRONIUM_INGOTS = bind("uncharged_neutronium_ingots"); - public static final TagKey HEATABLE_BLOCKS = bind("heatable_blocks"); - public static final TagKey LEVITATIONALS = bind("levitationals"); - public static final TagKey RADIATIONS = bind("radiations"); - public static final TagKey DISALLOW_HAND_INSERT_INTO_TANK = bind("disallow_hand_insert_into_tank"); + public static final TagKey UNCHARGED_NEUTRONIUM_INGOTS = ModItemTags.bind("uncharged_neutronium_ingots"); + public static final TagKey HEATABLE_BLOCKS = ModItemTags.bind("heatable_blocks"); + public static final TagKey LEVITATIONALS = ModItemTags.bind("levitationals"); + public static final TagKey RADIATIONS = ModItemTags.bind("radiations"); + public static final TagKey DISALLOW_HAND_INSERT_INTO_TANK = ModItemTags.bind("disallow_hand_insert_into_tank"); - public static final TagKey COMPRESS_ITEM = bind("compress_item"); - public static final TagKey SUPER_HEATING_BOOST_PRODUCTION = bind("super_heating_boost_production"); + public static final TagKey COMPRESS_ITEM = ModItemTags.bind("compress_item"); + public static final TagKey SUPER_HEATING_BOOST_PRODUCTION = ModItemTags.bind("super_heating_boost_production"); - public static final TagKey CURIOS_HEAD = bindCurios("head"); - public static final TagKey CURIOS_IONOCRAFT_BACKPACK = bindCurios("ionocraft_backpack"); - public static final TagKey CURIOS_CHARM = bindCurios("charm"); + public static final TagKey CURIOS_HEAD = ModItemTags.bindCurios("head"); + public static final TagKey CURIOS_IONOCRAFT_BACKPACK = ModItemTags.bindCurios("ionocraft_backpack"); + public static final TagKey CURIOS_CHARM = ModItemTags.bindCurios("charm"); - public static final TagKey TOTEM = bind("totem"); + public static final TagKey TOTEM = ModItemTags.bind("totem"); - public static final Object2ObjectMap> DYED_COLORS = initDyedTags(); + public static final Object2ObjectMap> DYED_COLORS = ModItemTags.initDyedTags(); public static TagKey bindC(String id) { return TagKey.create(Registries.ITEM, Identifier.fromNamespaceAndPath("c", id)); @@ -209,7 +209,7 @@ public static TagKey bind(String id) { public static Object2ObjectMap> initDyedTags() { Object2ObjectMap> map = new Object2ObjectOpenHashMap<>(); for (Color color : Color.values()) { - map.put(color, bindC("dyed/" + color)); + map.put(color, ModItemTags.bindC("dyed/" + color)); } return map; } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/ModItems.java b/src/main/java/dev/dubhe/anvilcraft/init/item/ModItems.java index 75e311d69f..291d307511 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/ModItems.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/ModItems.java @@ -170,7 +170,7 @@ public class ModItems { .properties(properties -> properties) .recipe(RegistrumItemRecipeLoader.pickaxe( Items.AMETHYST_SHARD, - (ctx, provider) -> enchanted(ctx.get(), Enchantments.FORTUNE, 3, provider.getRegistries()) + (ctx, provider) -> ModItems.enchanted(ctx.get(), Enchantments.FORTUNE, 3, provider.getRegistries()) )) .model(DataGenUtil::flatHandheldItem) .tag(ItemTags.PICKAXES, ItemTags.CLUSTER_MAX_HARVESTABLES, Tags.Items.MINING_TOOL_TOOLS) @@ -178,7 +178,7 @@ public class ModItems { public static final ItemEntry AMETHYST_AXE = REGISTRUM.item("amethyst_axe", AmethystAxeItem::new) .recipe(RegistrumItemRecipeLoader.axe( Items.AMETHYST_SHARD, - (ctx, provider) -> enchanted(ctx.get(), ModEnchantments.FELLING_KEY, 1, provider.getRegistries()) + (ctx, provider) -> ModItems.enchanted(ctx.get(), ModEnchantments.FELLING_KEY, 1, provider.getRegistries()) )) .model(DataGenUtil::flatHandheldItem) .tag(ItemTags.AXES, Tags.Items.MELEE_WEAPON_TOOLS) @@ -186,7 +186,7 @@ public class ModItems { public static final ItemEntry AMETHYST_HOE = REGISTRUM.item("amethyst_hoe", AmethystHoeItem::new) .recipe(RegistrumItemRecipeLoader.hoe( Items.AMETHYST_SHARD, - (ctx, generator) -> enchanted(ctx.get(), ModEnchantments.HARVEST_KEY, 1, generator.getRegistries()) + (ctx, generator) -> ModItems.enchanted(ctx.get(), ModEnchantments.HARVEST_KEY, 1, generator.getRegistries()) )) .model(DataGenUtil::flatHandheldItem) .tag(ItemTags.HOES) @@ -194,7 +194,7 @@ public class ModItems { public static final ItemEntry AMETHYST_SWORD = REGISTRUM.item("amethyst_sword", AmethystSwordItem::new) .recipe(RegistrumItemRecipeLoader.sword( Items.AMETHYST_SHARD, - (ctx, provider) -> enchanted(ctx.get(), ModEnchantments.BEHEADING_KEY, 1, provider.getRegistries()) + (ctx, provider) -> ModItems.enchanted(ctx.get(), ModEnchantments.BEHEADING_KEY, 1, provider.getRegistries()) )) .model(DataGenUtil::flatHandheldItem) .tag(ItemTags.SWORDS, Tags.Items.MELEE_WEAPON_TOOLS) @@ -202,7 +202,7 @@ public class ModItems { public static final ItemEntry AMETHYST_SHOVEL = REGISTRUM.item("amethyst_shovel", AmethystShovelItem::new) .recipe(RegistrumItemRecipeLoader.shovel( Items.AMETHYST_SHARD, - (ctx, provider) -> enchanted(ctx.get(), Enchantments.EFFICIENCY, 3, provider.getRegistries()) + (ctx, provider) -> ModItems.enchanted(ctx.get(), Enchantments.EFFICIENCY, 3, provider.getRegistries()) )) .model(DataGenUtil::flatHandheldItem) .tag(ItemTags.SHOVELS) @@ -818,66 +818,66 @@ private static ItemEntry createBigAmuletItem(String type, Suppli .register(); } - public static final ItemEntry EMERALD_AMULET = createAmuletItem( + public static final ItemEntry EMERALD_AMULET = ModItems.createAmuletItem( "emerald", () -> ModAmulets.EMERALD, builder -> builder.requires(Items.EMERALD_BLOCK) ); - public static final ItemEntry TOPAZ_AMULET = createAmuletItem( + public static final ItemEntry TOPAZ_AMULET = ModItems.createAmuletItem( "topaz", () -> ModAmulets.TOPAZ, builder -> builder.requires(ModBlocks.TOPAZ_BLOCK) ); - public static final ItemEntry RUBY_AMULET = createAmuletItem( + public static final ItemEntry RUBY_AMULET = ModItems.createAmuletItem( "ruby", () -> ModAmulets.RUBY, builder -> builder.requires(ModBlocks.RUBY_BLOCK) ); - public static final ItemEntry SAPPHIRE_AMULET = createAmuletItem( + public static final ItemEntry SAPPHIRE_AMULET = ModItems.createAmuletItem( "sapphire", () -> ModAmulets.SAPPHIRE, builder -> builder.requires(ModBlocks.SAPPHIRE_BLOCK) ); - public static final ItemEntry ANVIL_AMULET = createAmuletItem( + public static final ItemEntry ANVIL_AMULET = ModItems.createAmuletItem( "anvil", () -> ModAmulets.ANVIL, builder -> builder.requires(Items.ANVIL) ); - public static final ItemEntry COMRADE_AMULET = createAmuletItem( + public static final ItemEntry COMRADE_AMULET = ModItems.createAmuletItem( "comrade", () -> ModAmulets.COMRADE, builder -> builder.requires(Items.NAME_TAG, 4) ); - public static final ItemEntry FEATHER_AMULET = createAmuletItem( + public static final ItemEntry FEATHER_AMULET = ModItems.createAmuletItem( "feather", () -> ModAmulets.FEATHER, builder -> builder.requires(Items.FEATHER, 16).requires(Items.PHANTOM_MEMBRANE, 4) ); - public static final ItemEntry CAT_AMULET = createAmuletItem( + public static final ItemEntry CAT_AMULET = ModItems.createAmuletItem( "cat", () -> ModAmulets.CAT, builder -> builder.requires(Items.SALMON, 16).requires(Items.COD, 16) ); - public static final ItemEntry DOG_AMULET = createAmuletItem( + public static final ItemEntry DOG_AMULET = ModItems.createAmuletItem( "dog", () -> ModAmulets.DOG, builder -> builder.requires(Items.BONE, 16).requires(ItemTags.MEAT, 16) ); - public static final ItemEntry SILENCE_AMULET = createAmuletItem( + public static final ItemEntry SILENCE_AMULET = ModItems.createAmuletItem( "silence", () -> ModAmulets.SILENCE, builder -> builder.requires(Items.ECHO_SHARD, 16) ); - public static final ItemEntry ABNORMAL_AMULET = createAmuletItem( + public static final ItemEntry ABNORMAL_AMULET = ModItems.createAmuletItem( "abnormal", () -> ModAmulets.ABNORMAL, // TODO: 修改配方 builder -> builder.requires(ModItems.CURSED_GOLD_INGOT, 1).requires(ModItems.LEVITATION_POWDER, 16) ); - public static final ItemEntry GEM_AMULET = createBigAmuletItem( + public static final ItemEntry GEM_AMULET = ModItems.createBigAmuletItem( "gem", () -> ModAmulets.GEM ); - public static final ItemEntry NATURE_AMULET = createBigAmuletItem( + public static final ItemEntry NATURE_AMULET = ModItems.createBigAmuletItem( "nature", () -> ModAmulets.NATURE ); @@ -1334,12 +1334,12 @@ public void accept( .model(ModelProviderUtil::bucket) .register(); - public static final Object2ObjectMap> CEMENT_BUCKETS = registerAllCementBuckets(); + public static final Object2ObjectMap> CEMENT_BUCKETS = ModItems.registerAllCementBuckets(); private static Object2ObjectMap> registerAllCementBuckets() { Object2ObjectMap> map = new Object2ObjectOpenHashMap<>(); for (Color color : Color.values()) { - var entry = registerCementBucket(color); + var entry = ModItems.registerCementBucket(color); map.put(color, entry); } return map; @@ -1400,7 +1400,7 @@ public static NonNullBiConsumer, Creati int level ) { return (ctx, modifier) -> { - modifier.accept(enchanted(ctx.get(), enchKey, level, modifier.getParameters().holders()).create()); + modifier.accept(ModItems.enchanted(ctx.get(), enchKey, level, modifier.getParameters().holders()).create()); }; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/item/tabs/DisplayItemsGenerator.java b/src/main/java/dev/dubhe/anvilcraft/init/item/tabs/DisplayItemsGenerator.java index c9a4dea267..4832affc2b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/item/tabs/DisplayItemsGenerator.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/item/tabs/DisplayItemsGenerator.java @@ -50,7 +50,7 @@ public void enchanting(ItemLike item, ResourceKey enchKey, int leve if (this.output == null || this.itemDisplayParameters == null) { return; } - this.output.accept(enchanting(this.itemDisplayParameters, item, enchKey, level)); + this.output.accept(DisplayItemsGenerator.enchanting(this.itemDisplayParameters, item, enchKey, level)); } private static ItemStack enchanting( diff --git a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootContextParamSets.java b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootContextParamSets.java index 0dd8e0b185..5a69cc9e28 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootContextParamSets.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootContextParamSets.java @@ -8,7 +8,7 @@ import java.util.function.Consumer; public class ModLootContextParamSets { - public static final ContextKeySet USE_ON_ITEM = register( + public static final ContextKeySet USE_ON_ITEM = ModLootContextParamSets.register( "use_on_item", it -> it.required(LootContextParams.THIS_ENTITY) .required(LootContextParams.ORIGIN) @@ -17,7 +17,7 @@ public class ModLootContextParamSets { .required(LootContextParams.ENCHANTMENT_LEVEL) ); - public static final ContextKeySet POST_BREAK_BLOCK = register( + public static final ContextKeySet POST_BREAK_BLOCK = ModLootContextParamSets.register( "post_break_block", it -> it.required(LootContextParams.THIS_ENTITY) .required(LootContextParams.ORIGIN) diff --git a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootItemFunctions.java b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootItemFunctions.java index b910759dd0..7e8527a63e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootItemFunctions.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootItemFunctions.java @@ -13,7 +13,7 @@ public class ModLootItemFunctions { DeferredRegister.create(Registries.LOOT_FUNCTION_TYPE, AnvilCraft.MOD_ID); public static void register(IEventBus modEventBus) { - LOOT_FUNCTION_TYPES.register("curse_loot", () -> CurseLootItemFunction.CODEC); - LOOT_FUNCTION_TYPES.register(modEventBus); + ModLootItemFunctions.LOOT_FUNCTION_TYPES.register("curse_loot", () -> CurseLootItemFunction.CODEC); + ModLootItemFunctions.LOOT_FUNCTION_TYPES.register(modEventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootModifiers.java b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootModifiers.java index 817d8883b3..77b0e613db 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootModifiers.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootModifiers.java @@ -16,12 +16,12 @@ public class ModLootModifiers { DeferredRegister.create(NeoForgeRegistries.Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, AnvilCraft.MOD_ID); public static final Supplier> SMELTING_LOOT_MODIFIER = - GLOBAL_LOOT_MODIFIER_SERIALIZERS.register("smelting_loot_modifier", () -> SmeltingLootModifier.CODEC); + ModLootModifiers.GLOBAL_LOOT_MODIFIER_SERIALIZERS.register("smelting_loot_modifier", () -> SmeltingLootModifier.CODEC); public static final Supplier> DISINTEGRATION_LOOT_MODIFIER = - GLOBAL_LOOT_MODIFIER_SERIALIZERS.register("disintegration_loot_modifier", () -> DisintegrationLootModifier.CODEC); + ModLootModifiers.GLOBAL_LOOT_MODIFIER_SERIALIZERS.register("disintegration_loot_modifier", () -> DisintegrationLootModifier.CODEC); public static void register(IEventBus eventBus) { - GLOBAL_LOOT_MODIFIER_SERIALIZERS.register(eventBus); + ModLootModifiers.GLOBAL_LOOT_MODIFIER_SERIALIZERS.register(eventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootTables.java b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootTables.java index 9d6f74b302..ae2669ec99 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootTables.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/loot/ModLootTables.java @@ -13,24 +13,24 @@ import java.util.Map; public class ModLootTables { - public static final ResourceKey CRAB_TRAP_COMMON = key("gameplay/crab_trap/common"); - public static final ResourceKey CRAB_TRAP_RIVER = key("gameplay/crab_trap/river"); - public static final ResourceKey CRAB_TRAP_OCEAN = key("gameplay/crab_trap/ocean"); - public static final ResourceKey CRAB_TRAP_WARM_OCEAN = key("gameplay/crab_trap/warm_ocean"); - public static final ResourceKey CRAB_TRAP_SWAMP = key("gameplay/crab_trap/swamp"); - public static final ResourceKey CRAB_TRAP_JUNGLE = key("gameplay/crab_trap/jungle"); + public static final ResourceKey CRAB_TRAP_COMMON = ModLootTables.key("gameplay/crab_trap/common"); + public static final ResourceKey CRAB_TRAP_RIVER = ModLootTables.key("gameplay/crab_trap/river"); + public static final ResourceKey CRAB_TRAP_OCEAN = ModLootTables.key("gameplay/crab_trap/ocean"); + public static final ResourceKey CRAB_TRAP_WARM_OCEAN = ModLootTables.key("gameplay/crab_trap/warm_ocean"); + public static final ResourceKey CRAB_TRAP_SWAMP = ModLootTables.key("gameplay/crab_trap/swamp"); + public static final ResourceKey CRAB_TRAP_JUNGLE = ModLootTables.key("gameplay/crab_trap/jungle"); - public static final ResourceKey ADVANCEMENT_ROOT = key("advancement/root"); + public static final ResourceKey ADVANCEMENT_ROOT = ModLootTables.key("advancement/root"); public static final Map, LootTable> BEHEADING_LOOT = new HashMap<>(); - public static final ResourceKey BEHEADING_WITHER_SKELETON = beheadingKey(EntityType.WITHER_SKELETON); - public static final ResourceKey BEHEADING_ZOMBIE = beheadingKey(EntityType.ZOMBIE); - public static final ResourceKey BEHEADING_SKELETON = beheadingKey(EntityType.SKELETON); - public static final ResourceKey BEHEADING_CREEPER = beheadingKey(EntityType.CREEPER); - public static final ResourceKey BEHEADING_PIGLIN = beheadingKey(EntityType.PIGLIN); - public static final ResourceKey BEHEADING_ENDER_DRAGON = beheadingKey(EntityType.ENDER_DRAGON); - public static final ResourceKey BEHEADING_PLAYER = beheadingKey(EntityType.PLAYER); + public static final ResourceKey BEHEADING_WITHER_SKELETON = ModLootTables.beheadingKey(EntityType.WITHER_SKELETON); + public static final ResourceKey BEHEADING_ZOMBIE = ModLootTables.beheadingKey(EntityType.ZOMBIE); + public static final ResourceKey BEHEADING_SKELETON = ModLootTables.beheadingKey(EntityType.SKELETON); + public static final ResourceKey BEHEADING_CREEPER = ModLootTables.beheadingKey(EntityType.CREEPER); + public static final ResourceKey BEHEADING_PIGLIN = ModLootTables.beheadingKey(EntityType.PIGLIN); + public static final ResourceKey BEHEADING_ENDER_DRAGON = ModLootTables.beheadingKey(EntityType.ENDER_DRAGON); + public static final ResourceKey BEHEADING_PLAYER = ModLootTables.beheadingKey(EntityType.PLAYER); private static ResourceKey key(String path) { return ResourceKey.create(Registries.LOOT_TABLE, AnvilCraft.of(path)); @@ -38,14 +38,14 @@ private static ResourceKey key(String path) { private static ResourceKey beheadingKey(EntityType entityType) { Identifier entityId = EntityType.getKey(entityType); - return key("entities/beheading/" + entityId.getNamespace() + '/' + entityId.getPath()); + return ModLootTables.key("entities/beheading/" + entityId.getNamespace() + '/' + entityId.getPath()); } public static LootTable getBeheadingLoot(Entity entity) { MinecraftServer server = entity.level().getServer(); if (server == null) return LootTable.EMPTY; EntityType entityType = entity.getType(); - return BEHEADING_LOOT.computeIfAbsent(entityType, - e -> server.reloadableRegistries().getLootTable(beheadingKey(entityType))); + return ModLootTables.BEHEADING_LOOT.computeIfAbsent(entityType, + e -> server.reloadableRegistries().getLootTable(ModLootTables.beheadingKey(entityType))); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModNumberProviderTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModNumberProviderTypes.java index 3d49564a9c..a3a523e3ea 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModNumberProviderTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModNumberProviderTypes.java @@ -15,19 +15,19 @@ public class ModNumberProviderTypes { private static final DeferredRegister> DF = DeferredRegister .create(ModRegistries.NUMBER_PROVIDER_TYPE, AnvilCraft.MOD_ID); - public static final DeferredHolder, ConstantValue.Type> CONSTANT = DF + public static final DeferredHolder, ConstantValue.Type> CONSTANT = ModNumberProviderTypes.DF .register("constant", ConstantValue.Type::new); - public static final DeferredHolder, BinomialDistributionGenerator.Type> BINOMIAL = DF + public static final DeferredHolder, BinomialDistributionGenerator.Type> BINOMIAL = ModNumberProviderTypes.DF .register("binomial", BinomialDistributionGenerator.Type::new); - public static final DeferredHolder, UniformGenerator.Type> UNIFORM = DF + public static final DeferredHolder, UniformGenerator.Type> UNIFORM = ModNumberProviderTypes.DF .register("uniform", UniformGenerator.Type::new); - public static final DeferredHolder, EnchantmentLevelProvider.Type> ENCHANTMENT_LEVEL = DF + public static final DeferredHolder, EnchantmentLevelProvider.Type> ENCHANTMENT_LEVEL = ModNumberProviderTypes.DF .register("enchantment_level", EnchantmentLevelProvider.Type::new); public static void register(IEventBus bus) { - DF.register(bus); + ModNumberProviderTypes.DF.register(bus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeOutcomeTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeOutcomeTypes.java index 071f944ea7..c5b17bb1a0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeOutcomeTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeOutcomeTypes.java @@ -17,26 +17,27 @@ public class ModRecipeOutcomeTypes { AnvilCraft.MOD_ID ); - public static final DeferredHolder, DamageAnvil.Type> DAMAGE_ANVIL = OUTCOME_TYPE.register( + public static final DeferredHolder, DamageAnvil.Type> DAMAGE_ANVIL = ModRecipeOutcomeTypes.OUTCOME_TYPE.register( "damage_anvil", DamageAnvil.Type::new ); - public static final DeferredHolder, ProduceHeat.Type> PRODUCE_HEAT = OUTCOME_TYPE.register( + public static final DeferredHolder, ProduceHeat.Type> PRODUCE_HEAT = ModRecipeOutcomeTypes.OUTCOME_TYPE.register( "produce_heat", ProduceHeat.Type::new ); - public static final DeferredHolder, RoyalPreferenceOutcome.Type> ROYAL_PREFERENCE = OUTCOME_TYPE.register( + public static final DeferredHolder, RoyalPreferenceOutcome.Type> ROYAL_PREFERENCE = + ModRecipeOutcomeTypes.OUTCOME_TYPE.register( "royal_preference", RoyalPreferenceOutcome.Type::new ); public static final DeferredHolder, ResentmentAmberOutcome.Type> RESENTMENT_AMBER = - OUTCOME_TYPE.register("resentment_amber", ResentmentAmberOutcome.Type::new); + ModRecipeOutcomeTypes.OUTCOME_TYPE.register("resentment_amber", ResentmentAmberOutcome.Type::new); public static final DeferredHolder, ConsumeBurningHeaterFuel.Type> - CONSUME_BURNING_HEATER_FUEL = OUTCOME_TYPE.register( + CONSUME_BURNING_HEATER_FUEL = ModRecipeOutcomeTypes.OUTCOME_TYPE.register( "consume_burning_heater_fuel", ConsumeBurningHeaterFuel.Type::new ); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipePredicateTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipePredicateTypes.java index a41456aab7..015e88fa7e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipePredicateTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipePredicateTypes.java @@ -13,17 +13,19 @@ public class ModRecipePredicateTypes { public static final DeferredRegister> PREDICATE_TYPE = DeferredRegister .create(LibRegistries.PREDICATE_TYPE_REGISTRY, AnvilCraft.MOD_ID); - public static final DeferredHolder, HasCauldron.Type> HAS_CAULDRON = PREDICATE_TYPE.register( + public static final DeferredHolder, HasCauldron.Type> HAS_CAULDRON = + ModRecipePredicateTypes.PREDICATE_TYPE.register( "has_cauldron", HasCauldron.Type::new ); - public static final DeferredHolder, HasAnvil.Type> HAS_ANVIL = PREDICATE_TYPE.register( + public static final DeferredHolder, HasAnvil.Type> HAS_ANVIL = ModRecipePredicateTypes.PREDICATE_TYPE.register( "has_anvil", HasAnvil.Type::new ); - public static final DeferredHolder, HasDiffItems.Type> HAS_DIFF_ITEMS = PREDICATE_TYPE.register( + public static final DeferredHolder, HasDiffItems.Type> HAS_DIFF_ITEMS = + ModRecipePredicateTypes.PREDICATE_TYPE.register( "has_diff_items", HasDiffItems.Type::new ); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeTriggers.java b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeTriggers.java index bbdd185f2a..bbcc2e3a64 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeTriggers.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModRecipeTriggers.java @@ -10,7 +10,7 @@ public class ModRecipeTriggers { public static final DeferredRegister TRIGGER = DeferredRegister .create(LibRegistries.TRIGGER_REGISTRY, AnvilCraft.MOD_ID); - public static final DeferredHolder ON_ANVIL_FALL_ON = TRIGGER.register( + public static final DeferredHolder ON_ANVIL_FALL_ON = ModRecipeTriggers.TRIGGER.register( "on_anvil_fall_on", IRecipeTrigger.Impl::new ); diff --git a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModResultModifierTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModResultModifierTypes.java index 3c13d47988..413279ca22 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModResultModifierTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/recipe/ModResultModifierTypes.java @@ -18,28 +18,28 @@ public class ModResultModifierTypes { private static final DeferredRegister> DF = DeferredRegister .create(ModRegistries.MODIFIER_TYPE, AnvilCraft.MOD_ID); - public static final DeferredHolder, ApplyData.Type> APPLY_DATA = DF + public static final DeferredHolder, ApplyData.Type> APPLY_DATA = ModResultModifierTypes.DF .register("apply_data", ApplyData.Type::new); - public static final DeferredHolder, CopyData.Type> COPY_DATA = DF + public static final DeferredHolder, CopyData.Type> COPY_DATA = ModResultModifierTypes.DF .register("copy_data", CopyData.Type::new); - public static final DeferredHolder, MergeData.Type> MERGE_DATA = DF + public static final DeferredHolder, MergeData.Type> MERGE_DATA = ModResultModifierTypes.DF .register("merge_data", MergeData.Type::new); - public static final DeferredHolder, RemoveData.Type> REMOVE_DATA = DF + public static final DeferredHolder, RemoveData.Type> REMOVE_DATA = ModResultModifierTypes.DF .register("remove_data", RemoveData.Type::new); - public static final DeferredHolder, RemoveAttribute.Type> REMOVE_ATTRIBUTE = DF + public static final DeferredHolder, RemoveAttribute.Type> REMOVE_ATTRIBUTE = ModResultModifierTypes.DF .register("remove_attribute", RemoveAttribute.Type::new); - public static final DeferredHolder, ModifyCount.Type> MODIFY_COUNT = DF + public static final DeferredHolder, ModifyCount.Type> MODIFY_COUNT = ModResultModifierTypes.DF .register("modify_count", ModifyCount.Type::new); - public static final DeferredHolder, ChangeDataType.Type> CHANGE_DATA_TYPE = DF + public static final DeferredHolder, ChangeDataType.Type> CHANGE_DATA_TYPE = ModResultModifierTypes.DF .register("change_data_type", ChangeDataType.Type::new); public static void register(IEventBus bus) { - DF.register(bus); + ModResultModifierTypes.DF.register(bus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/init/registry/ModRegistryKeys.java b/src/main/java/dev/dubhe/anvilcraft/init/registry/ModRegistryKeys.java index 6b94dda506..810d178d1e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/registry/ModRegistryKeys.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/registry/ModRegistryKeys.java @@ -15,14 +15,14 @@ @EventBusSubscriber(modid = AnvilCraft.MOD_ID) public class ModRegistryKeys { - public static final ResourceKey>> AMULET_TYPE = key("amulet_type"); - public static final ResourceKey>> AMULET_DEF_TYPE = key("amulet_definition_type"); - public static final ResourceKey> AMULET_DEF = key("amulet_definition"); - public static final ResourceKey>> MODIFIER = key("result_modifier"); - public static final ResourceKey>> CUSTOM_DATA_TYPE = key("custom_data_component"); - public static final ResourceKey>> NUMBER_PROVIDER_TYPE = key("number_provider"); - public static final ResourceKey>> CATEGORY_TYPE = key("category_type"); - public static final ResourceKey> CATEGORY = key("category"); + public static final ResourceKey>> AMULET_TYPE = ModRegistryKeys.key("amulet_type"); + public static final ResourceKey>> AMULET_DEF_TYPE = ModRegistryKeys.key("amulet_definition_type"); + public static final ResourceKey> AMULET_DEF = ModRegistryKeys.key("amulet_definition"); + public static final ResourceKey>> MODIFIER = ModRegistryKeys.key("result_modifier"); + public static final ResourceKey>> CUSTOM_DATA_TYPE = ModRegistryKeys.key("custom_data_component"); + public static final ResourceKey>> NUMBER_PROVIDER_TYPE = ModRegistryKeys.key("number_provider"); + public static final ResourceKey>> CATEGORY_TYPE = ModRegistryKeys.key("category_type"); + public static final ResourceKey> CATEGORY = ModRegistryKeys.key("category"); @SubscribeEvent public static void registerRegistries(DataPackRegistryEvent.NewRegistry event) { diff --git a/src/main/java/dev/dubhe/anvilcraft/init/storage/ModCategoryTypes.java b/src/main/java/dev/dubhe/anvilcraft/init/storage/ModCategoryTypes.java index 292912102b..994c5fc5c0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/init/storage/ModCategoryTypes.java +++ b/src/main/java/dev/dubhe/anvilcraft/init/storage/ModCategoryTypes.java @@ -22,24 +22,26 @@ public class ModCategoryTypes { AnvilCraft.MOD_ID ); - public static final DeferredHolder, BlockCategory.Type> BLOCK = REGISTER + public static final DeferredHolder, BlockCategory.Type> BLOCK = ModCategoryTypes.REGISTER .register("block", BlockCategory.Type::new); - public static final DeferredHolder, UnstackableCategory.Type> UNSTACKABLE = REGISTER + public static final DeferredHolder, UnstackableCategory.Type> UNSTACKABLE = ModCategoryTypes.REGISTER .register("unstackable", UnstackableCategory.Type::new); - public static final DeferredHolder, AndCategory.Type> AND = REGISTER.register("and", AndCategory.Type::new); - public static final DeferredHolder, OrCategory.Type> OR = REGISTER.register("or", OrCategory.Type::new); - public static final DeferredHolder, HasComponentCategory.Type> HAS_COMPONENT = REGISTER + public static final DeferredHolder, AndCategory.Type> AND = ModCategoryTypes.REGISTER.register( + "and", AndCategory.Type::new); + public static final DeferredHolder, OrCategory.Type> OR = ModCategoryTypes.REGISTER.register( + "or", OrCategory.Type::new); + public static final DeferredHolder, HasComponentCategory.Type> HAS_COMPONENT = ModCategoryTypes.REGISTER .register("has_component", HasComponentCategory.Type::new); - public static final DeferredHolder, NamespaceCategory.Type> NAMESPACE = REGISTER + public static final DeferredHolder, NamespaceCategory.Type> NAMESPACE = ModCategoryTypes.REGISTER .register("namespace", NamespaceCategory.Type::new); - public static final DeferredHolder, CreativeModeTabCategory.Type> CREATIVE_MODE_TAB = REGISTER + public static final DeferredHolder, CreativeModeTabCategory.Type> CREATIVE_MODE_TAB = ModCategoryTypes.REGISTER .register("creative_mode_tab", CreativeModeTabCategory.Type::new); - public static final DeferredHolder, RecipeBookCategoryCategory.Type> RECIPE_BOOK_CATEGORY = REGISTER + public static final DeferredHolder, RecipeBookCategoryCategory.Type> RECIPE_BOOK_CATEGORY = ModCategoryTypes.REGISTER .register("recipe_book_category", RecipeBookCategoryCategory.Type::new); - public static final DeferredHolder, FilterCategory.Type> FILTER = REGISTER + public static final DeferredHolder, FilterCategory.Type> FILTER = ModCategoryTypes.REGISTER .register("filter", FilterCategory.Type::new); public static void register(IEventBus modEventBus) { - REGISTER.register(modEventBus); + ModCategoryTypes.REGISTER.register(modEventBus); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/IntegrationUtil.java b/src/main/java/dev/dubhe/anvilcraft/integration/IntegrationUtil.java index a19078d03a..e1de9fc5a8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/IntegrationUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/IntegrationUtil.java @@ -24,15 +24,15 @@ public class IntegrationUtil { public static Root root = Root.EMPTY; public static Root load() { - if (root != Root.EMPTY) return root; + if (IntegrationUtil.root != Root.EMPTY) return IntegrationUtil.root; try (InputStream stream = AnvilCraft.class.getClassLoader().getResourceAsStream("integrations.json")) { if (stream == null) return Root.EMPTY; InputStreamReader reader = new InputStreamReader(stream); JsonObject object = AnvilCraft.GSON.fromJson(reader, JsonObject.class); DataResult> result = Root.CODEC.decode(JsonOps.INSTANCE, object); Pair pair = result.getOrThrow(); - root = pair.getFirst(); - return root; + IntegrationUtil.root = pair.getFirst(); + return IntegrationUtil.root; } catch (Exception e) { AnvilCraft.LOGGER.error(e.getMessage(), e); } @@ -45,7 +45,7 @@ public record Root(Integrations integration, List additional) { Integrations.MAP_CODEC.fieldOf("integration").forGetter(Root::integration), Additional.MAP_CODEC.codec().listOf().optionalFieldOf("additional", List.of()).forGetter(Root::additional) ).apply(instance, Root::new)); - public static final Codec CODEC = MAP_CODEC.codec(); + public static final Codec CODEC = Root.MAP_CODEC.codec(); } public record Integrations( diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/iris/IrisState.java b/src/main/java/dev/dubhe/anvilcraft/integration/iris/IrisState.java index 84f6134f3e..a9e5547d98 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/iris/IrisState.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/iris/IrisState.java @@ -4,21 +4,17 @@ import dev.anvilcraft.lib.v2.integration.IntegrationType; import dev.dubhe.anvilcraft.client.init.ModRenderPipelines; import dev.dubhe.anvilcraft.client.renderer.RenderState; -import lombok.extern.java.Log; import lombok.extern.slf4j.Slf4j; import net.irisshaders.iris.api.v0.IrisApi; import net.irisshaders.iris.pipeline.IrisPipelines; import net.irisshaders.iris.pipeline.programs.ShaderKey; -import net.irisshaders.iris.pipeline.programs.ShaderOverrides; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; @Integration(value = "iris", type = IntegrationType.CLIENT) @Slf4j public class IrisState { public void applyClient() { - log.info("Iris integration loaded xwx"); + IrisState.log.info("Iris integration loaded xwx"); IrisPipelines.assignPipeline( ModRenderPipelines.LIGHTNING, ShaderKey.TEXTURED_COLOR @@ -31,7 +27,7 @@ public void applyClient() { public static boolean isShaderEnabled() { if (RenderState.isIrisPresent()) { - return isShaderEnabledInternal(); + return IrisState.isShaderEnabledInternal(); } return false; } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/CrabTrapBlockStateProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/CrabTrapBlockStateProvider.java index ea121e327a..d7838a43cc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/CrabTrapBlockStateProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/CrabTrapBlockStateProvider.java @@ -25,6 +25,6 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso @Override public Identifier getUid() { - return UID; + return CrabTrapBlockStateProvider.UID; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/HeatableBlockProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/HeatableBlockProvider.java index 0cb5688fa6..3a2672269d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/HeatableBlockProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/HeatableBlockProvider.java @@ -21,6 +21,6 @@ public void appendServerData(CompoundTag tag, BlockAccessor accessor) { @Override public Identifier getUid() { - return UID; + return HeatableBlockProvider.UID; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/ItemDetectorProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/ItemDetectorProvider.java index f56326680e..9b5ab4c458 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/ItemDetectorProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/ItemDetectorProvider.java @@ -22,6 +22,6 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso @Override public Identifier getUid() { - return UID; + return ItemDetectorProvider.UID; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/LargeFluidTankProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/LargeFluidTankProvider.java index 8530e87e9b..c3ffa5b9f0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/LargeFluidTankProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/LargeFluidTankProvider.java @@ -85,6 +85,6 @@ public boolean shouldRequestData(Accessor accessor) { @Override public Identifier getUid() { - return UID; + return LargeFluidTankProvider.UID; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/MultiPartPowerBlockProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/MultiPartPowerBlockProvider.java index 7dc7d83a41..45d450ca37 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/MultiPartPowerBlockProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/MultiPartPowerBlockProvider.java @@ -21,7 +21,7 @@ public enum MultiPartPowerBlockProvider implements IServerDataProvider multiPartBlock)) return; - PowerGrid grid = findPowerGrid(multiPartBlock, accessor.getLevel(), accessor.getPosition(), state); + PowerGrid grid = MultiPartPowerBlockProvider.findPowerGrid(multiPartBlock, accessor.getLevel(), accessor.getPosition(), state); if (grid == null) return; tag.putInt("generate", grid.getGenerate()); tag.putInt("consume", grid.getConsume()); @@ -35,13 +35,13 @@ public void appendServerData(CompoundTag tag, BlockAccessor accessor) { BlockState state ) { BlockPos mainPos = block.getMainPartPos(pos, state); - PowerGrid grid = getPowerGrid(level.getBlockEntity(mainPos)); + PowerGrid grid = MultiPartPowerBlockProvider.getPowerGrid(level.getBlockEntity(mainPos)); if (grid != null) return grid; for (P part : block.getParts()) { BlockPos partPos = pos.offset(block.offsetFrom(state, part)); if (partPos.equals(mainPos) || !level.getBlockState(partPos).is(block)) continue; - grid = getPowerGrid(level.getBlockEntity(partPos)); + grid = MultiPartPowerBlockProvider.getPowerGrid(level.getBlockEntity(partPos)); if (grid != null) return grid; } return null; diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/PowerBlockProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/PowerBlockProvider.java index 48365b1d9a..c335d173b6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/PowerBlockProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/PowerBlockProvider.java @@ -38,6 +38,6 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso @Override public Identifier getUid() { - return UID; + return PowerBlockProvider.UID; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/RubyPrismProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/RubyPrismProvider.java index 93325c6c1b..57ea3469d0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/RubyPrismProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/RubyPrismProvider.java @@ -21,6 +21,6 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso @Override public Identifier getUid() { - return UID; + return RubyPrismProvider.UID; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/SpaceOvercompressorProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/SpaceOvercompressorProvider.java index 1fcdd2fea9..1bd048d24c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/SpaceOvercompressorProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/SpaceOvercompressorProvider.java @@ -21,6 +21,6 @@ public void appendServerData(CompoundTag compoundTag, BlockAccessor blockAccesso @Override public Identifier getUid() { - return UID; + return SpaceOvercompressorProvider.UID; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/client/LargeFluidTankClientProvider.java b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/client/LargeFluidTankClientProvider.java index 320c422d90..4f09a5713c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/client/LargeFluidTankClientProvider.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jade/provider/client/LargeFluidTankClientProvider.java @@ -19,6 +19,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; public enum LargeFluidTankClientProvider implements IClientExtensionProvider { INSTANCE; @@ -29,7 +30,7 @@ public List> getClientGroups(Accessor accessor, Li for (ViewGroup group : groups) { List views = group.views.stream() .map(LargeFluidTankClientProvider::createView) - .filter(java.util.Objects::nonNull) + .filter(Objects::nonNull) .toList(); if (!views.isEmpty()) result.add(new ClientViewGroup<>(views)); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/AnvilCollisionCraftCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/AnvilCollisionCraftCategory.java index 469a5fe96e..3a74d77495 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/AnvilCollisionCraftCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/AnvilCollisionCraftCategory.java @@ -85,12 +85,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return AnvilCollisionCraftCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return AnvilCollisionCraftCategory.HEIGHT; } @Override @@ -111,12 +111,12 @@ public void setRecipe( // 如果有输出物品则添加到输出 if (!recipe.outputItems().isEmpty()) { - List chanceItemStacks = getChanceItemStacks(recipe); + List chanceItemStacks = AnvilCollisionCraftCategory.getChanceItemStacks(recipe); JeiItemUtil.addDefaultOutputSlots(builder, chanceItemStacks); } // 将被撞击的方块加入addInvisibleIngredients中 - JeiBlockIngredientUtil.addInputSlot(builder, HIT_BLOCK, 70, 24, 18, 18, recipe.hitBlock()); + JeiBlockIngredientUtil.addInputSlot(builder, AnvilCollisionCraftCategory.HIT_BLOCK, 70, 24, 18, 18, recipe.hitBlock()); // 将转换方块加入addInvisibleIngredients中 if (!recipe.transformBlocks().isEmpty()) { @@ -128,7 +128,7 @@ public void setRecipe( JeiBlockIngredientUtil.addSlot( builder, RecipeIngredientRole.INPUT, - TRANSFORM_INPUT_BLOCK, + AnvilCollisionCraftCategory.TRANSFORM_INPUT_BLOCK, x, 0, 18, @@ -142,7 +142,7 @@ public void setRecipe( JeiBlockIngredientUtil.addSlot( builder, RecipeIngredientRole.OUTPUT, - TRANSFORM_OUTPUT_BLOCK, + AnvilCollisionCraftCategory.TRANSFORM_OUTPUT_BLOCK, x, outputY, 18, @@ -193,7 +193,7 @@ public void draw( List hitBlockStates = recipe.hitBlock().constructStatesForRender(); if (!hitBlockStates.isEmpty()) { BlockState renderedState = JeiBlockIngredientUtil - .getDisplayedState(recipeSlotsView, HIT_BLOCK, hitBlockStates) + .getDisplayedState(recipeSlotsView, AnvilCollisionCraftCategory.HIT_BLOCK, hitBlockStates) .orElse(hitBlockStates.getFirst()); // 特判: 如果是大铁砧 则将BlockState改为cube=center,half=mid_center 并修改scale使其大小合理 // 建议下次写类似大铁砧的方块的时候 把registerDefaultState注册成有材质的中心位置 @@ -218,7 +218,7 @@ public void draw( .flatMap(transform -> transform.inputBlock().constructStatesForRender().stream()) .toList(); BlockState inputBlockRenderedState = JeiBlockIngredientUtil - .getDisplayedState(recipeSlotsView, TRANSFORM_INPUT_BLOCK, inputBlockStates) + .getDisplayedState(recipeSlotsView, AnvilCollisionCraftCategory.TRANSFORM_INPUT_BLOCK, inputBlockStates) .orElse(inputBlockStates.getFirst()); RenderSupport.renderBlock( graphics, @@ -232,7 +232,7 @@ public void draw( .map(transform -> transform.outputBlock().state()) .toList(); BlockState outputBlockState = JeiBlockIngredientUtil - .getDisplayedState(recipeSlotsView, TRANSFORM_OUTPUT_BLOCK, outputBlockStates) + .getDisplayedState(recipeSlotsView, AnvilCollisionCraftCategory.TRANSFORM_OUTPUT_BLOCK, outputBlockStates) .orElse(outputBlockStates.getFirst()); RenderSupport.renderBlock( graphics, @@ -266,7 +266,7 @@ public void draw( .flatMap(transform -> transform.inputBlock().constructStatesForRender().stream()) .toList(); BlockState inputBlockRenderedState = JeiBlockIngredientUtil - .getDisplayedState(recipeSlotsView, TRANSFORM_INPUT_BLOCK, inputBlockStates) + .getDisplayedState(recipeSlotsView, AnvilCollisionCraftCategory.TRANSFORM_INPUT_BLOCK, inputBlockStates) .orElse(inputBlockStates.getFirst()); RenderSupport.renderBlock( graphics, @@ -280,7 +280,7 @@ public void draw( .map(transform -> transform.outputBlock().state()) .toList(); BlockState outputBlockState = JeiBlockIngredientUtil - .getDisplayedState(recipeSlotsView, TRANSFORM_OUTPUT_BLOCK, outputBlockStates) + .getDisplayedState(recipeSlotsView, AnvilCollisionCraftCategory.TRANSFORM_OUTPUT_BLOCK, outputBlockStates) .orElse(outputBlockStates.getFirst()); RenderSupport.renderBlock( graphics, diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/BeaconConversionCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/BeaconConversionCategory.java index f3bd521654..d6c627282c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/BeaconConversionCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/BeaconConversionCategory.java @@ -78,12 +78,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return BeaconConversionCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return BeaconConversionCategory.HEIGHT; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ChargerChargingCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ChargerChargingCategory.java index 71c3f00281..9c0367a07f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ChargerChargingCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ChargerChargingCategory.java @@ -40,9 +40,9 @@ public class ChargerChargingCategory implements IRecipeCategory tooltip.add(this.centerTooltip)); @@ -122,7 +122,7 @@ public void setRecipe(IRecipeLayoutBuilder builder, DecayRecipe recipe, IFocusGr ? RecipeIngredientRole.INPUT : RecipeIngredientRole.CRAFTING_STATION; builder.addSlot(role, 27, 102) - .add(new ItemStack(block, countFixedNeighbors(recipe, block))) + .add(new ItemStack(block, DecayCategory.countFixedNeighbors(recipe, block))) .addRichTooltipCallback((recipeSlotView, tooltip) -> { tooltip.add(this.aroundTooltip); if (block != ModBlocks.CONFINEMENT_CHAMBER.get()) { @@ -152,7 +152,7 @@ public void createRecipeExtras(IRecipeExtrasBuilder builder, DecayRecipe recipe, IRecipeSlotDrawablesView recipeSlots = builder.getRecipeSlots(); List outputSlots = recipeSlots.getSlots(RecipeIngredientRole.OUTPUT); IScrollGridWidget scrollGridWidget = - builder.addScrollGridWidget(outputSlots, MAX_SHOWN_COLUMN, MAX_SHOWN_ROW); + builder.addScrollGridWidget(outputSlots, DecayCategory.MAX_SHOWN_COLUMN, DecayCategory.MAX_SHOWN_ROW); scrollGridWidget.setPosition( 60, 4, @@ -171,9 +171,9 @@ public void draw( double mouseX, double mouseY ) { - Block center = getDisplayedCenter(recipe, recipeSlotsView); + Block center = DecayCategory.getDisplayedCenter(recipe, recipeSlotsView); PreviewKey key = new PreviewKey(recipe, center); - LevelLike level = this.previewCache.computeIfAbsent(key, ignored -> createPreview(recipe, center)); + LevelLike level = this.previewCache.computeIfAbsent(key, ignored -> DecayCategory.createPreview(recipe, center)); RenderSupport.renderLevelLike(level, guiGraphics, 24, 36, 60, 12, 0.5f, false); this.slot.draw(guiGraphics, 7, 83); @@ -190,7 +190,7 @@ public void getTooltip( double mouseX, double mouseY ) { - if (!isImmediateDecay(recipe) + if (!DecayCategory.isImmediateDecay(recipe) && mouseX >= 5 && mouseX <= 45 && mouseY >= 15 && mouseY <= 65) { tooltip.add(this.randomTickTooltip); @@ -206,12 +206,12 @@ private static LevelLike createPreview(DecayRecipe recipe, Block center) { LevelLike preview = new LevelLike(Minecraft.getInstance().level); recipe.matchingNeighbors().forEach(pos -> preview.setBlockState(pos, center.defaultBlockState())); recipe.fixedNeighbors().forEach((pos, block) -> preview.setBlockState(pos, block.defaultBlockState())); - preview.setBlockState(CENTER_POS, center.defaultBlockState()); + preview.setBlockState(DecayCategory.CENTER_POS, center.defaultBlockState()); return preview; } private static Block getDisplayedCenter(DecayRecipe recipe, IRecipeSlotsView recipeSlotsView) { - return recipeSlotsView.findSlotByName(CENTER_SLOT) + return recipeSlotsView.findSlotByName(DecayCategory.CENTER_SLOT) .flatMap(IRecipeSlotView::getDisplayedItemStack) .map(ItemStack::getItem) .filter(BlockItem.class::isInstance) diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/EnergyWeaponCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/EnergyWeaponCategory.java index aea7a04015..3f6739eb15 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/EnergyWeaponCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/EnergyWeaponCategory.java @@ -54,12 +54,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return EnergyWeaponCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return EnergyWeaponCategory.HEIGHT; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/FluidMixingCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/FluidMixingCategory.java index 83ad97901b..800124f6b9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/FluidMixingCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/FluidMixingCategory.java @@ -92,12 +92,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return FluidMixingCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return FluidMixingCategory.HEIGHT; } @Override @@ -113,9 +113,9 @@ public void setRecipe( ) { FluidMixingRecipe recipe = recipeHolder.value(); if (recipe instanceof ComplexFluidJeiRecipe complexRecipe) { - setComplexRecipe(builder, complexRecipe); + FluidMixingCategory.setComplexRecipe(builder, complexRecipe); } else { - setFluidMixingRecipe(builder, recipe); + FluidMixingCategory.setFluidMixingRecipe(builder, recipe); } } @@ -124,7 +124,7 @@ private static void setFluidMixingRecipe(IRecipeLayoutBuilder builder, FluidMixi IIngredientAcceptor bucketIngredients = builder.addInvisibleIngredients(RecipeIngredientRole.INPUT); for (int index = 0; index < ingredients.size(); index++) { SizedFluidIngredient ingredient = ingredients.get(index); - SlotPosition position = inputPosition(ingredients.size(), index); + SlotPosition position = FluidMixingCategory.inputPosition(ingredients.size(), index); IRecipeSlotBuilder recipeSlot = builder.addSlot( RecipeIngredientRole.INPUT, position.x() + 1, @@ -141,14 +141,14 @@ private static void setFluidMixingRecipe(IRecipeLayoutBuilder builder, FluidMixi List fluidResults = recipe.getFluidResults(); boolean splitOutputColumns = !itemResults.isEmpty() && !fluidResults.isEmpty(); for (int index = 0; index < itemResults.size(); index++) { - SlotPosition position = itemOutputPosition(itemResults.size(), index, splitOutputColumns); + SlotPosition position = FluidMixingCategory.itemOutputPosition(itemResults.size(), index, splitOutputColumns); builder.addSlot(RecipeIngredientRole.OUTPUT, position.x() + 1, position.y() + 1) .add(itemResults.get(index).copy()); } IIngredientAcceptor outputBuckets = builder.addInvisibleIngredients(RecipeIngredientRole.OUTPUT); for (int index = 0; index < fluidResults.size(); index++) { FluidStack fluid = fluidResults.get(index); - SlotPosition position = fluidOutputPosition(fluidResults.size(), index, splitOutputColumns); + SlotPosition position = FluidMixingCategory.fluidOutputPosition(fluidResults.size(), index, splitOutputColumns); builder.addSlot(RecipeIngredientRole.OUTPUT, position.x() + 1, position.y() + 1) .setFluidRenderer(fluid.getAmount(), true, 16, 16) .add(fluid.getFluid(), fluid.getAmount(), fluid.getComponentsPatch()); @@ -161,11 +161,11 @@ private static void setComplexRecipe(IRecipeLayoutBuilder builder, ComplexFluidJ List> fluidInputs = recipe.getDisplayFluidInputs(); List itemInputs = recipe.getInputItems(); int inputCount = fluidInputs.size() + itemInputs.size(); - int inputGridSize = recipe.isHeaterRequired() ? HEATER_INPUT_GRID_SIZE : inputCount; + int inputGridSize = recipe.isHeaterRequired() ? FluidMixingCategory.HEATER_INPUT_GRID_SIZE : inputCount; List fluidInputSlots = new ArrayList<>(fluidInputs.size()); for (int index = 0; index < fluidInputs.size(); index++) { - SlotPosition position = inputPosition(inputGridSize, index); - fluidInputSlots.add(addFluidSlot( + SlotPosition position = FluidMixingCategory.inputPosition(inputGridSize, index); + fluidInputSlots.add(FluidMixingCategory.addFluidSlot( builder, RecipeIngredientRole.INPUT, position, @@ -174,7 +174,7 @@ private static void setComplexRecipe(IRecipeLayoutBuilder builder, ComplexFluidJ )); } for (int index = 0; index < itemInputs.size(); index++) { - SlotPosition position = inputPosition(inputGridSize, fluidInputs.size() + index); + SlotPosition position = FluidMixingCategory.inputPosition(inputGridSize, fluidInputs.size() + index); JeiItemUtil.addSlotWithCount( builder, position.x() + 1, @@ -184,18 +184,18 @@ private static void setComplexRecipe(IRecipeLayoutBuilder builder, ComplexFluidJ } if (recipe.isHeaterRequired()) { builder.addSlot( - RecipeIngredientRole.RENDER_ONLY, - HEATER_POSITION.x() + 1, - HEATER_POSITION.y() + 1 + RecipeIngredientRole.RENDER_ONLY, + FluidMixingCategory.HEATER_POSITION.x() + 1, + FluidMixingCategory.HEATER_POSITION.y() + 1 ).addItemStacks(List.of(ModBlocks.HEATER.asStack(), ModBlocks.BURNING_HEATER.asStack())) - .addRichTooltipCallback((slotView, tooltip) -> tooltip.add(HEATER_ACTIVE)); + .addRichTooltipCallback((slotView, tooltip) -> tooltip.add(FluidMixingCategory.HEATER_ACTIVE)); } List itemResults = recipe.getDisplayItemResults(); List> fluidResults = recipe.getDisplayFluidResults(); boolean splitOutputColumns = !itemResults.isEmpty() && !fluidResults.isEmpty(); for (int index = 0; index < itemResults.size(); index++) { - SlotPosition position = itemOutputPosition(itemResults.size(), index, splitOutputColumns); + SlotPosition position = FluidMixingCategory.itemOutputPosition(itemResults.size(), index, splitOutputColumns); JeiItemUtil.addOutputSlot( builder, position.x() + 1, @@ -205,8 +205,8 @@ private static void setComplexRecipe(IRecipeLayoutBuilder builder, ComplexFluidJ } List fluidOutputSlots = new ArrayList<>(fluidResults.size()); for (int index = 0; index < fluidResults.size(); index++) { - SlotPosition position = fluidOutputPosition(fluidResults.size(), index, splitOutputColumns); - fluidOutputSlots.add(addFluidSlot( + SlotPosition position = FluidMixingCategory.fluidOutputPosition(fluidResults.size(), index, splitOutputColumns); + fluidOutputSlots.add(FluidMixingCategory.addFluidSlot( builder, RecipeIngredientRole.OUTPUT, position, @@ -258,20 +258,20 @@ public void draw( int fluidOutputCount; if (recipe instanceof ComplexFluidJeiRecipe complexRecipe) { int inputCount = complexRecipe.getDisplayFluidInputCount() + complexRecipe.getInputItems().size(); - int inputGridSize = complexRecipe.isHeaterRequired() ? HEATER_INPUT_GRID_SIZE : inputCount; + int inputGridSize = complexRecipe.isHeaterRequired() ? FluidMixingCategory.HEATER_INPUT_GRID_SIZE : inputCount; for (int index = 0; index < inputCount; index++) { - SlotPosition position = inputPosition(inputGridSize, index); + SlotPosition position = FluidMixingCategory.inputPosition(inputGridSize, index); this.slot.draw(guiGraphics, position.x(), position.y()); } if (complexRecipe.isHeaterRequired()) { - this.slot.draw(guiGraphics, HEATER_POSITION.x(), HEATER_POSITION.y()); + this.slot.draw(guiGraphics, FluidMixingCategory.HEATER_POSITION.x(), FluidMixingCategory.HEATER_POSITION.y()); } itemOutputCount = complexRecipe.getDisplayItemResults().size(); fluidOutputCount = complexRecipe.getDisplayFluidResultCount(); } else { int inputCount = recipe.getFluidIngredients().size(); for (int index = 0; index < inputCount; index++) { - SlotPosition position = inputPosition(inputCount, index); + SlotPosition position = FluidMixingCategory.inputPosition(inputCount, index); this.slot.draw(guiGraphics, position.x(), position.y()); } itemOutputCount = recipe.getItemResults().size(); @@ -280,11 +280,11 @@ public void draw( boolean splitOutputColumns = itemOutputCount > 0 && fluidOutputCount > 0; for (int index = 0; index < itemOutputCount; index++) { - SlotPosition position = itemOutputPosition(itemOutputCount, index, splitOutputColumns); + SlotPosition position = FluidMixingCategory.itemOutputPosition(itemOutputCount, index, splitOutputColumns); this.slot.draw(guiGraphics, position.x(), position.y()); } for (int index = 0; index < fluidOutputCount; index++) { - SlotPosition position = fluidOutputPosition(fluidOutputCount, index, splitOutputColumns); + SlotPosition position = FluidMixingCategory.fluidOutputPosition(fluidOutputCount, index, splitOutputColumns); this.slot.draw(guiGraphics, position.x(), position.y()); } @@ -292,8 +292,8 @@ public void draw( this.arrowOut.draw(guiGraphics, 99, 29); float anvilYOffset = JeiRenderHelper.getAnvilAnimationOffset(this.timer) / 3.0F; - RenderSupport.renderBlock(guiGraphics, this.giantAnvil, 71, 13 + anvilYOffset, MODEL_SCALE * 2); - RenderSupport.renderBlock(guiGraphics, this.largeCauldron, 71, 35, MODEL_SCALE * 2); + RenderSupport.renderBlock(guiGraphics, this.giantAnvil, 71, 13 + anvilYOffset, FluidMixingCategory.MODEL_SCALE * 2); + RenderSupport.renderBlock(guiGraphics, this.largeCauldron, 71, 35, FluidMixingCategory.MODEL_SCALE * 2); } private static SlotPosition inputPosition(int count, int index) { @@ -308,11 +308,11 @@ private static SlotPosition inputPosition(int count, int index) { } private static SlotPosition itemOutputPosition(int count, int index, boolean splitColumns) { - return new SlotPosition(splitColumns ? 119 : 129, outputRow(count, index)); + return new SlotPosition(splitColumns ? 119 : 129, FluidMixingCategory.outputRow(count, index)); } private static SlotPosition fluidOutputPosition(int count, int index, boolean splitColumns) { - return new SlotPosition(splitColumns ? 138 : 129, outputRow(count, index)); + return new SlotPosition(splitColumns ? 138 : 129, FluidMixingCategory.outputRow(count, index)); } private static int outputRow(int count, int index) { diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/JewelCraftingCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/JewelCraftingCategory.java index 51d4ff02a5..84abfd31a0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/JewelCraftingCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/JewelCraftingCategory.java @@ -63,12 +63,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return JewelCraftingCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return JewelCraftingCategory.HEIGHT; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MineralFountainCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MineralFountainCategory.java index 053319182e..7580a1e0ee 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MineralFountainCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MineralFountainCategory.java @@ -84,28 +84,28 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return MineralFountainCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return MineralFountainCategory.HEIGHT; } @Override - public @Nullable IDrawable getIcon() { + public IDrawable getIcon() { return this.icon; } @Override public void setRecipe(IRecipeLayoutBuilder builder, MineralFountainJeiRecipe recipe, IFocusGroup focuses) { - List sideStacks = getIngredientStacks(recipe.sideBlocks()); - for (int i = 0; i < SIDE_SLOT_AREAS.length && !sideStacks.isEmpty(); i++) { - int[] area = SIDE_SLOT_AREAS[i]; + List sideStacks = MineralFountainCategory.getIngredientStacks(recipe.sideBlocks()); + for (int i = 0; i < MineralFountainCategory.SIDE_SLOT_AREAS.length && !sideStacks.isEmpty(); i++) { + int[] area = MineralFountainCategory.SIDE_SLOT_AREAS[i]; JeiBlockIngredientUtil.addSlot( builder, RecipeIngredientRole.INPUT, - SIDE_BLOCK_PREFIX + i, + MineralFountainCategory.SIDE_BLOCK_PREFIX + i, area[0], area[1], area[2], @@ -114,26 +114,26 @@ public void setRecipe(IRecipeLayoutBuilder builder, MineralFountainJeiRecipe rec ); } - List fromStacks = getIngredientStacks(recipe.fromBlocks()); + List fromStacks = MineralFountainCategory.getIngredientStacks(recipe.fromBlocks()); if (!fromStacks.isEmpty()) { JeiBlockIngredientUtil.addSlot( - builder, RecipeIngredientRole.INPUT, FROM_BLOCK, 40, 28, 16, 13, fromStacks + builder, RecipeIngredientRole.INPUT, MineralFountainCategory.FROM_BLOCK, 40, 28, 16, 13, fromStacks ); } JeiBlockIngredientUtil.addSlot( builder, RecipeIngredientRole.OUTPUT, - OUTPUT_BLOCK, + MineralFountainCategory.OUTPUT_BLOCK, 118, 28, 16, 16, - getIngredientStacks(List.of(recipe.result().state())) + MineralFountainCategory.getIngredientStacks(List.of(recipe.result().state())) ).addRichTooltipCallback((slot, tooltip) -> { tooltip.addAll(JeiRecipeUtil.getTooltips(recipe.result().chance())); if (recipe.dimension() != null) { - tooltip.add(getDimensionName(recipe.dimension()).copy().withStyle(ChatFormatting.GRAY)); + tooltip.add(MineralFountainCategory.getDimensionName(recipe.dimension()).copy().withStyle(ChatFormatting.GRAY)); } }); @@ -162,32 +162,33 @@ public void draw( BlockState sideState = null; if (!sideBlocks.isEmpty()) { sideState = JeiBlockIngredientUtil - .getDisplayedState(recipeSlotsView, SIDE_BLOCK_PREFIX + 0, sideBlocks) + .getDisplayedState(recipeSlotsView, MineralFountainCategory.SIDE_BLOCK_PREFIX + 0, sideBlocks) .orElse(sideBlocks.getFirst()); - renderSideBlock(graphics, sideState, 0); - renderSideBlock(graphics, sideState, 1); + MineralFountainCategory.renderSideBlock(graphics, sideState, 0); + MineralFountainCategory.renderSideBlock(graphics, sideState, 1); } - RenderSupport.renderBlock(graphics, ModBlocks.MINERAL_FOUNTAIN.getDefaultState(), 48, 50, BLOCK_SCALE); + RenderSupport.renderBlock(graphics, ModBlocks.MINERAL_FOUNTAIN.getDefaultState(), 48, 50, MineralFountainCategory.BLOCK_SCALE); if (sideState != null) { - renderSideBlock(graphics, sideState, 2); - renderSideBlock(graphics, sideState, 3); + MineralFountainCategory.renderSideBlock(graphics, sideState, 2); + MineralFountainCategory.renderSideBlock(graphics, sideState, 3); } if (!recipe.fromBlocks().isEmpty()) { - JeiBlockIngredientUtil.getDisplayedState(recipeSlotsView, FROM_BLOCK, recipe.fromBlocks()).ifPresent(state -> - RenderSupport.renderBlock(graphics, state, 48, 39.5f, BLOCK_SCALE) + JeiBlockIngredientUtil.getDisplayedState(recipeSlotsView, MineralFountainCategory.FROM_BLOCK, recipe.fromBlocks()).ifPresent( + state -> + RenderSupport.renderBlock(graphics, state, 48, 39.5f, MineralFountainCategory.BLOCK_SCALE) ); } - RenderSupport.renderBlock(graphics, ModBlocks.MINERAL_FOUNTAIN.getDefaultState(), 126, 50, BLOCK_SCALE); + RenderSupport.renderBlock(graphics, ModBlocks.MINERAL_FOUNTAIN.getDefaultState(), 126, 50, MineralFountainCategory.BLOCK_SCALE); BlockState resultState = JeiBlockIngredientUtil.getRenderablePreviewState(recipe.result().state()); - RenderSupport.renderBlock(graphics, resultState, 126, 39.5f, BLOCK_SCALE); + RenderSupport.renderBlock(graphics, resultState, 126, 39.5f, MineralFountainCategory.BLOCK_SCALE); this.arrow.draw(graphics, 82, 37); if (recipe.dimension() != null) { - Component dimensionName = getDimensionName(recipe.dimension()).copy().withStyle(ChatFormatting.WHITE); + Component dimensionName = MineralFountainCategory.getDimensionName(recipe.dimension()).copy().withStyle(ChatFormatting.WHITE); graphics.text(Minecraft.getInstance().font, dimensionName, 126, 65, 0xFFFFFFFF, true); } } @@ -234,7 +235,7 @@ public static void registerRecipes(IRecipeRegistration registration) { Set sides = new LinkedHashSet<>(); for (RecipeHolder normalHolder : normalRecipes) { MineralFountainRecipe normalRecipe = normalHolder.value(); - if (sharesBlock(from, normalRecipe.fromBlock().constructStatesForRender())) { + if (MineralFountainCategory.sharesBlock(from, normalRecipe.fromBlock().constructStatesForRender())) { sides.addAll(normalRecipe.needBlock().constructStatesForRender()); } } @@ -252,8 +253,8 @@ public static void registerRecipeCatalysts(IRecipeCatalystRegistration registrat } private static void renderSideBlock(GuiGraphicsExtractor graphics, BlockState state, int index) { - int[] position = SIDE_POSITIONS[index]; - RenderSupport.renderBlock(graphics, state, position[0], position[1], BLOCK_SCALE); + int[] position = MineralFountainCategory.SIDE_POSITIONS[index]; + RenderSupport.renderBlock(graphics, state, position[0], position[1], MineralFountainCategory.BLOCK_SCALE); } private static List getIngredientStacks(List states) { diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MobTransformCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MobTransformCategory.java index 760d5f1f74..720e716109 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MobTransformCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/MobTransformCategory.java @@ -57,7 +57,7 @@ public MobTransformCategory(IGuiHelper helper) { this.slotDefault = JeiRenderHelper.getSlotDefault(helper); this.slotChoice = JeiRenderHelper.getSlotChoice(helper); this.slotProbability = JeiRenderHelper.getSlotProbability(helper); - this.title = Component.translatable(KEY_CATEGORY); + this.title = Component.translatable(MobTransformCategory.KEY_CATEGORY); this.arrowDefault = JeiRenderHelper.getArrowDefault(helper); } @@ -84,12 +84,12 @@ public Identifier getIdentifier(MobTransformJeiRecipe recipe) { @Override public int getWidth() { - return WIDTH; + return MobTransformCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return MobTransformCategory.HEIGHT; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/PortalConversionCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/PortalConversionCategory.java index ee514e5b5c..51c372c740 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/PortalConversionCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/PortalConversionCategory.java @@ -62,12 +62,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return PortalConversionCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return PortalConversionCategory.HEIGHT; } @Override @@ -78,11 +78,11 @@ public int getHeight() { @Override public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder holder, IFocusGroup focuses) { PortalConversionRecipe recipe = holder.value(); - JeiBlockIngredientUtil.addInputSlot(builder, INPUT_BLOCK, 4, 4, 18, 18, recipe.getInput()); + JeiBlockIngredientUtil.addInputSlot(builder, PortalConversionCategory.INPUT_BLOCK, 4, 4, 18, 18, recipe.getInput()); JeiBlockIngredientUtil.addSlot( builder, RecipeIngredientRole.OUTPUT, - OUTPUT_BLOCK, + PortalConversionCategory.OUTPUT_BLOCK, 142, 4, 18, @@ -112,7 +112,7 @@ public void draw( RENDER_INPUT: { List input = recipe.getInput().constructStatesForRender(); if (input.isEmpty()) break RENDER_INPUT; - BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, INPUT_BLOCK, input) + BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, PortalConversionCategory.INPUT_BLOCK, input) .orElse(input.getFirst()); JeiRenderHelper.renderBlockWithSlot( graphics, @@ -128,7 +128,7 @@ public void draw( List results = recipe.getResults().states(); if (!results.isEmpty()) { List resultStates = results.stream().map(result -> result.state().state()).toList(); - BlockState displayedState = JeiBlockIngredientUtil.getDisplayedState(view, OUTPUT_BLOCK, resultStates) + BlockState displayedState = JeiBlockIngredientUtil.getDisplayedState(view, PortalConversionCategory.OUTPUT_BLOCK, resultStates) .orElse(resultStates.getFirst()); WeightedChanceBlockStates.Entry result = results.stream() .filter(entry -> entry.state().state().is(displayedState.getBlock())) diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ProceduralProcessCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ProceduralProcessCategory.java index 55def51783..80a2819671 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ProceduralProcessCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/ProceduralProcessCategory.java @@ -44,7 +44,7 @@ public class ProceduralProcessCategory implements IRecipeCategory process)) continue; for (int blockIndex = 0; blockIndex < process.getInputBlocks().size(); blockIndex++) { - int y = blockIndex == 0 ? BLOCK_Y - 6 : BLOCK_Y + 12 + 10 * (blockIndex - 1); + int y = blockIndex == 0 ? ProceduralProcessCategory.BLOCK_Y - 6 + : ProceduralProcessCategory.BLOCK_Y + 12 + 10 * (blockIndex - 1); int height = blockIndex == 0 ? 18 : 10; JeiBlockIngredientUtil.addInputSlot( builder, - stepBlockSlotName(index, blockIndex), - stepX(index, visibleSteps) - 9, + ProceduralProcessCategory.stepBlockSlotName(index, blockIndex), + ProceduralProcessCategory.stepX(index, visibleSteps) - 9, y, 18, height, @@ -133,8 +135,8 @@ public void setRecipe( ItemIngredientPredicate ingredient = process.getInputItems().getFirst(); IRecipeSlotBuilder slotBuilder = builder.addSlot( RecipeIngredientRole.INPUT, - stepX(index, visibleSteps) - 8, - ITEM_Y + 1 + ProceduralProcessCategory.stepX(index, visibleSteps) - 8, + ProceduralProcessCategory.ITEM_Y + 1 ); slotBuilder.addItemStacks( Arrays.stream(ingredient.getItems()).map(ItemStackTemplate::create).toList() @@ -158,55 +160,56 @@ public void draw( double mouseY ) { ProceduralProcessRecipe recipe = holder.value(); - renderPredicate( - graphics, view, INITIAL_BLOCK, recipe.getInitialBlock(), 0, holder, STEP_X - 20, BLOCK_Y, 18 + ProceduralProcessCategory.renderPredicate( + graphics, view, ProceduralProcessCategory.INITIAL_BLOCK, recipe.initialBlock(), 0, holder, + ProceduralProcessCategory.STEP_X - 20, ProceduralProcessCategory.BLOCK_Y, 18 ); - int visibleSteps = Math.min(recipe.getSteps().size(), MAX_VISIBLE_STEPS); - int displayedLoop = getDisplayedLoop(recipe); + int visibleSteps = Math.min(recipe.steps().size(), ProceduralProcessCategory.MAX_VISIBLE_STEPS); + int displayedLoop = ProceduralProcessCategory.getDisplayedLoop(recipe); for (int index = 0; index < visibleSteps; index++) { - ProceduralProcessStep step = getDisplayedStep(recipe, index, displayedLoop); + ProceduralProcessStep step = ProceduralProcessCategory.getDisplayedStep(recipe, index, displayedLoop); if (!(step.getContent() instanceof AbstractProcessRecipe process)) continue; - int x = stepX(index, visibleSteps); + int x = ProceduralProcessCategory.stepX(index, visibleSteps); RenderSupport.renderBlock(graphics, Blocks.ANVIL.defaultBlockState(), x - 10, 3, 20); if (!process.getInputItems().isEmpty()) { - this.slot.draw(graphics, x - 9, ITEM_Y); + this.slot.draw(graphics, x - 9, ProceduralProcessCategory.ITEM_Y); } List inputBlocks = process.getInputBlocks(); for (int inputIndex = inputBlocks.size() - 1; inputIndex >= 0; inputIndex--) { - renderPredicate( + ProceduralProcessCategory.renderPredicate( graphics, view, - stepBlockSlotName(index, inputIndex), + ProceduralProcessCategory.stepBlockSlotName(index, inputIndex), inputBlocks.get(inputIndex), - displayedLoop * recipe.getSteps().size() + index, + displayedLoop * recipe.steps().size() + index, holder, x - 9, - BLOCK_Y + inputIndex * 10, + ProceduralProcessCategory.BLOCK_Y + inputIndex * 10, 18 ); } } - this.longArrow.draw(graphics, WIDTH / 2 - 32, FLOW_Y + 4); - if (recipe.getLoop() > 1) { - this.cycle.draw(graphics, WIDTH / 2 + 47, FLOW_Y); + this.longArrow.draw(graphics, ProceduralProcessCategory.WIDTH / 2 - 32, ProceduralProcessCategory.FLOW_Y + 4); + if (recipe.loop() > 1) { + this.cycle.draw(graphics, ProceduralProcessCategory.WIDTH / 2 + 47, ProceduralProcessCategory.FLOW_Y); AgeratumUtil.renderText( graphics, - Component.literal(String.valueOf(recipe.getLoop())), - WIDTH / 2 + 68, - FLOW_Y + 4, + Component.literal(String.valueOf(recipe.loop())), + ProceduralProcessCategory.WIDTH / 2 + 68, + ProceduralProcessCategory.FLOW_Y + 4, 1.2F ); } - BlockState outputState = JeiBlockIngredientUtil.getRenderablePreviewState(recipe.getResultBlock().state()); + BlockState outputState = JeiBlockIngredientUtil.getRenderablePreviewState(recipe.resultBlock().state()); int outputScale = JeiBlockIngredientUtil.getRenderablePreviewScale(outputState, 20); - RenderSupport.renderBlock(graphics, outputState, 142, BLOCK_Y, outputScale); + RenderSupport.renderBlock(graphics, outputState, 142, ProceduralProcessCategory.BLOCK_Y, outputScale); } private static int stepX(int index, int visibleSteps) { - int gap = STEPS_LENGTH / Math.max(visibleSteps, 1) - STEP_LENGTH; - return STEP_X + gap / 2 + index * (STEP_LENGTH + gap); + int gap = ProceduralProcessCategory.STEPS_LENGTH / Math.max(visibleSteps, 1) - ProceduralProcessCategory.STEP_LENGTH; + return ProceduralProcessCategory.STEP_X + gap / 2 + index * (ProceduralProcessCategory.STEP_LENGTH + gap); } private static void renderPredicate( @@ -247,8 +250,8 @@ private static String stepBlockSlotName(int step, int block) { } private static int getDisplayedLoop(ProceduralProcessRecipe recipe) { - if (recipe.getLoop() <= 1) return 0; - return (int) ((System.currentTimeMillis() / LOOP_CYCLE_MILLIS) % recipe.getLoop()); + if (recipe.loop() <= 1) return 0; + return (int) ((System.currentTimeMillis() / ProceduralProcessCategory.LOOP_CYCLE_MILLIS) % recipe.loop()); } private static ProceduralProcessStep getDisplayedStep( @@ -257,8 +260,8 @@ private static ProceduralProcessStep getDisplayedStep( int displayedLoop ) { if (stepIndex == 0 && displayedLoop > 0) { - return recipe.getMultiLoopFirstStep().orElse(recipe.getSteps().getFirst()); + return recipe.multiLoopFirstStep().orElse(recipe.steps().getFirst()); } - return recipe.getSteps().get(stepIndex); + return recipe.steps().get(stepIndex); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/AbstractProgressCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/AbstractProgressCategory.java index 144931e070..40ca3835d8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/AbstractProgressCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/AbstractProgressCategory.java @@ -48,12 +48,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return AbstractProgressCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return AbstractProgressCategory.HEIGHT; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCompressCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCompressCategory.java index 348c37fc16..c550514167 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCompressCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCompressCategory.java @@ -65,12 +65,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return BlockCompressCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return BlockCompressCategory.HEIGHT; } @Override @@ -85,7 +85,7 @@ public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder input = recipe.getInputBlocks().get(i).constructStatesForRender(); if (input.isEmpty()) continue; BlockState renderedState = JeiBlockIngredientUtil - .getDisplayedState(view, INPUT_BLOCK_PREFIX + i, input) + .getDisplayedState(view, BlockCompressCategory.INPUT_BLOCK_PREFIX + i, input) .orElse(input.getFirst()); RenderSupport.renderBlock(graphics, renderedState, 40, 30 + 10 * i, 20); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCrushCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCrushCategory.java index 5bc290f23d..b870916115 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCrushCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockCrushCategory.java @@ -64,12 +64,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return BlockCrushCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return BlockCrushCategory.HEIGHT; } @Override @@ -80,7 +80,7 @@ public IDrawable getIcon() { @Override public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder recipeHolder, IFocusGroup focuses) { BlockCrushRecipe recipe = recipeHolder.value(); - JeiBlockIngredientUtil.addInputSlot(builder, INPUT_BLOCK, 40, 42, 18, 10, recipe.getFirstInputBlock()); + JeiBlockIngredientUtil.addInputSlot(builder, BlockCrushCategory.INPUT_BLOCK, 40, 42, 18, 10, recipe.getFirstInputBlock()); JeiBlockIngredientUtil.addSlot( builder, RecipeIngredientRole.OUTPUT, @@ -115,7 +115,7 @@ public void draw( renderInput: { List input = recipe.getFirstInputBlock().constructStatesForRender(); if (input.isEmpty()) break renderInput; - BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, INPUT_BLOCK, input) + BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, BlockCrushCategory.INPUT_BLOCK, input) .orElse(input.getFirst()); RenderSupport.renderBlock(graphics, renderedState, 40, 40, 20); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockSmearCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockSmearCategory.java index 35f132a4a0..a8e1984fba 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockSmearCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/BlockSmearCategory.java @@ -66,12 +66,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return BlockSmearCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return BlockSmearCategory.HEIGHT; } @Override @@ -86,11 +86,11 @@ public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder input = recipe.getInputBlocks().get(i).constructStatesForRender(); if (input.isEmpty()) continue; BlockState renderedState = JeiBlockIngredientUtil - .getDisplayedState(view, INPUT_BLOCK_PREFIX + i, input) + .getDisplayedState(view, BlockSmearCategory.INPUT_BLOCK_PREFIX + i, input) .orElse(input.getFirst()); RenderSupport.renderBlock(graphics, renderedState, 40, 30 + 10 * i, 20); } @@ -136,7 +136,7 @@ public void draw( RenderSupport.renderBlock(graphics, recipe.getFirstResultBlock().state(), 100, 40, 20); List input = recipe.getFirstInputBlock().constructStatesForRender(); - BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, RESULT_INPUT_BLOCK, input) + BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, BlockSmearCategory.RESULT_INPUT_BLOCK, input) .orElse(input.getFirst()); RenderSupport.renderBlock(graphics, renderedState, 100, 30, 20); RenderSupport.renderBlock(graphics, Blocks.ANVIL.defaultBlockState(), 100, 20, 20); diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemCompressCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemCompressCategory.java index cc26c35d77..e489d57519 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemCompressCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemCompressCategory.java @@ -65,8 +65,8 @@ public void setRecipe( IFocusGroup focuses ) { ItemCompressRecipe recipe = recipeHolder.value(); - boolean powered = recipeHolder.id().identifier().getPath().equals(SUPERCAPACITOR); - boolean normal = recipeHolder.id().identifier().getPath().equals(EMPTY_SUPERCAPACITOR); + boolean powered = recipeHolder.id().identifier().getPath().equals(ItemCompressCategory.SUPERCAPACITOR); + boolean normal = recipeHolder.id().identifier().getPath().equals(ItemCompressCategory.EMPTY_SUPERCAPACITOR); if (!powered && !normal) { super.setRecipe(builder, recipeHolder, focuses); return; @@ -74,7 +74,7 @@ public void setRecipe( List inputs = recipe.getInputItems(); JeiSlotUtil.addSlotWithCount(builder, 11, JeiSlotUtil.DEFAULT_Y, inputs.getFirst()); builder.addSlot(RecipeIngredientRole.INPUT, 30, JeiSlotUtil.ITEM_Y) - .add(resinWithCreeper(powered)) + .add(ItemCompressCategory.resinWithCreeper(powered)) .addRichTooltipCallback((slotView, tooltip) -> tooltip.add(Component.translatable(powered ? "gui.anvilcraft.category.item_compress.supercapacitor.resin" @@ -106,7 +106,7 @@ public void draw( this.arrowOutFromBelow.draw(graphics, 92, 29); JeiSlotUtil.drawDefaultInputSlots(graphics, this.slotDefault, recipe.getInputItems().size()); - if (recipeHolder.id().identifier().getPath().equals(SUPERCAPACITOR) + if (recipeHolder.id().identifier().getPath().equals(ItemCompressCategory.SUPERCAPACITOR) || JeiRecipeUtil.isChance(recipe.getResultItems())) { JeiSlotUtil.drawDefaultOutputSlots(graphics, this.slotProbability, recipe.getResultItems().size()); } else { @@ -119,8 +119,8 @@ public static void registerRecipes(IRecipeRegistration registration) { JeiRecipeUtil.getRecipeHoldersFromType(ModRecipeTypes.ITEM_COMPRESS.get()) ); recipes.add(new RecipeHolder<>( - ResourceKey.create(Registries.RECIPE, AnvilCraft.of(SUPERCAPACITOR)), - specialSupercapacitorRecipe() + ResourceKey.create(Registries.RECIPE, AnvilCraft.of(ItemCompressCategory.SUPERCAPACITOR)), + ItemCompressCategory.specialSupercapacitorRecipe() )); registration.addRecipes( AnvilCraftJeiPlugin.ITEM_COMPRESS, @@ -132,7 +132,7 @@ private static ItemCompressRecipe specialSupercapacitorRecipe() { HolderGetter items = RegistryUtil.getRegistryAccess().lookupOrThrow(Registries.ITEM); return ItemCompressRecipe.builder() .requires(items, ModItemTags.IRON_PLATES, 2) - .requires(ItemStackTemplate.fromNonEmptyStack(resinWithCreeper(true))) + .requires(ItemStackTemplate.fromNonEmptyStack(ItemCompressCategory.resinWithCreeper(true))) .result(ModItems.SUPER_CAPACITOR) .buildRecipe(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemInjectCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemInjectCategory.java index 04986e21ad..5c7b2e976b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemInjectCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/ItemInjectCategory.java @@ -88,12 +88,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return ItemInjectCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return ItemInjectCategory.HEIGHT; } @Override @@ -104,7 +104,7 @@ public IDrawable getIcon() { @Override public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder recipeHolder, IFocusGroup focuses) { ItemInjectRecipe recipe = recipeHolder.value(); - int transcendiumTier = getTranscendiumTier(recipeHolder); + int transcendiumTier = ItemInjectCategory.getTranscendiumTier(recipeHolder); if (transcendiumTier >= 0) { IRecipeSlotBuilder inputSlot = builder.addSlot( RecipeIngredientRole.INPUT, @@ -126,11 +126,11 @@ public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder= 0) { - addTranscendiumOutputSlots(builder, recipe, transcendiumTier); + ItemInjectCategory.addTranscendiumOutputSlots(builder, recipe, transcendiumTier); } else { - addOutputSlots(builder, recipe); + ItemInjectCategory.addOutputSlots(builder, recipe); } if (!recipe.getResultBlocks().isEmpty()) { JeiBlockIngredientUtil.addSlot( @@ -138,7 +138,7 @@ public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder input = recipe.getFirstInputBlock().constructStatesForRender(); if (input.isEmpty()) return; - BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, INPUT_BLOCK, input) + BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(view, ItemInjectCategory.INPUT_BLOCK, input) .orElse(input.getFirst()); boolean giantAnvil = renderedState.getBlock() instanceof GiantAnvilBlock; int inputScale = giantAnvil ? 13 : JeiBlockIngredientUtil.getRenderablePreviewScale(renderedState, 20); @@ -177,7 +177,7 @@ public void draw( this.arrowOut.draw(graphics, 92, 29); JeiSlotUtil.drawDefaultInputSlots(graphics, this.slotDefault, recipe.getInputItems().size()); - int transcendiumTier = getTranscendiumTier(recipeHolder); + int transcendiumTier = ItemInjectCategory.getTranscendiumTier(recipeHolder); if (transcendiumTier >= 0) { this.drawTranscendiumOutputSlots(graphics, transcendiumTier); } else if (!recipe.getResultItems().isEmpty()) { @@ -219,7 +219,7 @@ public void getTooltip( tooltip.addAll(TooltipUtil.tooltip(states.getFirst().getBlock())); } } - int outputY = getOutputBlockSlotY(recipe, getTranscendiumTier(recipeHolder)); + int outputY = ItemInjectCategory.getOutputBlockSlotY(recipe, ItemInjectCategory.getTranscendiumTier(recipeHolder)); if (!recipe.getResultBlocks().isEmpty() && MathUtil.isInRange(mouseX, mouseY, 124, outputY, 140, outputY + 18)) { Block block = recipe.getFirstResultBlock().state().getBlock(); @@ -238,7 +238,7 @@ private static void addOutputSlots(IRecipeLayoutBuilder builder, ItemInjectRecip return; } for (int index = 0; index < recipe.getResultItems().size(); index++) { - addOutputSlot(builder, 107 + index * 19, 15, recipe.getResultItems().get(index)); + ItemInjectCategory.addOutputSlot(builder, 107 + index * 19, 15, recipe.getResultItems().get(index)); } } @@ -249,30 +249,30 @@ private static void addTranscendiumOutputSlots( ) { List results = recipe.getResultItems(); switch (tier) { - case 0 -> addOutputSlot(builder, 125, 24, results.getFirst()); + case 0 -> ItemInjectCategory.addOutputSlot(builder, 125, 24, results.getFirst()); case 1 -> { - addOutputSlot(builder, 116, 15, results.get(0)) + ItemInjectCategory.addOutputSlot(builder, 116, 15, results.get(0)) .addRichTooltipCallback((slotView, tooltip) -> tooltip.add(Component.translatable( "gui.anvilcraft.category.item_inject.transcendium.chance" ).withStyle(ChatFormatting.GRAY))); - addOutputSlot(builder, 134, 15, results.get(1)); - addOutputSlot(builder, 116, 33, results.get(2)) + ItemInjectCategory.addOutputSlot(builder, 134, 15, results.get(1)); + ItemInjectCategory.addOutputSlot(builder, 116, 33, results.get(2)) .addRichTooltipCallback((slotView, tooltip) -> tooltip.add(Component.translatable( "gui.anvilcraft.category.item_inject.transcendium.amount_x3" ).withStyle(ChatFormatting.GOLD))); } case 2 -> { - addOutputSlot(builder, 116, 15, results.get(0)); - addOutputSlot(builder, 134, 15, results.get(1)); - addOutputSlot(builder, 116, 33, results.get(2)) + ItemInjectCategory.addOutputSlot(builder, 116, 15, results.get(0)); + ItemInjectCategory.addOutputSlot(builder, 134, 15, results.get(1)); + ItemInjectCategory.addOutputSlot(builder, 116, 33, results.get(2)) .addRichTooltipCallback((slotView, tooltip) -> tooltip.add(Component.translatable( "gui.anvilcraft.category.item_inject.transcendium.amount_x3" ).withStyle(ChatFormatting.GOLD))); } - case 3 -> addOutputSlot(builder, 125, 15, results.getFirst()); + case 3 -> ItemInjectCategory.addOutputSlot(builder, 125, 15, results.getFirst()); case 4 -> { - addOutputSlot(builder, 116, 15, results.get(0)); - addOutputSlot(builder, 134, 15, results.get(1)) + ItemInjectCategory.addOutputSlot(builder, 116, 15, results.get(0)); + ItemInjectCategory.addOutputSlot(builder, 134, 15, results.get(1)) .addRichTooltipCallback((slotView, tooltip) -> tooltip.add(Component.translatable( "gui.anvilcraft.category.item_inject.transcendium.amount_x1" ).withStyle(ChatFormatting.GOLD))); @@ -322,15 +322,15 @@ private static int getOutputBlockSlotY(ItemInjectRecipe recipe, int transcendium private static int getTranscendiumTier(RecipeHolder recipeHolder) { String path = recipeHolder.id().identifier().getPath(); - if (!path.startsWith(TRANSCENDIUM_PREFIX)) return -1; - return Integer.parseInt(path.substring(TRANSCENDIUM_PREFIX.length())); + if (!path.startsWith(ItemInjectCategory.TRANSCENDIUM_PREFIX)) return -1; + return Integer.parseInt(path.substring(ItemInjectCategory.TRANSCENDIUM_PREFIX.length())); } public static void registerRecipes(IRecipeRegistration registration) { List> recipes = new ArrayList<>( JeiRecipeUtil.getRecipeHoldersFromType(ModRecipeTypes.ITEM_INJECT.get()) ); - recipes.addAll(getTranscendiumRecipes()); + recipes.addAll(ItemInjectCategory.getTranscendiumRecipes()); registration.addRecipes( AnvilCraftJeiPlugin.ITEM_INJECT, recipes diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MassInjectCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MassInjectCategory.java index d83390d184..8942d233a3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MassInjectCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MassInjectCategory.java @@ -75,12 +75,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return MassInjectCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return MassInjectCategory.HEIGHT; } @Override @@ -96,12 +96,13 @@ public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder tooltip.add( - Component.translatable(KEY_MASS_NEEDED, SpaceOvercompressorBlockEntity.DISPLAYED_MASS).withStyle(ChatFormatting.GOLD) + Component.translatable(MassInjectCategory.KEY_MASS_NEEDED, SpaceOvercompressorBlockEntity.DISPLAYED_MASS) + .withStyle(ChatFormatting.GOLD) )); JeiBlockIngredientUtil.addSlot( builder, RecipeIngredientRole.CRAFTING_STATION, - SPACE_OVERCOMPRESSOR, + MassInjectCategory.SPACE_OVERCOMPRESSOR, 72, 34, 18, @@ -141,7 +142,7 @@ public void draw( pose.scale(0.8F, 0.8F); graphics.text( Minecraft.getInstance().font, - Component.translatable(KEY_MASS_VALUE, recipe.displayMassValue()), + Component.translatable(MassInjectCategory.KEY_MASS_VALUE, recipe.displayMassValue()), 0, 10, 0xFF000000, @@ -149,7 +150,8 @@ public void draw( ); graphics.text( Minecraft.getInstance().font, - Component.translatable(KEY_ITEMS_NEEDED, Math.ceilDiv(SpaceOvercompressorBlockEntity.NEUTRONIUM_INGOT_MASS, recipe.getMass())), + Component.translatable( + MassInjectCategory.KEY_ITEMS_NEEDED, Math.ceilDiv(SpaceOvercompressorBlockEntity.NEUTRONIUM_INGOT_MASS, recipe.getMass())), 0, 70, 0xFF000000, diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MeshRecipeCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MeshRecipeCategory.java index 66ac37071a..2dcd0b8b75 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MeshRecipeCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/MeshRecipeCategory.java @@ -61,12 +61,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return MeshRecipeCategory.WIDTH; } @Override public int getHeight() { - return ROW_START + MeshRecipeGroup.maxRows * 18; + return MeshRecipeCategory.ROW_START + MeshRecipeGroup.maxRows * 18; } @Override @@ -82,7 +82,8 @@ public void setRecipe(IRecipeLayoutBuilder builder, MeshRecipeGroup recipe, IFoc for (int i = 0; i < recipe.results().size(); i++) { MeshRecipeGroup.Result result = recipe.results().get(i); - IRecipeSlotBuilder slot = builder.addSlot(RecipeIngredientRole.OUTPUT, 1 + (i % 9) * 18, 1 + ROW_START + 18 * (i / 9)).add( + IRecipeSlotBuilder slot = builder.addSlot(RecipeIngredientRole.OUTPUT, 1 + (i % 9) * 18, 1 + MeshRecipeCategory.ROW_START + + 18 * (i / 9)).add( result.item()); JeiRecipeUtil.addTooltips(slot, result.item().count(), result.provider()); } @@ -105,7 +106,7 @@ public void draw( for (int row = 0; row < MeshRecipeGroup.maxRows; row++) { for (int column = 0; column < 9; column++) { - this.slotProbability.draw(graphics, column * 18, ROW_START + row * 18); + this.slotProbability.draw(graphics, column * 18, MeshRecipeCategory.ROW_START + row * 18); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/SqueezingCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/SqueezingCategory.java index 566661376a..25c149ebd8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/SqueezingCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/SqueezingCategory.java @@ -34,7 +34,6 @@ import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; -import org.jspecify.annotations.Nullable; import java.util.ArrayList; import java.util.List; @@ -78,16 +77,16 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return SqueezingCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return SqueezingCategory.HEIGHT; } @Override - public @Nullable IDrawable getIcon() { + public IDrawable getIcon() { return this.icon; } @@ -104,20 +103,21 @@ public void setRecipe( .flatMap(input -> input.getBlocks().stream()) .map(block -> new ItemStack(block.value())) .toList(); - JeiBlockIngredientUtil.addSlot(builder, RecipeIngredientRole.INPUT, INPUT_BLOCK, 40, 22, 18, 18, inputs); + JeiBlockIngredientUtil.addSlot(builder, RecipeIngredientRole.INPUT, SqueezingCategory.INPUT_BLOCK, 40, 22, 18, 18, inputs); } if (!recipe.getResultBlocks().isEmpty()) { List outputs = recipe.getResultBlocks().stream() .map(result -> new ItemStack(result.state().getBlock())) .toList(); - JeiBlockIngredientUtil.addSlot(builder, RecipeIngredientRole.OUTPUT, OUTPUT_BLOCK, 100, 22, 20, 18, outputs); + JeiBlockIngredientUtil.addSlot(builder, RecipeIngredientRole.OUTPUT, SqueezingCategory.OUTPUT_BLOCK, 100, 22, 20, 18, outputs); } for (ChanceItemStack output : recipe.getResultItems()) { builder.addInvisibleIngredients(RecipeIngredientRole.OUTPUT) .add(output.stack().withCount(output.getMaxCount())); } - JeiFluidUtil.addOutputSlot(builder, OUTPUT_FLUID, FLUID_X, FLUID_Y, 16, 16, recipe.getHasCauldron()); + JeiFluidUtil.addOutputSlot( + builder, SqueezingCategory.OUTPUT_FLUID, SqueezingCategory.FLUID_X, SqueezingCategory.FLUID_Y, 16, 16, recipe.getHasCauldron()); } @Override @@ -171,7 +171,7 @@ public void draw( input.addAll(predicate.constructStatesForRender()); } if (input.isEmpty()) return; - BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(recipeSlotsView, INPUT_BLOCK, input) + BlockState renderedState = JeiBlockIngredientUtil.getDisplayedState(recipeSlotsView, SqueezingCategory.INPUT_BLOCK, input) .orElse(input.getFirst()); RenderSupport.renderBlock(graphics, renderedState, 50, 30, 20); RenderSupport.renderBlock(graphics, Blocks.CAULDRON.defaultBlockState(), 50, 40, 20); @@ -180,13 +180,13 @@ public void draw( HasCauldronSimple cauldronFluid = recipe.getHasCauldron(); if (HasCauldron.isNotEmpty(cauldronFluid.transform())) { - this.slotDefault.draw(graphics, FLUID_X - 1, FLUID_Y - 1); + this.slotDefault.draw(graphics, SqueezingCategory.FLUID_X - 1, SqueezingCategory.FLUID_Y - 1); } List result = recipe.getResultBlocks(); if (result.isEmpty()) return; List resultStates = result.stream().map(ChanceBlockState::state).toList(); - renderedState = JeiBlockIngredientUtil.getDisplayedState(recipeSlotsView, OUTPUT_BLOCK, resultStates) + renderedState = JeiBlockIngredientUtil.getDisplayedState(recipeSlotsView, SqueezingCategory.OUTPUT_BLOCK, resultStates) .orElse(resultStates.getFirst()); RenderSupport.renderBlock(graphics, renderedState, 110, 30, 20); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/AbstractLiquidCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/AbstractLiquidCategory.java index 373d220a71..a7350af958 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/AbstractLiquidCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/AbstractLiquidCategory.java @@ -62,12 +62,12 @@ public Component getTitle() { @Override public int getWidth() { - return WIDTH; + return AbstractLiquidCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return AbstractLiquidCategory.HEIGHT; } @Override @@ -98,9 +98,9 @@ public void setRecipe( } if (hasInputFluid) { if (inputMixed) { - JeiFluidUtil.addFluidInputSlot(builder, INPUT_FLUID, 16, 16, cauldron); + JeiFluidUtil.addFluidInputSlot(builder, AbstractLiquidCategory.INPUT_FLUID, 16, 16, cauldron); } else { - JeiFluidUtil.addDefaultInputSlot(builder, INPUT_FLUID, 16, 16, cauldron); + JeiFluidUtil.addDefaultInputSlot(builder, AbstractLiquidCategory.INPUT_FLUID, 16, 16, cauldron); } } @@ -114,9 +114,9 @@ public void setRecipe( } if (hasOutputFluid) { if (outputMixed) { - JeiFluidUtil.addFluidOutputSlot(builder, OUTPUT_FLUID, 16, 16, cauldron); + JeiFluidUtil.addFluidOutputSlot(builder, AbstractLiquidCategory.OUTPUT_FLUID, 16, 16, cauldron); } else { - JeiFluidUtil.addDefaultOutputSlot(builder, OUTPUT_FLUID, 16, 16, cauldron); + JeiFluidUtil.addDefaultOutputSlot(builder, AbstractLiquidCategory.OUTPUT_FLUID, 16, 16, cauldron); } } } @@ -199,7 +199,7 @@ public void draw( } public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) { - AnvilCraftJeiPlugin.addAnvilCauldronCatalysts(registration, getRecipeType()); + AnvilCraftJeiPlugin.addAnvilCauldronCatalysts(registration, this.getRecipeType()); } /** diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/NeutronIrradiationCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/NeutronIrradiationCategory.java index 1a85e80da6..79501e87fc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/NeutronIrradiationCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/anvil/liquid/NeutronIrradiationCategory.java @@ -51,7 +51,7 @@ public void draw( double mouseX, double mouseY ) { - if (isExplosionRecipe(recipeHolder)) { + if (NeutronIrradiationCategory.isExplosionRecipe(recipeHolder)) { this.explosion.draw(graphics, 124, 16); } super.draw(recipeHolder, recipeSlotsView, graphics, mouseX, mouseY); @@ -77,7 +77,7 @@ public void getTooltip( double mouseX, double mouseY ) { - if (isExplosionRecipe(recipeHolder) + if (NeutronIrradiationCategory.isExplosionRecipe(recipeHolder) && mouseX >= 120 && mouseX <= 156 && mouseY >= 12 && mouseY <= 48) { tooltip.add(Component.translatable("gui.anvilcraft.category.neutron_irradiation.explosion")); diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockConversionCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockConversionCategory.java index 3e7a9a62d9..ba43d72141 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockConversionCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockConversionCategory.java @@ -142,17 +142,17 @@ public IRecipeHolderType getRecipeType() { @Override public Component getTitle() { - return TITLE; + return MultiBlockConversionCategory.TITLE; } @Override public int getWidth() { - return WIDTH; + return MultiBlockConversionCategory.WIDTH; } @Override public int getHeight() { - return HEIGHT; + return MultiBlockConversionCategory.HEIGHT; } @Override @@ -176,7 +176,7 @@ public void setRecipe( ); List inputItems = recipe.value().getInputPattern().toIngredientList(); - inputItems.sort(BY_COUNT_DECREASING); + inputItems.sort(MultiBlockConversionCategory.BY_COUNT_DECREASING); for (int i = 0; i < inputItems.size(); i++) { ItemStack stack = inputItems.get(i); @@ -184,7 +184,7 @@ public void setRecipe( } List outputItems = recipe.value().getOutputPattern().toIngredientList(); - outputItems.sort(BY_COUNT_DECREASING); + outputItems.sort(MultiBlockConversionCategory.BY_COUNT_DECREASING); for (int i = 0; i < outputItems.size(); i++) { ItemStack stack = outputItems.get(i); @@ -209,7 +209,7 @@ public void draw( ); pose.pushMatrix(); pose.scale(0.8F, 0.8F); - int textX = Math.round(WIDTH / 0.8F - minecraft.font.width(currentModeTooltip) - 5); + int textX = Math.round(MultiBlockConversionCategory.WIDTH / 0.8F - minecraft.font.width(currentModeTooltip) - 5); graphics.text(minecraft.font, currentModeTooltip, textX, 0, 0xFF000000, false); pose.popMatrix(); this.displayModeButton(mouseX, mouseY).draw(graphics, 149, 10); @@ -241,8 +241,8 @@ public void draw( final boolean modifiedOutput = !output.isAllLayersVisible(); input.setAllLayersVisible(true); output.setAllLayersVisible(true); - RenderSupport.renderLevelLike(input, graphics, 36, 44, SCALE_FAC_OVERVIEW, 8, 2.0F, false); - RenderSupport.renderLevelLike(output, graphics, 120, 44, SCALE_FAC_OVERVIEW, 8, 2.0F, false); + RenderSupport.renderLevelLike(input, graphics, 36, 44, MultiBlockConversionCategory.SCALE_FAC_OVERVIEW, 8, 2.0F, false); + RenderSupport.renderLevelLike(output, graphics, 120, 44, MultiBlockConversionCategory.SCALE_FAC_OVERVIEW, 8, 2.0F, false); if (modifiedInput) { input.setAllLayersVisible(false); } @@ -295,11 +295,11 @@ public void draw( drawable.setPosition(-1000, -1000); } } - RenderSupport.renderLevelLike(rendered, graphics, 80, 86, SCALE_FAC_LARGE, 8, 2.0F, false); + RenderSupport.renderLevelLike(rendered, graphics, 80, 86, MultiBlockConversionCategory.SCALE_FAC_LARGE, 8, 2.0F, false); Component component = this.layerTooltip(rendered); pose.pushMatrix(); pose.scale(0.8F, 0.8F); - textX = Math.round(WIDTH / 0.8F - minecraft.font.width(component) - 5); + textX = Math.round(MultiBlockConversionCategory.WIDTH / 0.8F - minecraft.font.width(component) - 5); graphics.text(minecraft.font, component, textX, 25, 0xFF000000, false); pose.popMatrix(); this.renderSwitchButton(rendered).draw(graphics, 125, 30); @@ -331,7 +331,7 @@ private IDrawable displayModeButton(double mouseX, double mouseY) { } private Component layerTooltip(LevelLike level) { - if (level.isAllLayersVisible()) return ALL_LAYERS; + if (level.isAllLayersVisible()) return MultiBlockConversionCategory.ALL_LAYERS; return Component.translatable( "gui.anvilcraft.category.multiblock.single_layer", level.getCurrentVisibleLayer() + 1, @@ -458,9 +458,9 @@ private enum DisplayMode { DisplayMode next() { return switch (this) { - case INPUT -> OUTPUT; - case OUTPUT -> OVERVIEW; - case OVERVIEW -> INPUT; + case INPUT -> DisplayMode.OUTPUT; + case OUTPUT -> DisplayMode.OVERVIEW; + case OVERVIEW -> DisplayMode.INPUT; }; } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockCraftingCategory.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockCraftingCategory.java index 664beeec3d..3cad3ec3cb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockCraftingCategory.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/category/multiblock/MultiBlockCraftingCategory.java @@ -104,17 +104,17 @@ public IRecipeHolderType getRecipeType() { @Override public Component getTitle() { - return TITLE; + return MultiBlockCraftingCategory.TITLE; } @Override public int getWidth() { - return WIDTH; + return MultiBlockCraftingCategory.WIDTH; } @Override public int getHeight() { - return START_HEIGHT + ROWS * 18; + return MultiBlockCraftingCategory.START_HEIGHT + MultiBlockCraftingCategory.ROWS * 18; } @Override @@ -128,13 +128,13 @@ public void setRecipe(IRecipeLayoutBuilder builder, RecipeHolder ingredientList = recipe.value().getPattern().toIngredientList(); - ingredientList.sort(BY_COUNT_DECREASING); + ingredientList.sort(MultiBlockCraftingCategory.BY_COUNT_DECREASING); for (int i = 0; i < ingredientList.size(); i++) { ItemStack stack = ingredientList.get(i); int row = i / 9; int col = i % 9; - builder.addSlot(RecipeIngredientRole.INPUT, col * 18 + 1, START_HEIGHT + row * 18 + 1).add(stack); + builder.addSlot(RecipeIngredientRole.INPUT, col * 18 + 1, MultiBlockCraftingCategory.START_HEIGHT + row * 18 + 1).add(stack); } } @@ -209,7 +209,7 @@ public void draw( pose.pushMatrix(); pose.scale(0.8F, 0.8F); - int textX = Math.round(WIDTH / 0.8F - minecraft.font.width(component) - 5); + int textX = Math.round(MultiBlockCraftingCategory.WIDTH / 0.8F - minecraft.font.width(component) - 5); graphics.text(minecraft.font, component, textX, 0, 0xFF000000, false); int size = recipe.value().pattern.getSize(); graphics.text( @@ -221,9 +221,9 @@ public void draw( this.arrowOut.draw(graphics, 110, 60); this.slot.draw(graphics, 129, 69); - for (int i = 0; i < ROWS; i++) { + for (int i = 0; i < MultiBlockCraftingCategory.ROWS; i++) { for (int j = 0; j < 9; j++) { - this.slot.draw(graphics, j * 18, START_HEIGHT + i * 18); + this.slot.draw(graphics, j * 18, MultiBlockCraftingCategory.START_HEIGHT + i * 18); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/ComplexFluidJeiRecipe.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/ComplexFluidJeiRecipe.java index 1a1eda2126..6f8ae2a840 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/ComplexFluidJeiRecipe.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/ComplexFluidJeiRecipe.java @@ -16,7 +16,6 @@ import net.minecraft.core.registries.Registries; import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStackTemplate; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.Enchantment; @@ -47,15 +46,15 @@ private ComplexFluidJeiRecipe( boolean linkFluidVariants ) { super( - toSizedIngredients(fluidInputs), - toItemStacks(resultItems), - firstFluids(fluidResults), + ComplexFluidJeiRecipe.toSizedIngredients(fluidInputs), + ComplexFluidJeiRecipe.toItemStacks(resultItems), + ComplexFluidJeiRecipe.firstFluids(fluidResults), false ); this.inputItems = List.copyOf(inputItems); this.resultItems = List.copyOf(resultItems); - this.displayFluidInputs = copyFluidGroups(fluidInputs); - this.displayFluidResults = copyFluidGroups(fluidResults); + this.displayFluidInputs = ComplexFluidJeiRecipe.copyFluidGroups(fluidInputs); + this.displayFluidResults = ComplexFluidJeiRecipe.copyFluidGroups(fluidResults); this.heaterRequired = heaterRequired; this.linkFluidVariants = linkFluidVariants; } @@ -68,21 +67,21 @@ public static boolean isComplex(SolidLiquidRecipe recipe) { public static ComplexFluidJeiRecipe fromSolidLiquid(SolidLiquidRecipe recipe) { HasCauldronSimple cauldron = recipe.getHasCauldron(); - List inputs = createFluidStacks( + List inputs = ComplexFluidJeiRecipe.createFluidStacks( cauldron.fluid(), cauldron.fluidTag(), - displayAmount(cauldron.consume()) + ComplexFluidJeiRecipe.displayAmount(cauldron.consume()) ); - List results = createFluidStacks( + List results = ComplexFluidJeiRecipe.createFluidStacks( cauldron.transform(), null, - displayAmount(cauldron.produce()) + ComplexFluidJeiRecipe.displayAmount(cauldron.produce()) ); return new ComplexFluidJeiRecipe( recipe.getInputItems(), recipe.getResultItems(), - asGroup(inputs), - asGroup(results), + ComplexFluidJeiRecipe.asGroup(inputs), + ComplexFluidJeiRecipe.asGroup(results), false, false ); @@ -149,7 +148,7 @@ public List getDisplayItemResults() { } public List> getDisplayFluidInputs() { - return copyFluidGroups(this.displayFluidInputs); + return ComplexFluidJeiRecipe.copyFluidGroups(this.displayFluidInputs); } public int getDisplayFluidInputCount() { @@ -157,7 +156,7 @@ public int getDisplayFluidInputCount() { } public List> getDisplayFluidResults() { - return copyFluidGroups(this.displayFluidResults); + return ComplexFluidJeiRecipe.copyFluidGroups(this.displayFluidResults); } public int getDisplayFluidResultCount() { diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/DecayRecipe.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/DecayRecipe.java index 9c83d886dd..f5e47781fe 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/DecayRecipe.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/DecayRecipe.java @@ -60,7 +60,7 @@ public static List getAllRecipes() { List.of(ModBlocks.VOID_MATTER_BLOCK.get()), List.of(), ModBlockTags.VOID_DECAY_PRODUCTS, - List.of(DOWN, BACK, FRONT, UP, LEFT), + List.of(DecayRecipe.DOWN, DecayRecipe.BACK, DecayRecipe.FRONT, DecayRecipe.UP, DecayRecipe.LEFT), Map.of() ), new DecayRecipe( @@ -68,7 +68,7 @@ public static List getAllRecipes() { radioactiveBlocks, decayProducts, null, - List.of(UP, DOWN, LEFT), + List.of(DecayRecipe.UP, DecayRecipe.DOWN, DecayRecipe.LEFT), Map.of() ), new DecayRecipe( @@ -76,15 +76,15 @@ public static List getAllRecipes() { radioactiveBlocks, decayProducts, null, - List.of(UP, DOWN, LEFT, RIGHT), - Map.of(FRONT, ModBlocks.LEAD_BLOCK.get()) + List.of(DecayRecipe.UP, DecayRecipe.DOWN, DecayRecipe.LEFT, DecayRecipe.RIGHT), + Map.of(DecayRecipe.FRONT, ModBlocks.LEAD_BLOCK.get()) ), new DecayRecipe( AnvilCraft.of("decay/radioactive_six_sides"), radioactiveBlocks, List.of(Blocks.LAVA, Blocks.LAVA), null, - List.of(UP, DOWN, LEFT, RIGHT, FRONT, BACK), + List.of(DecayRecipe.UP, DecayRecipe.DOWN, DecayRecipe.LEFT, DecayRecipe.RIGHT, DecayRecipe.FRONT, DecayRecipe.BACK), Map.of() ), new DecayRecipe( @@ -92,7 +92,7 @@ public static List getAllRecipes() { List.of(ModBlocks.EXCITED_STATE_VOID_MATTER_BLOCK.get()), ExcitedStateVoidMatterBlock.getDecayProducts(), null, - List.of(RIGHT), + List.of(DecayRecipe.RIGHT), Map.of() ), new DecayRecipe( @@ -100,8 +100,8 @@ public static List getAllRecipes() { List.of(ModBlocks.EXCITED_STATE_VOID_MATTER_BLOCK.get()), ExcitedStateVoidMatterBlock.getConfinedAnvilons(), null, - List.of(RIGHT), - Map.of(LEFT, ModBlocks.CONFINEMENT_CHAMBER.get()) + List.of(DecayRecipe.RIGHT), + Map.of(DecayRecipe.LEFT, ModBlocks.CONFINEMENT_CHAMBER.get()) ), new DecayRecipe( AnvilCraft.of("decay/void_matter_near_excited_state"), @@ -109,7 +109,7 @@ public static List getAllRecipes() { List.of(), ModBlockTags.VOID_DECAY_PRODUCTS, List.of(), - Map.of(RIGHT, ModBlocks.EXCITED_STATE_VOID_MATTER_BLOCK.get()) + Map.of(DecayRecipe.RIGHT, ModBlocks.EXCITED_STATE_VOID_MATTER_BLOCK.get()) ) ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/MeshRecipeGroup.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/MeshRecipeGroup.java index 130f781d9a..5ee05420d4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/MeshRecipeGroup.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/recipe/MeshRecipeGroup.java @@ -24,7 +24,7 @@ public record MeshRecipeGroup(ItemIngredientPredicate ingredient, List r public static int maxRows; public static ImmutableList getAllRecipesGrouped() { - maxRows = 1; + MeshRecipeGroup.maxRows = 1; List recipes = JeiRecipeUtil.getRecipesFromType(ModRecipeTypes.MESH.get()); Multimap ingredientGrouper = ArrayListMultimap.create(); @@ -56,8 +56,8 @@ public static ImmutableList getAllRecipesGrouped() { jeiRecipes.add(new MeshRecipeGroup(ingredient, results)); int rows = Mth.ceil(values.size() / 9F); - if (rows > maxRows) { - maxRows = rows; + if (rows > MeshRecipeGroup.maxRows) { + MeshRecipeGroup.maxRows = rows; } } return jeiRecipes.build(); diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/BlockTagUtil.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/BlockTagUtil.java index 530332a3a1..62fbc1b3f1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/BlockTagUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/BlockTagUtil.java @@ -28,7 +28,7 @@ public class BlockTagUtil { /// 为了防止某些内容特别多的标签被特别多的配方引用造成的内存空间浪费,本方法的实现将每个{@link TagKey} /// 对应的原料缓存在{@link HashMap}中。 public static Ingredient toIngredient(TagKey tag) { - return CACHE.computeIfAbsent(tag, t -> new BlockTagIngredient(t).toVanilla()); + return BlockTagUtil.CACHE.computeIfAbsent(tag, t -> new BlockTagIngredient(t).toVanilla()); } /// 根据方块标签,获取当前的用于循环展示的方块。 diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiBlockIngredientUtil.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiBlockIngredientUtil.java index 6cad8bec9e..ae15b368af 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiBlockIngredientUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiBlockIngredientUtil.java @@ -31,6 +31,7 @@ import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import org.jspecify.annotations.Nullable; import java.util.List; import java.util.Optional; @@ -44,7 +45,7 @@ public final class JeiBlockIngredientUtil { private JeiBlockIngredientUtil() { } - public static IRecipeSlotBuilder addInputSlot( + public static void addInputSlot( IRecipeLayoutBuilder builder, String name, int x, @@ -56,7 +57,7 @@ public static IRecipeSlotBuilder addInputSlot( List stacks = input.getBlocks().stream() .map(holder -> new ItemStack(holder.value())) .toList(); - return addSlot(builder, RecipeIngredientRole.INPUT, name, x, y, width, height, stacks); + JeiBlockIngredientUtil.addSlot(builder, RecipeIngredientRole.INPUT, name, x, y, width, height, stacks); } public static IRecipeSlotBuilder addSlot( @@ -69,7 +70,7 @@ public static IRecipeSlotBuilder addSlot( int height, Block block ) { - return addSlot(builder, role, name, x, y, width, height, List.of(new ItemStack(block))); + return JeiBlockIngredientUtil.addSlot(builder, role, name, x, y, width, height, List.of(new ItemStack(block))); } public static IRecipeSlotBuilder addSlot( @@ -83,7 +84,7 @@ public static IRecipeSlotBuilder addSlot( List stacks ) { return builder.addSlot(role, x, y) - .setSlotName(SLOT_PREFIX + name) + .setSlotName(JeiBlockIngredientUtil.SLOT_PREFIX + name) .setCustomRenderer(VanillaTypes.ITEM_STACK, new TransparentItemRenderer(width, height)) .addItemStacks(stacks); } @@ -91,7 +92,8 @@ public static IRecipeSlotBuilder addSlot( public static void suppressHoverOverlays(IRecipeExtrasBuilder builder) { List slots = builder.getRecipeSlots().getSlots().stream() .filter(slot -> slot.getSlotName() - .filter(name -> name.startsWith(SLOT_PREFIX) || name.startsWith(PREVIEW_SLOT_PREFIX)) + .filter(name -> name.startsWith(JeiBlockIngredientUtil.SLOT_PREFIX) || name.startsWith( + JeiBlockIngredientUtil.PREVIEW_SLOT_PREFIX)) .isPresent()) .toList(); if (!slots.isEmpty()) { @@ -105,7 +107,7 @@ public static Optional getDisplayedState( List states ) { if (states.isEmpty()) return Optional.empty(); - Optional displayedBlock = recipeSlotsView.findSlotByName(SLOT_PREFIX + slotName) + Optional displayedBlock = recipeSlotsView.findSlotByName(JeiBlockIngredientUtil.SLOT_PREFIX + slotName) .flatMap(IRecipeSlotView::getDisplayedItemStack) .map(ItemStack::getItem) .filter(BlockItem.class::isInstance) @@ -183,7 +185,7 @@ public Optional getSlotUnderMouse(double mouseX, double mo } } - @SuppressWarnings("removal") + @SuppressWarnings({"removal", "NonExtendableApiUsage"}) private record NoHoverRecipeSlot(IRecipeSlotDrawable delegate) implements IRecipeSlotDrawable { @Override public Stream> getAllIngredients() { @@ -191,7 +193,7 @@ public Stream> getAllIngredients() { } @Override - public List> getAllIngredientsList() { + public List<@Nullable ITypedIngredient> getAllIngredientsList() { return this.delegate.getAllIngredientsList(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiFluidUtil.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiFluidUtil.java index 9115231339..c93873e006 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiFluidUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiFluidUtil.java @@ -39,7 +39,7 @@ public static void addFluidInputSlot( int height, HasCauldronSimple cauldron ) { - addInputSlot(builder, name, JeiSlotUtil.INPUT_X, JeiSlotUtil.FLUID_Y, width, height, cauldron); + JeiFluidUtil.addInputSlot(builder, name, JeiSlotUtil.INPUT_X, JeiSlotUtil.FLUID_Y, width, height, cauldron); } /** @@ -52,7 +52,7 @@ public static void addDefaultInputSlot( int height, HasCauldronSimple cauldron ) { - addInputSlot(builder, name, JeiSlotUtil.INPUT_X, JeiSlotUtil.DEFAULT_Y, width, height, cauldron); + JeiFluidUtil.addInputSlot(builder, name, JeiSlotUtil.INPUT_X, JeiSlotUtil.DEFAULT_Y, width, height, cauldron); } public static void addInputSlot( @@ -64,7 +64,7 @@ public static void addInputSlot( int height, HasCauldronSimple cauldron ) { - addSlot( + JeiFluidUtil.addSlot( builder, RecipeIngredientRole.INPUT, name, @@ -72,7 +72,7 @@ public static void addInputSlot( y, width, height, - getFluids(cauldron.fluid(), cauldron.fluidTag()), + JeiFluidUtil.getFluids(cauldron.fluid(), cauldron.fluidTag()), cauldron.consume() ); } @@ -87,7 +87,7 @@ public static void addFluidOutputSlot( int height, HasCauldronSimple cauldron ) { - addOutputSlot(builder, name, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.FLUID_Y, width, height, cauldron); + JeiFluidUtil.addOutputSlot(builder, name, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.FLUID_Y, width, height, cauldron); } /** @@ -100,7 +100,7 @@ public static void addDefaultOutputSlot( int height, HasCauldronSimple cauldron ) { - addOutputSlot(builder, name, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.DEFAULT_Y, width, height, cauldron); + JeiFluidUtil.addOutputSlot(builder, name, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.DEFAULT_Y, width, height, cauldron); } public static void addOutputSlot( @@ -112,7 +112,7 @@ public static void addOutputSlot( int height, HasCauldronSimple cauldron ) { - addSlot( + JeiFluidUtil.addSlot( builder, RecipeIngredientRole.OUTPUT, name, @@ -120,7 +120,7 @@ public static void addOutputSlot( y, width, height, - getFluids(cauldron.transform(), null), + JeiFluidUtil.getFluids(cauldron.transform(), null), cauldron.produce() ); } @@ -139,10 +139,10 @@ private static void addSlot( if (fluids.isEmpty()) return; long displayAmount = amount > 0 ? amount : FluidType.BUCKET_VOLUME; IRecipeSlotBuilder slot = builder.addSlot(role, x, y) - .setSlotName(SLOT_PREFIX + name) + .setSlotName(JeiFluidUtil.SLOT_PREFIX + name) .setFluidRenderer(displayAmount, false, width, height); fluids.forEach(fluid -> slot.add(fluid, displayAmount)); - addBucketIngredients(builder, role, fluids); + JeiFluidUtil.addBucketIngredients(builder, role, fluids); } private static void addBucketIngredients( diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiItemUtil.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiItemUtil.java index c501d9a85a..5fee1a5846 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiItemUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiItemUtil.java @@ -17,14 +17,14 @@ public class JeiItemUtil { * 默认的居中位置 */ public static void addDefaultInputSlots(IRecipeLayoutBuilder builder, List mergedIngredients) { - addInputSlots(builder, mergedIngredients, JeiSlotUtil.INPUT_X, JeiSlotUtil.DEFAULT_Y); + JeiItemUtil.addInputSlots(builder, mergedIngredients, JeiSlotUtil.INPUT_X, JeiSlotUtil.DEFAULT_Y); } /** * 存在流体时物品位置向上偏移 */ public static void addItemInputSlots(IRecipeLayoutBuilder builder, List mergedIngredients) { - addInputSlots(builder, mergedIngredients, JeiSlotUtil.INPUT_X, JeiSlotUtil.ITEM_Y); + JeiItemUtil.addInputSlots(builder, mergedIngredients, JeiSlotUtil.INPUT_X, JeiSlotUtil.ITEM_Y); } public static void addInputSlots( @@ -33,9 +33,9 @@ public static void addInputSlots( int centerX, int centerY ) { - addSlots( + JeiItemUtil.addSlots( mergedIngredients.size(), centerX, centerY, - (x, y, i) -> addSlotWithCount(builder, x, y, mergedIngredients.get(i)) + (x, y, i) -> JeiItemUtil.addSlotWithCount(builder, x, y, mergedIngredients.get(i)) ); } @@ -43,20 +43,20 @@ public static void addInputSlots( * 默认的居中位置 */ public static void addDefaultOutputSlots(IRecipeLayoutBuilder builder, List results) { - addOutputSlots(builder, results, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.DEFAULT_Y); + JeiItemUtil.addOutputSlots(builder, results, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.DEFAULT_Y); } /** * 存在流体时物品位置向上偏移 */ public static void addItemOutputSlots(IRecipeLayoutBuilder builder, List results) { - addOutputSlots(builder, results, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.ITEM_Y); + JeiItemUtil.addOutputSlots(builder, results, JeiSlotUtil.OUTPUT_X, JeiSlotUtil.ITEM_Y); } public static void addOutputSlots(IRecipeLayoutBuilder builder, List results, int centerX, int centerY) { - addSlots( + JeiItemUtil.addSlots( results.size(), centerX, centerY, - (x, y, i) -> addOutputSlot(builder, x, y, results.get(i)) + (x, y, i) -> JeiItemUtil.addOutputSlot(builder, x, y, results.get(i)) ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRecipeUtil.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRecipeUtil.java index 4ec198f666..f3f4afb6ac 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRecipeUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRecipeUtil.java @@ -69,18 +69,18 @@ public static List getTooltips(NumberProvider provider) { if (provider instanceof BinomialDistributionGenerator(NumberProvider n, NumberProvider p)) { if (n instanceof ConstantValue(float value) && value == 1) { - String chance = FORMATTER.format(NumberProviderUtil.expected(p) * 100); + String chance = JeiRecipeUtil.FORMATTER.format(NumberProviderUtil.expected(p) * 100); tooltipLines.add(Component.translatable("gui.anvilcraft.category.chance", chance).withStyle(ChatFormatting.GRAY)); } else { - addAvgOutput(tooltipLines, NumberProviderUtil.expected(provider)); + JeiRecipeUtil.addAvgOutput(tooltipLines, NumberProviderUtil.expected(provider)); } - addMinMax(tooltipLines, 0, getMax(n)); + JeiRecipeUtil.addMinMax(tooltipLines, 0, JeiRecipeUtil.getMax(n)); } else if (provider.getClass() != ConstantValue.class) { double val = NumberProviderUtil.expected(provider); if (val != -1) { - addAvgOutput(tooltipLines, val); + JeiRecipeUtil.addAvgOutput(tooltipLines, val); if (provider instanceof UniformGenerator) { - addMinMax(tooltipLines, getMin(provider), getMax(provider)); + JeiRecipeUtil.addMinMax(tooltipLines, JeiRecipeUtil.getMin(provider), JeiRecipeUtil.getMax(provider)); } } } else { @@ -89,7 +89,7 @@ public static List getTooltips(NumberProvider provider) { if (value != 1) { tooltipLines.add(Component.translatable( "gui.anvilcraft.category.chance", - FORMATTER.format(value * 100) + JeiRecipeUtil.FORMATTER.format(value * 100) ).withStyle(ChatFormatting.GRAY)); } } @@ -102,19 +102,19 @@ public static void addTooltips(IRecipeSlotBuilder slot, int count, NumberProvide if (provider instanceof BinomialDistributionGenerator(NumberProvider n, NumberProvider p)) { if (n instanceof ConstantValue(float value) && value == 1) { - String chance = FORMATTER.format(NumberProviderUtil.expected(p) * 100); + String chance = JeiRecipeUtil.FORMATTER.format(NumberProviderUtil.expected(p) * 100); tooltipLines.add(Component.translatable("gui.anvilcraft.category.chance", chance) .withStyle(ChatFormatting.GRAY)); } else { - addAvgOutput(tooltipLines, count * NumberProviderUtil.expected(provider)); + JeiRecipeUtil.addAvgOutput(tooltipLines, count * NumberProviderUtil.expected(provider)); } - addMinMax(tooltipLines, 0, getMax(n)); + JeiRecipeUtil.addMinMax(tooltipLines, 0, JeiRecipeUtil.getMax(n)); } else if (provider.getClass() != ConstantValue.class) { double val = count * NumberProviderUtil.expected(provider); if (val != -1) { - addAvgOutput(tooltipLines, val); + JeiRecipeUtil.addAvgOutput(tooltipLines, val); if (provider instanceof UniformGenerator) { - addMinMax(tooltipLines, getMin(provider), getMax(provider)); + JeiRecipeUtil.addMinMax(tooltipLines, JeiRecipeUtil.getMin(provider), JeiRecipeUtil.getMax(provider)); } } } @@ -137,7 +137,7 @@ public static boolean isChance(List chanceItemStacks) { private static double getMin(NumberProvider provider) { return switch (provider) { case ConstantValue value -> value.value(); - case UniformGenerator uniform -> getMin(uniform.min()); + case UniformGenerator uniform -> JeiRecipeUtil.getMin(uniform.min()); default -> 0; }; } @@ -145,21 +145,21 @@ private static double getMin(NumberProvider provider) { private static double getMax(NumberProvider provider) { return switch (provider) { case ConstantValue value -> value.value(); - case UniformGenerator uniform -> getMax(uniform.max()); - case BinomialDistributionGenerator binomial -> getMax(binomial.n()); + case UniformGenerator uniform -> JeiRecipeUtil.getMax(uniform.max()); + case BinomialDistributionGenerator binomial -> JeiRecipeUtil.getMax(binomial.n()); default -> 0; }; } private static void addAvgOutput(ImmutableList.Builder tooltipLines, double avgValue) { - String avgOutput = FORMATTER.format(avgValue); + String avgOutput = JeiRecipeUtil.FORMATTER.format(avgValue); tooltipLines.add(Component.translatable("gui.anvilcraft.category.average_output", avgOutput) .withStyle(ChatFormatting.GRAY)); } private static void addMinMax(ImmutableList.Builder tooltipLines, double min, double max) { - String minOutput = FORMATTER.format(min); - String maxOutput = FORMATTER.format(max); + String minOutput = JeiRecipeUtil.FORMATTER.format(min); + String maxOutput = JeiRecipeUtil.FORMATTER.format(max); tooltipLines.add(Component.translatable("gui.anvilcraft.category.min_output", minOutput) .withStyle(ChatFormatting.GRAY)); diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRenderHelper.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRenderHelper.java index 9529a79f73..7cc56900dd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRenderHelper.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiRenderHelper.java @@ -11,7 +11,7 @@ public class JeiRenderHelper { // Animation public static int getAnvilAnimationOffset(ITickTimer timer) { - return timer.getValue() < 30 ? getAnvilAnimationOffset(timer.getValue()) : 8; + return timer.getValue() < 30 ? JeiRenderHelper.getAnvilAnimationOffset(timer.getValue()) : 8; } public static int getAnvilAnimationOffset(float time) { diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiSlotUtil.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiSlotUtil.java index 01da1196cb..0f71bc96eb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiSlotUtil.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiSlotUtil.java @@ -27,42 +27,42 @@ public class JeiSlotUtil { * 使用默认的居中位置绘制输入槽。 */ public static void drawDefaultInputSlots(GuiGraphicsExtractor graphics, IDrawable slot, int inputSize) { - drawSlots(graphics, slot, inputSize, INPUT_X - 1, DEFAULT_Y - 1); + JeiSlotUtil.drawSlots(graphics, slot, inputSize, JeiSlotUtil.INPUT_X - 1, JeiSlotUtil.DEFAULT_Y - 1); } /** * 存在流体时将物品输入槽向上偏移。 */ public static void drawItemInputSlots(GuiGraphicsExtractor graphics, IDrawable slot, int inputSize) { - drawSlots(graphics, slot, inputSize, INPUT_X - 1, ITEM_Y - 1); + JeiSlotUtil.drawSlots(graphics, slot, inputSize, JeiSlotUtil.INPUT_X - 1, JeiSlotUtil.ITEM_Y - 1); } /** * 存在物品时将流体输入槽向下偏移。 */ public static void drawFluidInputSlots(GuiGraphicsExtractor graphics, IDrawable slot, int inputSize) { - drawSlots(graphics, slot, inputSize, INPUT_X - 1, FLUID_Y - 1); + JeiSlotUtil.drawSlots(graphics, slot, inputSize, JeiSlotUtil.INPUT_X - 1, JeiSlotUtil.FLUID_Y - 1); } /** * 使用默认的居中位置绘制输出槽。 */ public static void drawDefaultOutputSlots(GuiGraphicsExtractor graphics, IDrawable slot, int outputSize) { - drawSlots(graphics, slot, outputSize, OUTPUT_X - 1, DEFAULT_Y - 1); + JeiSlotUtil.drawSlots(graphics, slot, outputSize, JeiSlotUtil.OUTPUT_X - 1, JeiSlotUtil.DEFAULT_Y - 1); } /** * 存在流体时将物品输出槽向上偏移。 */ public static void drawItemOutputSlots(GuiGraphicsExtractor graphics, IDrawable slot, int outputSize) { - drawSlots(graphics, slot, outputSize, OUTPUT_X - 1, ITEM_Y - 1); + JeiSlotUtil.drawSlots(graphics, slot, outputSize, JeiSlotUtil.OUTPUT_X - 1, JeiSlotUtil.ITEM_Y - 1); } /** * 存在物品时将流体输出槽向下偏移。 */ public static void drawFluidOutputSlots(GuiGraphicsExtractor graphics, IDrawable slot, int outputSize) { - drawSlots(graphics, slot, outputSize, OUTPUT_X - 1, FLUID_Y - 1); + JeiSlotUtil.drawSlots(graphics, slot, outputSize, JeiSlotUtil.OUTPUT_X - 1, JeiSlotUtil.FLUID_Y - 1); } public static void drawSlots( @@ -75,10 +75,10 @@ public static void drawSlots( if (size == 0) return; int columns = (int) Math.ceil(Math.sqrt(size)); int rows = Math.ceilDiv(size, columns); - int startX = centerX - (columns - 1) * OFFSET / 2; - int startY = centerY - (rows - 1) * OFFSET / 2; + int startX = centerX - (columns - 1) * JeiSlotUtil.OFFSET / 2; + int startY = centerY - (rows - 1) * JeiSlotUtil.OFFSET / 2; for (int i = 0; i < size; i++) { - slot.draw(graphics, startX + (i % columns) * OFFSET, startY + (i / columns) * OFFSET); + slot.draw(graphics, startX + (i % columns) * JeiSlotUtil.OFFSET, startY + (i / columns) * JeiSlotUtil.OFFSET); } } @@ -161,7 +161,7 @@ public static void addDiffInputSlots(IRecipeLayoutBuilder builder, ItemIngredien for (int index = 0; index < inputSize; index++) { int row = index / 2; int col = index % 2; - addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, ingredient.withCount(1)); + JeiSlotUtil.addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, ingredient.withCount(1)); } } else if (inputSize <= 6) { int startX = 2; @@ -169,7 +169,7 @@ public static void addDiffInputSlots(IRecipeLayoutBuilder builder, ItemIngredien for (int index = 0; index < inputSize; index++) { int row = index / 3; int col = index % 3; - addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, ingredient.withCount(1)); + JeiSlotUtil.addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, ingredient.withCount(1)); } } else { int startX = 1; @@ -178,7 +178,7 @@ public static void addDiffInputSlots(IRecipeLayoutBuilder builder, ItemIngredien if (index > 9) break; int row = index / 3; int col = index % 3; - addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, ingredient.withCount(1)); + JeiSlotUtil.addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, ingredient.withCount(1)); } } } @@ -196,7 +196,7 @@ public static void addInputSlots(IRecipeLayoutBuilder builder, List 9) break; int row = index / 3; int col = index % 3; - addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, mergedIngredients.get(index)); + JeiSlotUtil.addSlotWithCount(builder, startX + 19 * col, startY + 19 * row, mergedIngredients.get(index)); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiTextures.java b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiTextures.java index d1bf4ec4f8..7668ad827d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiTextures.java +++ b/src/main/java/dev/dubhe/anvilcraft/integration/jei/util/JeiTextures.java @@ -5,30 +5,30 @@ public class JeiTextures { // Arrow - public static final Identifier ARROW_DEFAULT = texture("arrow_default"); - public static final Identifier ARROW_BLOCK_CONVERSION = texture("arrow_block_conversion"); - public static final Identifier ARROW_INPUT = texture("arrow_input"); - public static final Identifier ARROW_LONG = texture("arrow_long"); - public static final Identifier ARROW_OUTPUT = texture("arrow_output"); - public static final Identifier ARROW_OUTPUT_FROM_BELOW = texture("arrow_output_from_below"); + public static final Identifier ARROW_DEFAULT = JeiTextures.texture("arrow_default"); + public static final Identifier ARROW_BLOCK_CONVERSION = JeiTextures.texture("arrow_block_conversion"); + public static final Identifier ARROW_INPUT = JeiTextures.texture("arrow_input"); + public static final Identifier ARROW_LONG = JeiTextures.texture("arrow_long"); + public static final Identifier ARROW_OUTPUT = JeiTextures.texture("arrow_output"); + public static final Identifier ARROW_OUTPUT_FROM_BELOW = JeiTextures.texture("arrow_output_from_below"); // Slot - public static final Identifier SLOT_CHOICE = texture("slot_choice"); - public static final Identifier SLOT_DEFAULT = texture("slot_default"); - public static final Identifier SLOT_PROBABILITY = texture("slot_probability"); + public static final Identifier SLOT_CHOICE = JeiTextures.texture("slot_choice"); + public static final Identifier SLOT_DEFAULT = JeiTextures.texture("slot_default"); + public static final Identifier SLOT_PROBABILITY = JeiTextures.texture("slot_probability"); // MULTIBLOCK - public static final Identifier DISPLAY_MODES = texture("multiblock/display_modes"); - public static final Identifier LAYER_UP = texture("multiblock/layer_up"); - public static final Identifier LAYER_DOWN = texture("multiblock/layer_down"); - public static final Identifier LAYER_SWITCH = texture("multiblock/layer_switch"); - public static final Identifier BLOCK_CONVERSION = texture("multiblock/multiblock_conversion"); - public static final Identifier BLOCK_CRAFTING = texture("multiblock/multiblock_crafting"); + public static final Identifier DISPLAY_MODES = JeiTextures.texture("multiblock/display_modes"); + public static final Identifier LAYER_UP = JeiTextures.texture("multiblock/layer_up"); + public static final Identifier LAYER_DOWN = JeiTextures.texture("multiblock/layer_down"); + public static final Identifier LAYER_SWITCH = JeiTextures.texture("multiblock/layer_switch"); + public static final Identifier BLOCK_CONVERSION = JeiTextures.texture("multiblock/multiblock_conversion"); + public static final Identifier BLOCK_CRAFTING = JeiTextures.texture("multiblock/multiblock_crafting"); // Other - public static final Identifier EXPLOSION = texture("explosion"); - public static final Identifier CYCLE = texture("cycle"); - public static final Identifier PRE_RENDERED_END_PORTAL = texture("pre_rendered_end_portal"); + public static final Identifier EXPLOSION = JeiTextures.texture("explosion"); + public static final Identifier CYCLE = JeiTextures.texture("cycle"); + public static final Identifier PRE_RENDERED_END_PORTAL = JeiTextures.texture("pre_rendered_end_portal"); public static Identifier texture(String path) { return SharedTextures.textureGui("jei/" + path); diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/ActiveSilencerMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/ActiveSilencerMenu.java index 76f9fe9a0f..75fcbf058d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/ActiveSilencerMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/ActiveSilencerMenu.java @@ -43,7 +43,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.ACTIVE_SILENCER.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/AdjacentSmithingMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/AdjacentSmithingMenu.java index 0326f1d530..01f255c578 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/AdjacentSmithingMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/AdjacentSmithingMenu.java @@ -117,14 +117,14 @@ public void broadcastChanges() { if (!(this.menuPlayer instanceof ServerPlayer serverPlayer) || this.tablePos == null) return; long gameTime = this.templateLevel.getGameTime(); if (gameTime < this.nextRefreshTime) return; - this.nextRefreshTime = gameTime + REFRESH_INTERVAL; + this.nextRefreshTime = gameTime + AdjacentSmithingMenu.REFRESH_INTERVAL; this.refreshTemplateCatalog(); this.syncTemplateData(serverPlayer); } @Override public void clicked(int slotId, int button, ContainerInput containerInput, Player player) { - if (!this.borrowedTemplateStack.isEmpty() && slotId == TEMPLATE_SLOT) return; + if (!this.borrowedTemplateStack.isEmpty() && slotId == AdjacentSmithingMenu.TEMPLATE_SLOT) return; super.clicked(slotId, button, containerInput, player); } @@ -140,7 +140,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean canTakeItemForPickAll(ItemStack stack, Slot slot) { - if (!this.borrowedTemplateStack.isEmpty() && slot == this.getSlot(TEMPLATE_SLOT)) return false; + if (!this.borrowedTemplateStack.isEmpty() && slot == this.getSlot(AdjacentSmithingMenu.TEMPLATE_SLOT)) return false; return super.canTakeItemForPickAll(stack, slot); } @@ -163,12 +163,12 @@ private void refreshTemplateCatalog() { this.collectTemplates(handler, templates); } if (!this.borrowedTemplateStack.isEmpty()) { - addUniqueTemplate(templates, this.borrowedTemplateStack); + AdjacentSmithingMenu.addUniqueTemplate(templates, this.borrowedTemplateStack); } templates.sort(Comparator - .comparingInt((ItemStack stack) -> favoriteIndex(favorites, itemId(stack))) - .thenComparingInt(stack -> templateIndex(this.adjacentTemplates, itemId(stack)))); - if (!sameTemplates(this.adjacentTemplates, templates) || !this.favoriteTemplates.equals(favorites)) { + .comparingInt((ItemStack stack) -> AdjacentSmithingMenu.favoriteIndex(favorites, AdjacentSmithingMenu.itemId(stack))) + .thenComparingInt(stack -> AdjacentSmithingMenu.templateIndex(this.adjacentTemplates, AdjacentSmithingMenu.itemId(stack)))); + if (!AdjacentSmithingMenu.sameTemplates(this.adjacentTemplates, templates) || !this.favoriteTemplates.equals(favorites)) { this.adjacentTemplates = templates; this.favoriteTemplates = List.copyOf(favorites); this.templateDataDirty = true; @@ -178,21 +178,21 @@ private void refreshTemplateCatalog() { private void collectTemplates(@Nullable ResourceHandler handler, List templates) { if (handler == null) return; for (int slot = 0; slot < handler.size(); slot++) { - ItemStack stack = getStack(handler, slot); + ItemStack stack = AdjacentSmithingMenu.getStack(handler, slot); if (stack.isEmpty() || !this.isUsableTemplate(stack)) continue; - ItemStack simulated = simulateExtract(handler, slot); + ItemStack simulated = AdjacentSmithingMenu.simulateExtract(handler, slot); if (!ItemStack.isSameItemSameComponents(stack.copyWithCount(1), simulated)) continue; - addUniqueTemplate(templates, stack); + AdjacentSmithingMenu.addUniqueTemplate(templates, stack); } } private void borrowTemplate(ServerPlayer player, Identifier template) { if (this.tablePos == null) return; if (this.isBorrowedTemplateId(template)) return; - ItemStack currentTemplate = this.inputSlots.getItem(TEMPLATE_SLOT); + ItemStack currentTemplate = this.inputSlots.getItem(AdjacentSmithingMenu.TEMPLATE_SLOT); if (this.borrowedTemplate == null && !currentTemplate.isEmpty()) return; if (this.borrowedTemplate != null - && !matchesTemplate(currentTemplate, this.borrowedTemplate.template())) { + && !AdjacentSmithingMenu.matchesTemplate(currentTemplate, this.borrowedTemplate.template())) { this.borrowedTemplate = null; this.borrowedTemplateStack = ItemStack.EMPTY; this.templateDataDirty = true; @@ -217,7 +217,7 @@ private void borrowTemplate(ServerPlayer player, Identifier template) { extracted.sourceBlockEntity() ); this.borrowedTemplateStack = extracted.stack().copy(); - this.inputSlots.setItem(TEMPLATE_SLOT, extracted.stack()); + this.inputSlots.setItem(AdjacentSmithingMenu.TEMPLATE_SLOT, extracted.stack()); this.templateDataDirty = true; this.refreshTemplateCatalog(); this.syncTemplateData(player); @@ -231,12 +231,12 @@ private ExtractedTemplate extractTemplate(Identifier template) { ResourceHandler handler = this.getItemHandler(sourcePos); if (handler == null) continue; for (int slot = 0; slot < handler.size(); slot++) { - ItemStack stack = getStack(handler, slot); - if (!matchesTemplate(stack, template) || !this.isUsableTemplate(stack)) continue; - ItemStack simulated = simulateExtract(handler, slot); - if (!matchesTemplate(simulated, template) || !this.isUsableTemplate(simulated)) continue; - ItemStack extracted = extract(handler, slot); - if (matchesTemplate(extracted, template) && this.isUsableTemplate(extracted)) { + ItemStack stack = AdjacentSmithingMenu.getStack(handler, slot); + if (!AdjacentSmithingMenu.matchesTemplate(stack, template) || !this.isUsableTemplate(stack)) continue; + ItemStack simulated = AdjacentSmithingMenu.simulateExtract(handler, slot); + if (!AdjacentSmithingMenu.matchesTemplate(simulated, template) || !this.isUsableTemplate(simulated)) continue; + ItemStack extracted = AdjacentSmithingMenu.extract(handler, slot); + if (AdjacentSmithingMenu.matchesTemplate(extracted, template) && this.isUsableTemplate(extracted)) { return new ExtractedTemplate( sourcePos.immutable(), slot, @@ -253,15 +253,15 @@ private ExtractedTemplate extractTemplate(Identifier template) { private void returnBorrowedTemplate(boolean notifyMenu) { BorrowedTemplate origin = this.borrowedTemplate; if (origin == null) return; - final ItemStack stack = this.inputSlots.getItem(TEMPLATE_SLOT); + final ItemStack stack = this.inputSlots.getItem(AdjacentSmithingMenu.TEMPLATE_SLOT); this.borrowedTemplate = null; this.borrowedTemplateStack = ItemStack.EMPTY; this.templateDataDirty = true; - if (stack.isEmpty() || !matchesTemplate(stack, origin.template())) return; + if (stack.isEmpty() || !AdjacentSmithingMenu.matchesTemplate(stack, origin.template())) return; if (notifyMenu) { - this.inputSlots.setItem(TEMPLATE_SLOT, ItemStack.EMPTY); + this.inputSlots.setItem(AdjacentSmithingMenu.TEMPLATE_SLOT, ItemStack.EMPTY); } else { - this.inputSlots.removeItemNoUpdate(TEMPLATE_SLOT); + this.inputSlots.removeItemNoUpdate(AdjacentSmithingMenu.TEMPLATE_SLOT); } ResourceHandler handler = this.templateLevel.getBlockEntity(origin.sourcePos()) == origin.sourceBlockEntity() @@ -282,12 +282,12 @@ private void returnToHandlerOrDrop( ) { ItemStack remainder = stack; if (handler != null && preferredSlot >= 0 && preferredSlot < handler.size()) { - remainder = insert(handler, preferredSlot, remainder); + remainder = AdjacentSmithingMenu.insert(handler, preferredSlot, remainder); } if (handler != null && !remainder.isEmpty()) { for (int slot = 0; slot < handler.size() && !remainder.isEmpty(); slot++) { if (slot == preferredSlot) continue; - remainder = insert(handler, slot, remainder); + remainder = AdjacentSmithingMenu.insert(handler, slot, remainder); } } if (remainder.isEmpty()) return; @@ -349,11 +349,11 @@ private static ItemStack insert(ResourceHandler handler, int slot, } private boolean containsTemplate(Identifier template) { - return this.adjacentTemplates.stream().anyMatch(stack -> matchesTemplate(stack, template)); + return this.adjacentTemplates.stream().anyMatch(stack -> AdjacentSmithingMenu.matchesTemplate(stack, template)); } private boolean isBorrowedTemplateId(Identifier template) { - return !this.borrowedTemplateStack.isEmpty() && itemId(this.borrowedTemplateStack).equals(template); + return !this.borrowedTemplateStack.isEmpty() && AdjacentSmithingMenu.itemId(this.borrowedTemplateStack).equals(template); } private static void addUniqueTemplate(List templates, ItemStack stack) { @@ -376,13 +376,13 @@ private static int favoriteIndex(List favorites, Identifier template private static int templateIndex(List templates, Identifier template) { for (int index = 0; index < templates.size(); index++) { - if (itemId(templates.get(index)).equals(template)) return index; + if (AdjacentSmithingMenu.itemId(templates.get(index)).equals(template)) return index; } return Integer.MAX_VALUE; } private static boolean matchesTemplate(ItemStack stack, Identifier template) { - return !stack.isEmpty() && itemId(stack).equals(template); + return !stack.isEmpty() && AdjacentSmithingMenu.itemId(stack).equals(template); } private static Identifier itemId(ItemStack stack) { diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/AdvancedComparatorMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/AdvancedComparatorMenu.java index 3461c5a8ff..0ce03ba695 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/AdvancedComparatorMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/AdvancedComparatorMenu.java @@ -46,7 +46,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.ADVANCED_COMPARATOR.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/BaseChuteMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/BaseChuteMenu.java index 7f0a9eb4a9..195949443c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/BaseChuteMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/BaseChuteMenu.java @@ -9,6 +9,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; @@ -82,17 +83,18 @@ private void addPlayerHotbar(Inventory playerInventory) { private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; - private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; - private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + private static final int PLAYER_INVENTORY_SLOT_COUNT = + BaseChuteMenu.PLAYER_INVENTORY_COLUMN_COUNT * BaseChuteMenu.PLAYER_INVENTORY_ROW_COUNT; + private static final int VANILLA_SLOT_COUNT = BaseChuteMenu.HOTBAR_SLOT_COUNT + BaseChuteMenu.PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; - private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; + private static final int TE_INVENTORY_FIRST_SLOT_INDEX = BaseChuteMenu.VANILLA_FIRST_SLOT_INDEX + BaseChuteMenu.VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int TE_INVENTORY_SLOT_COUNT = 9; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player playerIn, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); // noinspection ConstantValue if (sourceSlot == null || !sourceSlot.hasItem()) { return ItemStack.EMPTY; @@ -101,14 +103,17 @@ public ItemStack quickMoveStack(Player playerIn, int index) { final ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots - if (index < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { + if (index < BaseChuteMenu.VANILLA_FIRST_SLOT_INDEX + BaseChuteMenu.VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (this.moveItemToActiveSlot(sourceStack)) { return ItemStack.EMPTY; // EMPTY_ITEM } - } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { + } else if (index < BaseChuteMenu.TE_INVENTORY_FIRST_SLOT_INDEX + BaseChuteMenu.TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory - if (!moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) { + if (!this.moveItemStackTo( + sourceStack, BaseChuteMenu.VANILLA_FIRST_SLOT_INDEX, + BaseChuteMenu.VANILLA_FIRST_SLOT_INDEX + BaseChuteMenu.VANILLA_SLOT_COUNT, false + )) { return ItemStack.EMPTY; } } else { @@ -128,10 +133,10 @@ public ItemStack quickMoveStack(Player playerIn, int index) { // 移动物品到可用槽位 private boolean moveItemToActiveSlot(ItemStack stack) { int count = stack.getCount(); - for (int index = TE_INVENTORY_FIRST_SLOT_INDEX; index < 45; index++) { + for (int index = BaseChuteMenu.TE_INVENTORY_FIRST_SLOT_INDEX; index < 45; index++) { // 只有对应槽位可以放入物品时才向槽位里快速移动物品 if (this.canPlace(stack, index)) { - moveItemStackTo(stack, index, index + 1, false); + this.moveItemStackTo(stack, index, index + 1, false); if (stack.isEmpty()) { break; } @@ -156,7 +161,8 @@ private boolean canPlace(ItemStack stack, int index) { @Override public boolean stillValid(Player player) { - return stillValid(ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, this.getBlock()); + return AbstractContainerMenu.stillValid( + ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, this.getBlock()); } protected abstract Block getBlock(); diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCrafterMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCrafterMenu.java index 60c1684cb3..9763d45f38 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCrafterMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCrafterMenu.java @@ -95,17 +95,19 @@ private void addPlayerHotbar(Inventory playerInventory) { private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; - private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; - private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + private static final int PLAYER_INVENTORY_SLOT_COUNT = + BatchCrafterMenu.PLAYER_INVENTORY_COLUMN_COUNT * BatchCrafterMenu.PLAYER_INVENTORY_ROW_COUNT; + private static final int VANILLA_SLOT_COUNT = BatchCrafterMenu.HOTBAR_SLOT_COUNT + BatchCrafterMenu.PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; - private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; + private static final int TE_INVENTORY_FIRST_SLOT_INDEX = + BatchCrafterMenu.VANILLA_FIRST_SLOT_INDEX + BatchCrafterMenu.VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int TE_INVENTORY_SLOT_COUNT = 9; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player playerIn, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); // noinspection ConstantValue if (sourceSlot == null || !sourceSlot.hasItem()) { return ItemStack.EMPTY; // EMPTY_ITEM @@ -113,17 +115,17 @@ public ItemStack quickMoveStack(Player playerIn, int index) { ItemStack sourceStack = sourceSlot.getItem(); final ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots - if (index < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { + if (index < BatchCrafterMenu.VANILLA_FIRST_SLOT_INDEX + BatchCrafterMenu.VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (this.moveItemToActiveSlot(sourceStack)) { return ItemStack.EMPTY; // EMPTY_ITEM } - } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { + } else if (index < BatchCrafterMenu.TE_INVENTORY_FIRST_SLOT_INDEX + BatchCrafterMenu.TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory - if (!moveItemStackTo( + if (!this.moveItemStackTo( sourceStack, - VANILLA_FIRST_SLOT_INDEX, - VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, + BatchCrafterMenu.VANILLA_FIRST_SLOT_INDEX, + BatchCrafterMenu.VANILLA_FIRST_SLOT_INDEX + BatchCrafterMenu.VANILLA_SLOT_COUNT, false )) { return ItemStack.EMPTY; @@ -148,7 +150,7 @@ private boolean moveItemToActiveSlot(ItemStack stack) { for (int index = BatchCrafterMenu.TE_INVENTORY_FIRST_SLOT_INDEX; index < 45; index++) { // 只有对应槽位可以放入物品时才向槽位里快速移动物品 if (this.canPlace(stack, index)) { - moveItemStackTo(stack, index, index + 1, false); + this.moveItemStackTo(stack, index, index + 1, false); if (stack.isEmpty()) { break; } @@ -174,7 +176,7 @@ private boolean canPlace(ItemStack stack, int index) { @Override public boolean stillValid(Player player) { - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.BATCH_CRAFTER.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCutterMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCutterMenu.java index 1d7d58f033..17b106f9c6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCutterMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/BatchCutterMenu.java @@ -90,17 +90,18 @@ private void addPlayerHotbar(Inventory playerInventory) { private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; - private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; - private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + private static final int PLAYER_INVENTORY_SLOT_COUNT = + BatchCutterMenu.PLAYER_INVENTORY_COLUMN_COUNT * BatchCutterMenu.PLAYER_INVENTORY_ROW_COUNT; + private static final int VANILLA_SLOT_COUNT = BatchCutterMenu.HOTBAR_SLOT_COUNT + BatchCutterMenu.PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; - private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; + private static final int TE_INVENTORY_FIRST_SLOT_INDEX = BatchCutterMenu.VANILLA_FIRST_SLOT_INDEX + BatchCutterMenu.VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int TE_INVENTORY_SLOT_COUNT = 1; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player playerIn, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); // noinspection ConstantValue if (sourceSlot == null || !sourceSlot.hasItem()) { return ItemStack.EMPTY; // EMPTY_ITEM @@ -108,17 +109,17 @@ public ItemStack quickMoveStack(Player playerIn, int index) { ItemStack sourceStack = sourceSlot.getItem(); final ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots - if (index < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { + if (index < BatchCutterMenu.VANILLA_FIRST_SLOT_INDEX + BatchCutterMenu.VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (this.moveItemToActiveSlot(sourceStack)) { return ItemStack.EMPTY; // EMPTY_ITEM } - } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { + } else if (index < BatchCutterMenu.TE_INVENTORY_FIRST_SLOT_INDEX + BatchCutterMenu.TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory - if (!moveItemStackTo( + if (!this.moveItemStackTo( sourceStack, - VANILLA_FIRST_SLOT_INDEX, - VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, + BatchCutterMenu.VANILLA_FIRST_SLOT_INDEX, + BatchCutterMenu.VANILLA_FIRST_SLOT_INDEX + BatchCutterMenu.VANILLA_SLOT_COUNT, false )) { return ItemStack.EMPTY; @@ -166,7 +167,8 @@ private boolean canPlace(ItemStack stack) { @Override public boolean stillValid(Player player) { - return stillValid(ContainerLevelAccess.create(this.level, this.entity.getBlockPos()), player, ModBlocks.BATCH_CUTTER.get()); + return AbstractContainerMenu.stillValid( + ContainerLevelAccess.create(this.level, this.entity.getBlockPos()), player, ModBlocks.BATCH_CUTTER.get()); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/ControlValveMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/ControlValveMenu.java index 646402b5fb..1a7cf7471a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/ControlValveMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/ControlValveMenu.java @@ -43,7 +43,7 @@ public ControlValveMenu( Inventory inventory, FriendlyByteBuf extraData ) { - this(menuType, containerId, inventory, getBlockEntity(inventory, extraData.readBlockPos())); + this(menuType, containerId, inventory, ControlValveMenu.getBlockEntity(inventory, extraData.readBlockPos())); } private ControlValveMenu( @@ -90,7 +90,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { if (this.blockEntity == null) return false; - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.CONTROL_VALVE.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/EmberGrindstoneMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/EmberGrindstoneMenu.java index 9d062af43e..5645048653 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/EmberGrindstoneMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/EmberGrindstoneMenu.java @@ -275,7 +275,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid(this.access, player, ModBlocks.EMBER_GRINDSTONE.get()); + return AbstractContainerMenu.stillValid(this.access, player, ModBlocks.EMBER_GRINDSTONE.get()); } /// 移除 diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/ExpCollectorMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/ExpCollectorMenu.java index 6c99e0c456..6ad0edd04e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/ExpCollectorMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/ExpCollectorMenu.java @@ -73,7 +73,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.EXP_COLLECTOR.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/FilterMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/FilterMenu.java index 6f6b6e89f2..1e1b5c9c28 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/FilterMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/FilterMenu.java @@ -27,10 +27,10 @@ public class FilterMenu extends AbstractContainerMenu { private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; - private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; - private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + private static final int PLAYER_INVENTORY_SLOT_COUNT = FilterMenu.PLAYER_INVENTORY_COLUMN_COUNT * FilterMenu.PLAYER_INVENTORY_ROW_COUNT; + private static final int VANILLA_SLOT_COUNT = FilterMenu.HOTBAR_SLOT_COUNT + FilterMenu.PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_SLOT_INDEX = 0; - private static final int FILTER_FIRST_SLOT_INDEX = VANILLA_SLOT_INDEX + VANILLA_SLOT_COUNT; + private static final int FILTER_FIRST_SLOT_INDEX = FilterMenu.VANILLA_SLOT_INDEX + FilterMenu.VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int FILTER_SLOT_COUNT = 18; // must be the number of slots you have! private final FilterContainer container; @@ -71,10 +71,10 @@ private void addPlayerHotbar(Inventory playerInventory) { public void clicked(int slotIndex, int buttonNum, ContainerInput containerInput, Player player) { if ( containerInput == ContainerInput.SWAP - && slotIndex >= FILTER_FIRST_SLOT_INDEX - && slotIndex < FILTER_FIRST_SLOT_INDEX + FILTER_SLOT_COUNT + && slotIndex >= FilterMenu.FILTER_FIRST_SLOT_INDEX + && slotIndex < FilterMenu.FILTER_FIRST_SLOT_INDEX + FilterMenu.FILTER_SLOT_COUNT && this.getSlot(slotIndex) instanceof FilterOnlySlot filterSlot - && (buttonNum >= 0 && buttonNum < HOTBAR_SLOT_COUNT || buttonNum == Inventory.SLOT_OFFHAND) + && (buttonNum >= 0 && buttonNum < FilterMenu.HOTBAR_SLOT_COUNT || buttonNum == Inventory.SLOT_OFFHAND) ) { filterSlot.set(player.getInventory().getItem(buttonNum).copy()); return; diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/FrostGrindstoneMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/FrostGrindstoneMenu.java index b10fcb1c59..1c9c8498e7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/FrostGrindstoneMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/FrostGrindstoneMenu.java @@ -264,7 +264,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid(this.access, player, ModBlocks.FROST_GRINDSTONE.get()); + return AbstractContainerMenu.stillValid(this.access, player, ModBlocks.FROST_GRINDSTONE.get()); } /// 移除 diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/FrostSmithingMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/FrostSmithingMenu.java index 2a1d7441b8..80d6a283c0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/FrostSmithingMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/FrostSmithingMenu.java @@ -236,9 +236,10 @@ public void sync(int selected, List results) { } public void turn(boolean left) { - if (this.selected == -1 || this.results == null) return; + var selectedRecipe = this.selectedRecipe; + if (this.selected == -1 || this.results == null || selectedRecipe == null) return; this.selected = (this.selected + (left ? -1 : 1)) % this.results.size(); if (this.selected < 0) this.selected += this.results.size(); - this.resultSlots.setItem(0, this.selectedRecipe.value().assemble(this.selected, this.createRecipeInput(), this.level)); + this.resultSlots.setItem(0, selectedRecipe.value().assemble(this.selected, this.createRecipeInput(), this.level)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/HammerOpenedAnvilMenuHelper.java b/src/main/java/dev/dubhe/anvilcraft/inventory/HammerOpenedAnvilMenuHelper.java index c058a94dbc..bd9d3bc4af 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/HammerOpenedAnvilMenuHelper.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/HammerOpenedAnvilMenuHelper.java @@ -27,7 +27,7 @@ public static boolean touchesOpenedHammerSlot( ContainerInput containerInput, int openedHammerSlot ) { - if (isValidInventorySlot(inventory, openedHammerSlot)) return false; + if (HammerOpenedAnvilMenuHelper.isValidInventorySlot(inventory, openedHammerSlot)) return false; if (slotId >= 0 && slotId < menu.slots.size()) { Slot slot = menu.getSlot(slotId); if (slot.container == inventory && slot.getContainerSlot() == openedHammerSlot) { diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/ItemCollectorMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/ItemCollectorMenu.java index 84da2aa43d..a4ff970705 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/ItemCollectorMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/ItemCollectorMenu.java @@ -86,17 +86,19 @@ public void setItem(int slotId, int stateId, ItemStack stack) { private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; - private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; - private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + private static final int PLAYER_INVENTORY_SLOT_COUNT = + ItemCollectorMenu.PLAYER_INVENTORY_COLUMN_COUNT * ItemCollectorMenu.PLAYER_INVENTORY_ROW_COUNT; + private static final int VANILLA_SLOT_COUNT = ItemCollectorMenu.HOTBAR_SLOT_COUNT + ItemCollectorMenu.PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; - private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; + private static final int TE_INVENTORY_FIRST_SLOT_INDEX = + ItemCollectorMenu.VANILLA_FIRST_SLOT_INDEX + ItemCollectorMenu.VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int TE_INVENTORY_SLOT_COUNT = 9; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player playerIn, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); // noinspection ConstantValue if (sourceSlot == null || !sourceSlot.hasItem()) { return ItemStack.EMPTY; @@ -105,14 +107,19 @@ public ItemStack quickMoveStack(Player playerIn, int index) { final ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots - if (index < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { + if (index < ItemCollectorMenu.VANILLA_FIRST_SLOT_INDEX + ItemCollectorMenu.VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (this.moveItemToActiveSlot(sourceStack)) { return ItemStack.EMPTY; // EMPTY_ITEM } - } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { + } else if (index < ItemCollectorMenu.TE_INVENTORY_FIRST_SLOT_INDEX + ItemCollectorMenu.TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory - if (!this.moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) { + if (!this.moveItemStackTo( + sourceStack, + ItemCollectorMenu.VANILLA_FIRST_SLOT_INDEX, + ItemCollectorMenu.VANILLA_FIRST_SLOT_INDEX + ItemCollectorMenu.VANILLA_SLOT_COUNT, + false + )) { return ItemStack.EMPTY; } } else { @@ -132,7 +139,7 @@ public ItemStack quickMoveStack(Player playerIn, int index) { // 移动物品到可用槽位 private boolean moveItemToActiveSlot(ItemStack stack) { int count = stack.getCount(); - for (int index = TE_INVENTORY_FIRST_SLOT_INDEX; index < 45; index++) { + for (int index = ItemCollectorMenu.TE_INVENTORY_FIRST_SLOT_INDEX; index < 45; index++) { // 只有对应槽位可以放入物品时才向槽位里快速移动物品 if (this.canPlace(stack, index)) { this.moveItemStackTo(stack, index, index + 1, false); @@ -158,7 +165,11 @@ private boolean canPlace(ItemStack stack, int index) { @Override public boolean stillValid(Player player) { - return stillValid(ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.ITEM_COLLECTOR.get()); + return AbstractContainerMenu.stillValid( + ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), + player, + ModBlocks.ITEM_COLLECTOR.get() + ); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/ItemDetectorMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/ItemDetectorMenu.java index 4c128ca5d8..3cb60283d5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/ItemDetectorMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/ItemDetectorMenu.java @@ -72,17 +72,18 @@ private void addPlayerHotbar(Inventory playerInventory) { private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; - private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; - private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + private static final int PLAYER_INVENTORY_SLOT_COUNT = + ItemDetectorMenu.PLAYER_INVENTORY_COLUMN_COUNT * ItemDetectorMenu.PLAYER_INVENTORY_ROW_COUNT; + private static final int VANILLA_SLOT_COUNT = ItemDetectorMenu.HOTBAR_SLOT_COUNT + ItemDetectorMenu.PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; - private static final int FILTER_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; + private static final int FILTER_FIRST_SLOT_INDEX = ItemDetectorMenu.VANILLA_FIRST_SLOT_INDEX + ItemDetectorMenu.VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int FILTER_SLOT_COUNT = 9; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player player, int index) { // Check if the slot clicked is one of the vanilla container slots - if (index >= VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { + if (index >= ItemDetectorMenu.VANILLA_FIRST_SLOT_INDEX + ItemDetectorMenu.VANILLA_SLOT_COUNT) { return ItemStack.EMPTY; } Slot sourceSlot = this.getSlot(index); @@ -92,15 +93,15 @@ public ItemStack quickMoveStack(Player player, int index) { } // EMPTY_ITEM ItemStack sourceStack = sourceSlot.getItem(); // This is a vanilla container slot so try to set filter - for (int j = 0; j < FILTER_SLOT_COUNT; j++) { - Slot slot = this.getSlot(FILTER_FIRST_SLOT_INDEX + j); + for (int j = 0; j < ItemDetectorMenu.FILTER_SLOT_COUNT; j++) { + Slot slot = this.getSlot(ItemDetectorMenu.FILTER_FIRST_SLOT_INDEX + j); if (!(slot instanceof FilterOnlySlot filterSlot)) continue; if (!filterSlot.getItem().is(sourceStack.getItem())) continue; filterSlot.set(sourceStack.copy()); return ItemStack.EMPTY; } - for (int j = 0; j < FILTER_SLOT_COUNT; j++) { - Slot slot = this.getSlot(FILTER_FIRST_SLOT_INDEX + j); + for (int j = 0; j < ItemDetectorMenu.FILTER_SLOT_COUNT; j++) { + Slot slot = this.getSlot(ItemDetectorMenu.FILTER_FIRST_SLOT_INDEX + j); if (!(slot instanceof FilterOnlySlot filterSlot)) continue; if (!filterSlot.getItem().isEmpty()) continue; filterSlot.set(sourceStack.copy()); @@ -113,10 +114,10 @@ public ItemStack quickMoveStack(Player player, int index) { public void clicked(int slotId, int button, ContainerInput input, Player player) { if ( input == ContainerInput.SWAP - && slotId >= FILTER_FIRST_SLOT_INDEX - && slotId < FILTER_FIRST_SLOT_INDEX + FILTER_SLOT_COUNT + && slotId >= ItemDetectorMenu.FILTER_FIRST_SLOT_INDEX + && slotId < ItemDetectorMenu.FILTER_FIRST_SLOT_INDEX + ItemDetectorMenu.FILTER_SLOT_COUNT && this.getSlot(slotId) instanceof FilterOnlySlot filterSlot - && (button >= 0 && button < HOTBAR_SLOT_COUNT || button == Inventory.SLOT_OFFHAND) + && (button >= 0 && button < ItemDetectorMenu.HOTBAR_SLOT_COUNT || button == Inventory.SLOT_OFFHAND) ) { filterSlot.set(player.getInventory().getItem(button).copy()); return; diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/JewelCraftingMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/JewelCraftingMenu.java index f990777301..553a1b3440 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/JewelCraftingMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/JewelCraftingMenu.java @@ -97,7 +97,7 @@ private void addPlayerHotbar(Inventory playerInventory) { @Override public ItemStack quickMoveStack(Player player, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); if (!sourceSlot.hasItem()) { return ItemStack.EMPTY; // EMPTY_ITEM } @@ -107,14 +107,14 @@ public ItemStack quickMoveStack(Player player, int index) { // noinspection ConstantValue if (sourceSlot == null || !sourceSlot.hasItem()) return sourceStack; - if (index == RESULT_SLOT) { + if (index == JewelCraftingMenu.RESULT_SLOT) { int totalCrafted = 0; while (true) { ItemStack currentResult = sourceSlot.getItem(); if (currentResult.isEmpty()) break; ItemStack moveStack = currentResult.copy(); - if (!moveItemStackTo(moveStack, INV_SLOT_START, USE_ROW_SLOT_END, true)) { + if (!this.moveItemStackTo(moveStack, JewelCraftingMenu.INV_SLOT_START, JewelCraftingMenu.USE_ROW_SLOT_END, true)) { break; } @@ -134,11 +134,11 @@ public ItemStack quickMoveStack(Player player, int index) { } return totalCrafted > 0 ? sourceStack.copyWithCount(totalCrafted) : ItemStack.EMPTY; - } else if (index >= SOURCE_SLOT && index < CRAFT_SLOT_END) { - if (!moveItemStackTo(copyOfSourceStack, INV_SLOT_START, USE_ROW_SLOT_END, true)) { + } else if (index >= JewelCraftingMenu.SOURCE_SLOT && index < JewelCraftingMenu.CRAFT_SLOT_END) { + if (!this.moveItemStackTo(copyOfSourceStack, JewelCraftingMenu.INV_SLOT_START, JewelCraftingMenu.USE_ROW_SLOT_END, true)) { return ItemStack.EMPTY; } - } else if (index >= INV_SLOT_START && index < USE_ROW_SLOT_END) { + } else if (index >= JewelCraftingMenu.INV_SLOT_START && index < JewelCraftingMenu.USE_ROW_SLOT_END) { ItemStack empty = this.quickMoveInvStack(index, copyOfSourceStack); if (empty != null) return empty; } @@ -154,7 +154,7 @@ public ItemStack quickMoveStack(Player player, int index) { sourceStack.setCount(copyOfSourceStack.getCount()); sourceSlot.onTake(player, copyOfSourceStack); - if (index == RESULT_SLOT) { + if (index == JewelCraftingMenu.RESULT_SLOT) { player.drop(copyOfSourceStack, false); } return sourceStack; @@ -162,14 +162,24 @@ public ItemStack quickMoveStack(Player player, int index) { protected @Nullable ItemStack quickMoveInvStack(int index, ItemStack copyOfSourceStack) { // 从背包里转移物品 - if (this.moveItemStackTo(copyOfSourceStack, SOURCE_SLOT, SOURCE_SLOT + 1, false)) { + if (this.moveItemStackTo(copyOfSourceStack, JewelCraftingMenu.SOURCE_SLOT, JewelCraftingMenu.SOURCE_SLOT + 1, false)) { this.slotsChanged(this.sourceContainer); - } else if (this.moveItemStackTo(copyOfSourceStack, CRAFT_SLOT_START, CRAFT_SLOT_END, false)) { + } else if (this.moveItemStackTo(copyOfSourceStack, JewelCraftingMenu.CRAFT_SLOT_START, JewelCraftingMenu.CRAFT_SLOT_END, false)) { this.slotsChanged(this.craftingContainer); - } else if (index < INV_SLOT_END && !this.moveItemStackTo(copyOfSourceStack, USE_ROW_SLOT_START, USE_ROW_SLOT_END, false)) { + } else if (index < JewelCraftingMenu.INV_SLOT_END && !this.moveItemStackTo( + copyOfSourceStack, + JewelCraftingMenu.USE_ROW_SLOT_START, + JewelCraftingMenu.USE_ROW_SLOT_END, + false + )) { // 移到快捷栏 return ItemStack.EMPTY; - } else if (index >= INV_SLOT_END && !this.moveItemStackTo(copyOfSourceStack, INV_SLOT_START, INV_SLOT_END, false)) { + } else if (index >= JewelCraftingMenu.INV_SLOT_END && !this.moveItemStackTo( + copyOfSourceStack, + JewelCraftingMenu.INV_SLOT_START, + JewelCraftingMenu.INV_SLOT_END, + false + )) { // 移动到背包 return ItemStack.EMPTY; } @@ -178,7 +188,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid(this.access, player, ModBlocks.JEWEL_CRAFTING_TABLE.get()); + return AbstractContainerMenu.stillValid(this.access, player, ModBlocks.JEWEL_CRAFTING_TABLE.get()); } public @Nullable RecipeHolder findRecipeBySource(ItemStack source) { @@ -191,13 +201,13 @@ public boolean stillValid(Player player) { @Override public void slotsChanged(Container container) { - for (int i = CRAFT_SLOT_START; i < CRAFT_SLOT_END; i++) { - Slot slot = slots.get(i); + for (int i = JewelCraftingMenu.CRAFT_SLOT_START; i < JewelCraftingMenu.CRAFT_SLOT_END; i++) { + Slot slot = this.slots.get(i); if (slot instanceof JewelInputSlot inputSlot) { inputSlot.updateIngredient(); } } - this.access.execute((level, _) -> changedCraftingSlots( + this.access.execute((level, _) -> JewelCraftingMenu.changedCraftingSlots( this, level, this.player, @@ -240,11 +250,11 @@ private static void changedCraftingSlots( } } resultContainer.setItem(0, itemStack); - menu.setRemoteSlot(RESULT_SLOT, itemStack); + menu.setRemoteSlot(JewelCraftingMenu.RESULT_SLOT, itemStack); serverPlayer.connection.send(new ClientboundContainerSetSlotPacket( menu.containerId, menu.incrementStateId(), - RESULT_SLOT, + JewelCraftingMenu.RESULT_SLOT, itemStack )); } @@ -264,14 +274,14 @@ public void autoFill() { List ingredients = recipe.ingredients(); for (int i = 0; i < Math.min(ingredients.size(), 4); i++) { - this.quickMoveStack(this.player, CRAFT_SLOT_START + i); - this.moveInvItemTo(ingredients.get(i), CRAFT_SLOT_START + i); + this.quickMoveStack(this.player, JewelCraftingMenu.CRAFT_SLOT_START + i); + this.moveInvItemTo(ingredients.get(i), JewelCraftingMenu.CRAFT_SLOT_START + i); } } protected void moveInvItemTo(ItemIngredientPredicate needItem, int targetIndex) { - for (int i = INV_SLOT_START; i < USE_ROW_SLOT_END; i++) { - Slot slot = slots.get(i); + for (int i = JewelCraftingMenu.INV_SLOT_START; i < JewelCraftingMenu.USE_ROW_SLOT_END; i++) { + Slot slot = this.slots.get(i); if (!needItem.test(slot.getItem())) continue; if (!this.moveItemStackTo(slot.getItem(), targetIndex, targetIndex + 1, false)) { return; diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/PulseGeneratorMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/PulseGeneratorMenu.java index df6be107d0..9ab07c3536 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/PulseGeneratorMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/PulseGeneratorMenu.java @@ -43,7 +43,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.PULSE_GENERATOR.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalGrindstoneMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalGrindstoneMenu.java index af7462d43d..7462df7a23 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalGrindstoneMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalGrindstoneMenu.java @@ -50,8 +50,8 @@ public class RoyalGrindstoneMenu extends AbstractContainerMenu { public @Nullable RepairCostRecipeEntry currentRecipe = null; static { - REPAIR_COST_RECIPES.put(Items.GOLD_INGOT, new RepairCostRecipeEntry(1, ModItems.CURSED_GOLD_INGOT.get())); - REPAIR_COST_RECIPES.put(Items.GOLD_BLOCK, new RepairCostRecipeEntry(9, ModBlocks.CURSED_GOLD_BLOCK.asItem())); + RoyalGrindstoneMenu.REPAIR_COST_RECIPES.put(Items.GOLD_INGOT, new RepairCostRecipeEntry(1, ModItems.CURSED_GOLD_INGOT.get())); + RoyalGrindstoneMenu.REPAIR_COST_RECIPES.put(Items.GOLD_BLOCK, new RepairCostRecipeEntry(9, ModBlocks.CURSED_GOLD_BLOCK.asItem())); } public RoyalGrindstoneMenu(MenuType type, int containerId, Inventory playerInventory) { @@ -116,18 +116,20 @@ public boolean mayPlace(ItemStack stack) { public void onTake(Player player, ItemStack stack) { player.playSound(SoundEvents.GRINDSTONE_USE); - if (RoyalGrindstoneMenu.this.currentRecipe != null) { + RepairCostRecipeEntry currentRecipe = RoyalGrindstoneMenu.this.currentRecipe; + Item repairMaterial = RoyalGrindstoneMenu.this.repairMaterial; + if (currentRecipe != null && repairMaterial != null) { RoyalGrindstoneMenu.this.resultMaterialSlots.setItem( 2, new ItemStack( - RoyalGrindstoneMenu.this.currentRecipe.item, + currentRecipe.item, RoyalGrindstoneMenu.this.usedGold + RoyalGrindstoneMenu.this.resultMaterialSlots.getItem(2).getCount() ) ); RoyalGrindstoneMenu.this.repairMaterialSlots.setItem( 0, new ItemStack( - RoyalGrindstoneMenu.this.repairMaterial, + repairMaterial, RoyalGrindstoneMenu.this.repairMaterialSlots.getItem(0).getCount() - RoyalGrindstoneMenu.this.usedGold ) ); @@ -161,7 +163,7 @@ private ItemStack createResult() { final ItemStack repairMaterialSlotItem = this.repairMaterialSlots.getItem(0); final ItemStack resultMaterialSlotItem = this.resultMaterialSlots.getItem(0); this.repairMaterial = repairMaterialSlotItem.getItem(); - this.currentRecipe = REPAIR_COST_RECIPES.getOrDefault(repairMaterialSlotItem.getItem(), null); + this.currentRecipe = RoyalGrindstoneMenu.REPAIR_COST_RECIPES.get(repairMaterialSlotItem.getItem()); if (!resultMaterialSlotItem.isEmpty() && this.currentRecipe != null && resultMaterialSlotItem.getItem() != this.currentRecipe.item @@ -202,16 +204,16 @@ private ItemStack createResult() { this.removedRepairCost = Math.min(repairCost, maxRemovable); int remainRepairCost = repairCost - this.removedRepairCost; result.set(DataComponents.REPAIR_COST, remainRepairCost); - if (repairMaterialSlotItem.is(DEFAULT_REPAIR_MATERIAL) - && repairMaterialSlotItem.getCount() - this.usedGold >= GOLD_PER_CURSE + if (repairMaterialSlotItem.is(RoyalGrindstoneMenu.DEFAULT_REPAIR_MATERIAL) + && repairMaterialSlotItem.getCount() - this.usedGold >= RoyalGrindstoneMenu.GOLD_PER_CURSE && mutEnch != null) { Iterator> iterator = mutEnch.keySet().iterator(); - while (iterator.hasNext() && repairMaterialUsable >= GOLD_PER_CURSE) { + while (iterator.hasNext() && repairMaterialUsable >= RoyalGrindstoneMenu.GOLD_PER_CURSE) { Holder curseEnchantment = iterator.next(); if (!curseEnchantment.is(EnchantmentTags.CURSE)) continue; iterator.remove(); - this.usedGold += GOLD_PER_CURSE; - repairMaterialUsable -= GOLD_PER_CURSE; + this.usedGold += RoyalGrindstoneMenu.GOLD_PER_CURSE; + repairMaterialUsable -= RoyalGrindstoneMenu.GOLD_PER_CURSE; this.removedCurseCount += 1; } result.set(enchantmentComponent, mutEnch.toImmutable()); @@ -277,7 +279,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid(this.access, player, ModBlocks.ROYAL_GRINDSTONE.get()); + return AbstractContainerMenu.stillValid(this.access, player, ModBlocks.ROYAL_GRINDSTONE.get()); } @Override @@ -321,7 +323,7 @@ protected void clearContainer(Player player, Container container) { } private boolean isRepairMaterial(ItemStack stack) { - return REPAIR_COST_RECIPES.containsKey(stack.getItem()); + return RoyalGrindstoneMenu.REPAIR_COST_RECIPES.containsKey(stack.getItem()); } public record RepairCostRecipeEntry(int count, Item item) { diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalSmithingMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalSmithingMenu.java index bde4fef104..81df218503 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalSmithingMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/RoyalSmithingMenu.java @@ -51,7 +51,7 @@ private RoyalSmithingMenu( ContainerLevelAccess access, Level level ) { - super(type, containerId, inventory, access, createInputSlotDefinitions(level.recipeAccess())); + super(type, containerId, inventory, access, RoyalSmithingMenu.createInputSlotDefinitions(level.recipeAccess())); this.level = level; this.baseItemTest = level.recipeAccess().propertySet(RecipePropertySet.SMITHING_BASE); this.templateItemTest = level.recipeAccess().propertySet(RecipePropertySet.SMITHING_TEMPLATE); diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/SliderMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/SliderMenu.java index 7150a871d4..3980981e34 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/SliderMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/SliderMenu.java @@ -26,7 +26,7 @@ public SliderMenu(int containerId, Callback callback) { @Override public ItemStack quickMoveStack(Player player, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); // noinspection ConstantValue if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY; return sourceSlot.getItem(); diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/SmartBlockPlacerMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/SmartBlockPlacerMenu.java index 85c6afb11a..8776f0d158 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/SmartBlockPlacerMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/SmartBlockPlacerMenu.java @@ -5,6 +5,7 @@ import dev.dubhe.anvilcraft.init.item.ModItems; import dev.dubhe.anvilcraft.inventory.component.BookOnlySlot; import dev.dubhe.anvilcraft.inventory.component.StructureDiskOnlySlot; +import dev.dubhe.anvilcraft.inventory.component.WrittenBookOnlySlot; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -13,6 +14,7 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import org.jspecify.annotations.Nullable; @@ -43,7 +45,7 @@ public SmartBlockPlacerMenu( // 提取条件:只有当书槽位为空时才能取出磁盘 () -> this.blockEntity.getBookInventory().getItem(0).isEmpty() )); - + // 添加蓝图模式书物品栏槽位(输入,1个槽位,只在蓝图模式下显示) int bookSlotX = 46; int bookSlotY = 86; @@ -55,11 +57,11 @@ public SmartBlockPlacerMenu( // 可见性条件:只有当结构磁盘槽位有物品时才可见 () -> !this.blockEntity.getDiskInventory().getItem(0).isEmpty() )); - + // 添加蓝图模式输出书物品栏槽位(输出,1个槽位,只在蓝图模式下显示) int outputBookSlotX = 84; int outputBookSlotY = 86; - this.addSlot(new dev.dubhe.anvilcraft.inventory.component.WrittenBookOnlySlot( + this.addSlot(new WrittenBookOnlySlot( this.blockEntity.getOutputBookInventory(), 0, outputBookSlotX, @@ -96,8 +98,10 @@ public SmartBlockPlacerBlockEntity getBlockEntity() { private static final int OUTPUT_BOOK_SLOT_COUNT = 1; // 输出书物品栏1个槽位 private static final int PLAYER_INVENTORY_SLOT_COUNT = 27; // 主物品栏3行9列 private static final int HOTBAR_SLOT_COUNT = 9; // 快捷栏1行9列 - private static final int VANILLA_SLOT_COUNT = PLAYER_INVENTORY_SLOT_COUNT + HOTBAR_SLOT_COUNT; - private static final int TOTAL_SLOT_COUNT = STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT + OUTPUT_BOOK_SLOT_COUNT + VANILLA_SLOT_COUNT; + private static final int VANILLA_SLOT_COUNT = SmartBlockPlacerMenu.PLAYER_INVENTORY_SLOT_COUNT + SmartBlockPlacerMenu.HOTBAR_SLOT_COUNT; + private static final int TOTAL_SLOT_COUNT = + SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT + SmartBlockPlacerMenu.OUTPUT_BOOK_SLOT_COUNT + + SmartBlockPlacerMenu.VANILLA_SLOT_COUNT; @Override public ItemStack quickMoveStack(Player player, int index) { @@ -108,52 +112,68 @@ public ItemStack quickMoveStack(Player player, int index) { itemstack = originalStack.copy(); // Structure Disk槽位(索引0)的物品移动到玩家物品栏 - if (index < STRUCTURE_DISK_SLOT_COUNT) { + if (index < SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT) { // 检查书槽位是否有书,如果有则不允许取出磁盘 if (this.blockEntity != null && !this.blockEntity.getBookInventory().getItem(0).isEmpty()) { return ItemStack.EMPTY; } - if (!this.moveItemStackTo(originalStack, - STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT + OUTPUT_BOOK_SLOT_COUNT, TOTAL_SLOT_COUNT, false)) { + if (!this.moveItemStackTo( + originalStack, + SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT + + SmartBlockPlacerMenu.OUTPUT_BOOK_SLOT_COUNT, SmartBlockPlacerMenu.TOTAL_SLOT_COUNT, false + )) { return ItemStack.EMPTY; } - } else if (index < STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT) { // Book槽位(索引1)的物品移动到玩家物品栏 - if (!this.moveItemStackTo(originalStack, - STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT + OUTPUT_BOOK_SLOT_COUNT, TOTAL_SLOT_COUNT, false)) { + } else if (index + < SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT) { // Book槽位(索引1)的物品移动到玩家物品栏 + if (!this.moveItemStackTo( + originalStack, + SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT + + SmartBlockPlacerMenu.OUTPUT_BOOK_SLOT_COUNT, SmartBlockPlacerMenu.TOTAL_SLOT_COUNT, false + )) { return ItemStack.EMPTY; } - } else if (index < STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT + OUTPUT_BOOK_SLOT_COUNT) { + } else if (index < SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT + + SmartBlockPlacerMenu.OUTPUT_BOOK_SLOT_COUNT) { // Output Book槽位(索引2)的物品移动到玩家物品栏 - if (!this.moveItemStackTo(originalStack, - STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT + OUTPUT_BOOK_SLOT_COUNT, TOTAL_SLOT_COUNT, true)) { + if (!this.moveItemStackTo( + originalStack, + SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT + + SmartBlockPlacerMenu.OUTPUT_BOOK_SLOT_COUNT, SmartBlockPlacerMenu.TOTAL_SLOT_COUNT, true + )) { return ItemStack.EMPTY; } - } else if (index < TOTAL_SLOT_COUNT) { // 玩家物品栏的物品移动 + } else if (index < SmartBlockPlacerMenu.TOTAL_SLOT_COUNT) { // 玩家物品栏的物品移动 // 检查是否是蓝图模式 boolean isBlueprintMode = this.blockEntity != null && !this.blockEntity.getDiskInventory().getItem(0).isEmpty(); - + if (originalStack.is(ModItems.STRUCTURE_DISK.get())) { // Structure Disk尝试移动到Disk槽位 - if (!this.moveItemStackTo(originalStack, 0, STRUCTURE_DISK_SLOT_COUNT, false)) { + if (!this.moveItemStackTo(originalStack, 0, SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT, false)) { return ItemStack.EMPTY; } - } else if (isBlueprintMode - && (originalStack.is(net.minecraft.world.item.Items.WRITTEN_BOOK) - || originalStack.is(net.minecraft.world.item.Items.WRITABLE_BOOK) - || originalStack.is(net.minecraft.world.item.Items.BOOK))) { + } else if (isBlueprintMode + && (originalStack.is(Items.WRITTEN_BOOK) + || originalStack.is(Items.WRITABLE_BOOK) + || originalStack.is(Items.BOOK))) { // 蓝图模式下的书尝试移动到Book槽位(输入) - if (!this.moveItemStackTo(originalStack, - STRUCTURE_DISK_SLOT_COUNT, STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT, false)) { + if (!this.moveItemStackTo( + originalStack, + SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT, SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + + SmartBlockPlacerMenu.BOOK_SLOT_COUNT, false + )) { return ItemStack.EMPTY; } } else { // 其他物品在玩家物品栏内部移动(主物品栏<->快捷栏) // 非蓝图模式下,书也会走这个分支 // 玩家物品栏始终从索引 3 开始(disk + book + outputBook) - int playerInventoryStart = STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT + OUTPUT_BOOK_SLOT_COUNT; - int playerInventoryEnd = - STRUCTURE_DISK_SLOT_COUNT + BOOK_SLOT_COUNT + OUTPUT_BOOK_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; - + int playerInventoryStart = SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT + + SmartBlockPlacerMenu.OUTPUT_BOOK_SLOT_COUNT; + int playerInventoryEnd = + SmartBlockPlacerMenu.STRUCTURE_DISK_SLOT_COUNT + SmartBlockPlacerMenu.BOOK_SLOT_COUNT + + SmartBlockPlacerMenu.OUTPUT_BOOK_SLOT_COUNT + SmartBlockPlacerMenu.PLAYER_INVENTORY_SLOT_COUNT; + if (index >= playerInventoryEnd) { // 从快捷栏移动到主物品栏 if (!this.moveItemStackTo(originalStack, playerInventoryStart, playerInventoryEnd, false)) { @@ -161,7 +181,7 @@ public ItemStack quickMoveStack(Player player, int index) { } } else { // 从主物品栏移动到快捷栏 - if (!this.moveItemStackTo(originalStack, playerInventoryEnd, TOTAL_SLOT_COUNT, false)) { + if (!this.moveItemStackTo(originalStack, playerInventoryEnd, SmartBlockPlacerMenu.TOTAL_SLOT_COUNT, false)) { return ItemStack.EMPTY; } } @@ -183,7 +203,7 @@ public boolean stillValid(Player player) { if (this.blockEntity == null) { return false; } - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.SMART_BLOCK_PLACER.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/StructureScannerMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/StructureScannerMenu.java index 7247425c3f..c735669bdf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/StructureScannerMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/StructureScannerMenu.java @@ -80,8 +80,10 @@ public boolean mayPlace(ItemStack stack) { private static final int OUTPUT_SLOT_COUNT = 1; // 输出槽位1个槽位 private static final int PLAYER_INVENTORY_SLOT_COUNT = 27; // 主物品栏3行9列 private static final int HOTBAR_SLOT_COUNT = 9; // 快捷栏1行9列 - private static final int VANILLA_SLOT_COUNT = PLAYER_INVENTORY_SLOT_COUNT + HOTBAR_SLOT_COUNT; - private static final int TOTAL_SLOT_COUNT = STRUCTURE_DISK_SLOT_COUNT + OUTPUT_SLOT_COUNT + VANILLA_SLOT_COUNT; + private static final int VANILLA_SLOT_COUNT = StructureScannerMenu.PLAYER_INVENTORY_SLOT_COUNT + StructureScannerMenu.HOTBAR_SLOT_COUNT; + private static final int TOTAL_SLOT_COUNT = StructureScannerMenu.STRUCTURE_DISK_SLOT_COUNT + + StructureScannerMenu.OUTPUT_SLOT_COUNT + + StructureScannerMenu.VANILLA_SLOT_COUNT; @Override public ItemStack quickMoveStack(Player player, int index) { @@ -92,29 +94,41 @@ public ItemStack quickMoveStack(Player player, int index) { itemstack = originalStack.copy(); // Structure Disk槽位(索引0)或输出槽位(索引1)的物品移动到玩家物品栏 - if (index < STRUCTURE_DISK_SLOT_COUNT + OUTPUT_SLOT_COUNT) { - if (!this.moveItemStackTo(originalStack, STRUCTURE_DISK_SLOT_COUNT + OUTPUT_SLOT_COUNT, TOTAL_SLOT_COUNT, false)) { + if (index < StructureScannerMenu.STRUCTURE_DISK_SLOT_COUNT + StructureScannerMenu.OUTPUT_SLOT_COUNT) { + if (!this.moveItemStackTo( + originalStack, + StructureScannerMenu.STRUCTURE_DISK_SLOT_COUNT + StructureScannerMenu.OUTPUT_SLOT_COUNT, + StructureScannerMenu.TOTAL_SLOT_COUNT, + false + )) { return ItemStack.EMPTY; } - } else if (index < TOTAL_SLOT_COUNT) { // 玩家物品栏的物品移动 + } else if (index < StructureScannerMenu.TOTAL_SLOT_COUNT) { // 玩家物品栏的物品移动 if (originalStack.is(ModItems.STRUCTURE_DISK.get())) { // Structure Disk尝试移动到Disk槽位 - if (!this.moveItemStackTo(originalStack, 0, STRUCTURE_DISK_SLOT_COUNT, false)) { + if (!this.moveItemStackTo(originalStack, 0, StructureScannerMenu.STRUCTURE_DISK_SLOT_COUNT, false)) { return ItemStack.EMPTY; } } else { // 其他物品在玩家物品栏内部移动(主物品栏<->快捷栏) - int playerInventoryEnd = STRUCTURE_DISK_SLOT_COUNT + OUTPUT_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + int playerInventoryEnd = StructureScannerMenu.STRUCTURE_DISK_SLOT_COUNT + + StructureScannerMenu.OUTPUT_SLOT_COUNT + + StructureScannerMenu.PLAYER_INVENTORY_SLOT_COUNT; if (index >= playerInventoryEnd) { // 从快捷栏移动到主物品栏 - if (!this.moveItemStackTo(originalStack, - STRUCTURE_DISK_SLOT_COUNT + OUTPUT_SLOT_COUNT, playerInventoryEnd, false)) { + if (!this.moveItemStackTo( + originalStack, + StructureScannerMenu.STRUCTURE_DISK_SLOT_COUNT + + StructureScannerMenu.OUTPUT_SLOT_COUNT, + playerInventoryEnd, + false + )) { return ItemStack.EMPTY; } } else { // 从主物品栏移动到快捷栏 - if (!this.moveItemStackTo(originalStack, playerInventoryEnd, TOTAL_SLOT_COUNT, false)) { + if (!this.moveItemStackTo(originalStack, playerInventoryEnd, StructureScannerMenu.TOTAL_SLOT_COUNT, false)) { return ItemStack.EMPTY; } } @@ -133,7 +147,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.STRUCTURE_SCANNER.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/StructureToolMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/StructureToolMenu.java index 939f9ee048..1a4680c140 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/StructureToolMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/StructureToolMenu.java @@ -36,18 +36,18 @@ private void addPlayerHotbar(Inventory playerInventory) { @Override public ItemStack quickMoveStack(Player player, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); if (!sourceSlot.hasItem()) return ItemStack.EMPTY; ItemStack sourceStack = sourceSlot.getItem(); final ItemStack copyOfSourceStack = sourceStack.copy(); if (index < 4 * 9) { - if (!moveItemStackTo(sourceStack, 4 * 9, 4 * 9 + 1, false)) { + if (!this.moveItemStackTo(sourceStack, 4 * 9, 4 * 9 + 1, false)) { return ItemStack.EMPTY; } } else if (index == 4 * 9) { - if (!moveItemStackTo(sourceStack, 0, 4 * 9, false)) { + if (!this.moveItemStackTo(sourceStack, 0, 4 * 9, false)) { return ItemStack.EMPTY; } } else { @@ -65,7 +65,7 @@ public boolean stillValid(Player player) { public void removed(Player player) { super.removed(player); if (player instanceof ServerPlayer serverPlayer) { - ItemStack slotStack = slots.get(4 * 9).getItem(); + ItemStack slotStack = this.slots.get(4 * 9).getItem(); if (!slotStack.isEmpty()) { if (serverPlayer.isAlive() && !serverPlayer.hasDisconnected()) { player.getInventory().placeItemBackInInventory(slotStack); diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/TeslaTowerMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/TeslaTowerMenu.java index 28ceacf42d..6eb7e0b2e5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/TeslaTowerMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/TeslaTowerMenu.java @@ -45,7 +45,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid( + return AbstractContainerMenu.stillValid( ContainerLevelAccess.create(this.level, this.blockEntity.getBlockPos()), player, ModBlocks.TESLA_TOWER.get() diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/TradingStationMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/TradingStationMenu.java index a73a6393d7..1d8efd49fc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/TradingStationMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/TradingStationMenu.java @@ -121,34 +121,39 @@ private void addPlayerHotbar(Inventory playerInventory) { private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; - private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; - private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; + private static final int PLAYER_INVENTORY_SLOT_COUNT = + TradingStationMenu.PLAYER_INVENTORY_COLUMN_COUNT * TradingStationMenu.PLAYER_INVENTORY_ROW_COUNT; + private static final int VANILLA_SLOT_COUNT = TradingStationMenu.HOTBAR_SLOT_COUNT + TradingStationMenu.PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; - private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; + private static final int TE_INVENTORY_FIRST_SLOT_INDEX = + TradingStationMenu.VANILLA_FIRST_SLOT_INDEX + TradingStationMenu.VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int TE_INVENTORY_SLOT_COUNT = 12; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player player, int index) { - Slot sourceSlot = slots.get(index); + Slot sourceSlot = this.slots.get(index); // noinspection ConstantValue if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY; ItemStack sourceStack = sourceSlot.getItem(); final ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots - if (index < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { + if (index < TradingStationMenu.VANILLA_FIRST_SLOT_INDEX + TradingStationMenu.VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (this.moveItemToActiveSlot(sourceStack)) { return ItemStack.EMPTY; // EMPTY_ITEM } - } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { + } else if (index < TradingStationMenu.TE_INVENTORY_FIRST_SLOT_INDEX + TradingStationMenu.TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory - if (!this.moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) { + if (!this.moveItemStackTo( + sourceStack, TradingStationMenu.VANILLA_FIRST_SLOT_INDEX, TradingStationMenu.VANILLA_FIRST_SLOT_INDEX + + TradingStationMenu.VANILLA_SLOT_COUNT, false + )) { return ItemStack.EMPTY; } - } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT + 3) { + } else if (index < TradingStationMenu.TE_INVENTORY_FIRST_SLOT_INDEX + TradingStationMenu.TE_INVENTORY_SLOT_COUNT + 3) { // This is a filter slot so just skip it return ItemStack.EMPTY; } else { @@ -168,7 +173,7 @@ public ItemStack quickMoveStack(Player player, int index) { // 移动物品到可用槽位 private boolean moveItemToActiveSlot(ItemStack stack) { int count = stack.getCount(); - for (int index = TE_INVENTORY_FIRST_SLOT_INDEX; index < 48; index++) { + for (int index = TradingStationMenu.TE_INVENTORY_FIRST_SLOT_INDEX; index < 48; index++) { // 只有对应槽位可以放入物品时才向槽位里快速移动物品 if (this.canPlace(stack, index)) { this.moveItemStackTo(stack, index, index + 1, false); @@ -195,7 +200,7 @@ public boolean isFilterEnabled() { @Override public int getFilterSlotIndex(Slot slot) { - return slot.index - TE_INVENTORY_FIRST_SLOT_INDEX; + return slot.index - TradingStationMenu.TE_INVENTORY_FIRST_SLOT_INDEX; } @Override @@ -205,6 +210,7 @@ public void flush() { @Override public boolean stillValid(Player player) { - return stillValid(ContainerLevelAccess.create(this.level, this.be.getBlockPos()), player, ModBlocks.TRADING_STATION.get()); + return AbstractContainerMenu.stillValid( + ContainerLevelAccess.create(this.level, this.be.getBlockPos()), player, ModBlocks.TRADING_STATION.get()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/TranscendenceGrindstoneMenu.java b/src/main/java/dev/dubhe/anvilcraft/inventory/TranscendenceGrindstoneMenu.java index c1540a76cb..3a7c09fc10 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/TranscendenceGrindstoneMenu.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/TranscendenceGrindstoneMenu.java @@ -173,15 +173,15 @@ public void onTake(Player player, ItemStack stack) { private static boolean isValidSource(ItemStack stack) { return stack.isDamageableItem() || stack.getOrDefault(DataComponents.REPAIR_COST, 0) > 0 - || hasAnyEnchantments(stack); + || TranscendenceGrindstoneMenu.hasAnyEnchantments(stack); } private boolean isValidModifier(ItemStack stack) { - return isGold(stack) + return TranscendenceGrindstoneMenu.isGold(stack) || stack.is(Items.BOOK) || this.isSmallTank(stack) || this.isLargeTank(stack) - || isTransferTarget(stack); + || TranscendenceGrindstoneMenu.isTransferTarget(stack); } private static boolean isTransferTarget(ItemStack stack) { @@ -190,7 +190,7 @@ private static boolean isTransferTarget(ItemStack stack) { || stack.is(ItemTags.DURABILITY_ENCHANTABLE) || stack.is(ItemTags.MINING_ENCHANTABLE) || stack.is(ItemTags.WEAPON_ENCHANTABLE) - || hasAnyEnchantments(stack); + || TranscendenceGrindstoneMenu.hasAnyEnchantments(stack); } private static boolean isGold(ItemStack stack) { @@ -206,7 +206,7 @@ private boolean isLargeTank(ItemStack stack) { } private static boolean hasAnyEnchantments(ItemStack stack) { - for (DataComponentType type : getEnchantmentTypes()) { + for (DataComponentType type : TranscendenceGrindstoneMenu.getEnchantmentTypes()) { if (!stack.getOrDefault(type, ItemEnchantments.EMPTY).isEmpty()) return true; } return false; @@ -224,11 +224,11 @@ private static List> getEnchantmentTypes() { private Mode getMode() { ItemStack stack = this.modifier.getItem(0); if (stack.isEmpty()) return Mode.DISENCHANT; - if (isGold(stack)) return Mode.GOLD; + if (TranscendenceGrindstoneMenu.isGold(stack)) return Mode.GOLD; if (stack.is(Items.BOOK)) return Mode.BOOK; if (this.isSmallTank(stack)) return Mode.SMALL_TANK; if (this.isLargeTank(stack)) return Mode.LARGE_TANK; - if (isTransferTarget(stack)) return Mode.ITEM; + if (TranscendenceGrindstoneMenu.isTransferTarget(stack)) return Mode.ITEM; return Mode.UNSUPPORTED; } @@ -236,6 +236,7 @@ public boolean isGoldMode() { return this.getMode() == Mode.GOLD; } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isTransferMode() { Mode mode = this.getMode(); return mode == Mode.BOOK || mode == Mode.ITEM; @@ -283,12 +284,12 @@ private ItemStack createGoldResult() { this.removedCurseCount = 0; if (goldStack.is(Items.GOLD_INGOT)) { int remainingGold = goldStack.getCount() - this.usedGold; - int removableCurses = Math.min(this.totalCurseCount, remainingGold / GOLD_PER_CURSE); + int removableCurses = Math.min(this.totalCurseCount, remainingGold / TranscendenceGrindstoneMenu.GOLD_PER_CURSE); this.removedCurseCount = this.removeCurses(output, removableCurses); - this.usedGold += this.removedCurseCount * GOLD_PER_CURSE; + this.usedGold += this.removedCurseCount * TranscendenceGrindstoneMenu.GOLD_PER_CURSE; } - if (output.is(Items.ENCHANTED_BOOK) && !hasAnyEnchantments(output)) { + if (output.is(Items.ENCHANTED_BOOK) && !TranscendenceGrindstoneMenu.hasAnyEnchantments(output)) { return output.transmuteCopy(Items.BOOK); } return output; @@ -296,7 +297,7 @@ private ItemStack createGoldResult() { private int countCurses(ItemStack stack) { int count = 0; - for (DataComponentType type : getEnchantmentTypes()) { + for (DataComponentType type : TranscendenceGrindstoneMenu.getEnchantmentTypes()) { for (Holder enchantment : stack.getOrDefault(type, ItemEnchantments.EMPTY).keySet()) { if (enchantment.is(EnchantmentTags.CURSE)) count++; } @@ -306,7 +307,7 @@ private int countCurses(ItemStack stack) { private int removeCurses(ItemStack stack, int amount) { int removed = 0; - for (DataComponentType type : getEnchantmentTypes()) { + for (DataComponentType type : TranscendenceGrindstoneMenu.getEnchantmentTypes()) { if (removed >= amount) break; ItemEnchantments current = stack.getOrDefault(type, ItemEnchantments.EMPTY); ItemEnchantments.Mutable mutable = new ItemEnchantments.Mutable(current); @@ -358,7 +359,7 @@ private ItemStack createTankResult() { long totalAmount = 0; List fluids = new ArrayList<>(); for (EnchantmentData data : selected) { - long amount = getLiquidAmount(data.level()); + long amount = TranscendenceGrindstoneMenu.getLiquidAmount(data.level()); if (amount <= 0 || amount > capacity - totalAmount) return ItemStack.EMPTY; FluidStack fluid = new FluidStack(ModFluids.LIQUID_ENCHANTMENT.get(), (int) amount); @@ -392,7 +393,7 @@ private ItemStack createSourceWithoutSelected() { for (Map.Entry, ItemEnchantments.Mutable> entry : mutableByType.entrySet()) { output.set(entry.getKey(), entry.getValue().toImmutable()); } - if (output.is(Items.ENCHANTED_BOOK) && !hasAnyEnchantments(output)) { + if (output.is(Items.ENCHANTED_BOOK) && !TranscendenceGrindstoneMenu.hasAnyEnchantments(output)) { return output.transmuteCopy(Items.BOOK); } return output; @@ -409,7 +410,7 @@ private List getSelectedEnchantments() { private void refreshEnchantments() { ItemStack input = this.source.getItem(0); this.enchantments.clear(); - for (DataComponentType type : getEnchantmentTypes()) { + for (DataComponentType type : TranscendenceGrindstoneMenu.getEnchantmentTypes()) { for (var entry : input.getOrDefault(type, ItemEnchantments.EMPTY).entrySet()) { Holder enchantment = entry.getKey(); if (enchantment.is(EnchantmentTags.CURSE)) continue; @@ -547,17 +548,23 @@ public ItemStack quickMoveStack(Player player, int index) { ItemStack original = clicked.copy(); if (index == 2) { ItemStack moving = clicked.copy(); - if (!this.moveItemStackTo(moving, PLAYER_INVENTORY_SLOT_START, PLAYER_INVENTORY_SLOT_END, true)) { + if (!this.moveItemStackTo( + moving, TranscendenceGrindstoneMenu.PLAYER_INVENTORY_SLOT_START, TranscendenceGrindstoneMenu.PLAYER_INVENTORY_SLOT_END, + true + )) { return ItemStack.EMPTY; } slot.onTake(player, clicked); return original; } - if (index < PLAYER_INVENTORY_SLOT_START) { - if (!this.moveItemStackTo(clicked, PLAYER_INVENTORY_SLOT_START, PLAYER_INVENTORY_SLOT_END, false)) { + if (index < TranscendenceGrindstoneMenu.PLAYER_INVENTORY_SLOT_START) { + if (!this.moveItemStackTo( + clicked, TranscendenceGrindstoneMenu.PLAYER_INVENTORY_SLOT_START, TranscendenceGrindstoneMenu.PLAYER_INVENTORY_SLOT_END, + false + )) { return ItemStack.EMPTY; } - } else if (isValidSource(clicked) && !this.getSlot(0).hasItem()) { + } else if (TranscendenceGrindstoneMenu.isValidSource(clicked) && !this.getSlot(0).hasItem()) { if (!this.moveItemStackTo(clicked, 0, 1, false)) return ItemStack.EMPTY; } else if (this.isValidModifier(clicked) && !this.getSlot(1).hasItem()) { if (!this.moveItemStackTo(clicked, 1, 2, false)) return ItemStack.EMPTY; @@ -575,7 +582,7 @@ public ItemStack quickMoveStack(Player player, int index) { @Override public boolean stillValid(Player player) { - return stillValid(this.access, player, ModBlocks.TRANSCENDENCE_GRINDSTONE.get()); + return AbstractContainerMenu.stillValid(this.access, player, ModBlocks.TRANSCENDENCE_GRINDSTONE.get()); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/component/StructureDiskOnlySlot.java b/src/main/java/dev/dubhe/anvilcraft/inventory/component/StructureDiskOnlySlot.java index f704ad0399..962b00ad1d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/component/StructureDiskOnlySlot.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/component/StructureDiskOnlySlot.java @@ -3,6 +3,8 @@ import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.init.item.ModItems; import dev.dubhe.anvilcraft.item.property.component.StructureDiskData; +import net.minecraft.world.Container; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import org.jspecify.annotations.Nullable; @@ -28,7 +30,7 @@ public class StructureDiskOnlySlot extends Slot { * @param enforceSizeLimit 是否强制执行 5x5x5 大小限制(Smart Block Placer 需要,Structure Scanner 不需要) */ public StructureDiskOnlySlot( - net.minecraft.world.Container container, int slot, int x, int y, + Container container, int slot, int x, int y, boolean enforceSizeLimit ) { this(container, slot, x, y, enforceSizeLimit, null); @@ -38,7 +40,7 @@ public StructureDiskOnlySlot( * 创建结构磁盘槽位(带提取条件) */ public StructureDiskOnlySlot( - net.minecraft.world.Container container, int slot, int x, int y, + Container container, int slot, int x, int y, @Nullable BooleanSupplier canExtractCondition ) { this(container, slot, x, y, false, canExtractCondition); @@ -48,7 +50,7 @@ public StructureDiskOnlySlot( * 创建结构磁盘槽位(完整参数) */ public StructureDiskOnlySlot( - net.minecraft.world.Container container, int slot, int x, int y, + Container container, int slot, int x, int y, boolean enforceSizeLimit, @Nullable BooleanSupplier canExtractCondition ) { @@ -84,7 +86,7 @@ public boolean mayPlace(ItemStack stack) { } @Override - public boolean mayPickup(net.minecraft.world.entity.player.Player playerIn) { + public boolean mayPickup(Player playerIn) { // 检查提取条件(如果书槽位有书,则不允许取出) return this.canExtractCondition == null || this.canExtractCondition.getAsBoolean(); } diff --git a/src/main/java/dev/dubhe/anvilcraft/inventory/tooltip/CreativeContainerTooltip.java b/src/main/java/dev/dubhe/anvilcraft/inventory/tooltip/CreativeContainerTooltip.java index d679711529..6cdfcf7a42 100644 --- a/src/main/java/dev/dubhe/anvilcraft/inventory/tooltip/CreativeContainerTooltip.java +++ b/src/main/java/dev/dubhe/anvilcraft/inventory/tooltip/CreativeContainerTooltip.java @@ -11,11 +11,11 @@ public record CreativeContainerTooltip(List entries) implements TooltipCo public record Entry(ItemStack item, FluidStack fluid, Component text) { public static Entry item(ItemStack item) { ItemStack icon = item.copyWithCount(1); - return new Entry(icon, FluidStack.EMPTY, contentText(item.getHoverName())); + return new Entry(icon, FluidStack.EMPTY, Entry.contentText(item.getHoverName())); } public static Entry fluid(FluidStack fluid) { - return new Entry(ItemStack.EMPTY, fluid.copy(), contentText(fluid.getHoverName())); + return new Entry(ItemStack.EMPTY, fluid.copy(), Entry.contentText(fluid.getHoverName())); } public boolean isFluid() { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/FluidTankMinecartItem.java b/src/main/java/dev/dubhe/anvilcraft/item/FluidTankMinecartItem.java index df165d98d8..8473a448a9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/FluidTankMinecartItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/FluidTankMinecartItem.java @@ -1,6 +1,7 @@ package dev.dubhe.anvilcraft.item; import dev.dubhe.anvilcraft.api.tooltip.FluidTankItemTooltip; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.entity.FluidTankMinecartEntity; import dev.dubhe.anvilcraft.init.entity.ModEntities; import net.minecraft.core.BlockPos; @@ -31,21 +32,20 @@ import java.util.function.Consumer; /// 放置与发射储罐矿车的物品 -public class FluidTankMinecartItem extends Item { +public class FluidTankMinecartItem extends Item implements IItemTooltipProvider { public FluidTankMinecartItem(Properties properties) { super(properties.stacksTo(1)); DispenserBlock.registerBehavior(this, new DispenseBehavior()); } @Override - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); FluidTankItemTooltip.appendFixedTank( stack, context, @@ -85,8 +85,8 @@ public InteractionResult useOn(UseOnContext context) { ItemStack stack = context.getItemInHand(); if (level instanceof ServerLevel serverLevel) { - double yoffset = railShape(state, serverLevel, pos).isSlope() ? 0.5D : 0.0D; - FluidTankMinecartEntity cart = createMinecart( + double yoffset = FluidTankMinecartItem.railShape(state, serverLevel, pos).isSlope() ? 0.5D : 0.0D; + FluidTankMinecartEntity cart = FluidTankMinecartItem.createMinecart( serverLevel, pos.getX() + 0.5D, pos.getY() + 0.0625D + yoffset, @@ -127,17 +127,17 @@ public ItemStack execute(BlockSource source, ItemStack stack) { BlockState state = level.getBlockState(pos); double yoffset; if (state.is(BlockTags.RAILS)) { - yoffset = railShape(state, level, pos).isSlope() ? 0.6D : 0.1D; + yoffset = FluidTankMinecartItem.railShape(state, level, pos).isSlope() ? 0.6D : 0.1D; } else { if (!state.isAir()) return this.fallback.dispense(source, stack); BlockState below = level.getBlockState(pos.below()); if (!below.is(BlockTags.RAILS)) return this.fallback.dispense(source, stack); - yoffset = direction != Direction.DOWN && railShape(below, level, pos.below()).isSlope() + yoffset = direction != Direction.DOWN && FluidTankMinecartItem.railShape(below, level, pos.below()).isSlope() ? -0.4D : -0.9D; } - FluidTankMinecartEntity cart = createMinecart(level, x, y + yoffset, z, stack, null); + FluidTankMinecartEntity cart = FluidTankMinecartItem.createMinecart(level, x, y + yoffset, z, stack, null); if (cart == null) return stack; level.addFreshEntity(cart); stack.shrink(1); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/SapphireItem.java b/src/main/java/dev/dubhe/anvilcraft/item/SapphireItem.java index 84f181bae5..440d31964b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/SapphireItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/SapphireItem.java @@ -9,7 +9,6 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; -import net.minecraft.tags.BlockTags; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; diff --git a/src/main/java/dev/dubhe/anvilcraft/item/StructureDiskItem.java b/src/main/java/dev/dubhe/anvilcraft/item/StructureDiskItem.java index 5b022a3eb4..03bb0860e7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/StructureDiskItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/StructureDiskItem.java @@ -1,10 +1,11 @@ package dev.dubhe.anvilcraft.item; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.item.property.component.StructureDiskData; +import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.world.item.Item; -import net.minecraft.world.item.Item.TooltipContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.component.TooltipDisplay; @@ -15,23 +16,20 @@ * 结构磁盘物品 * 在tooltip中显示保存的结构名称 */ -public class StructureDiskItem extends Item { +public class StructureDiskItem extends Item implements IItemTooltipProvider { public StructureDiskItem(Properties properties) { super(properties); } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); - // 从 NBT 中读取结构信息并显示在 tooltip 中 StructureDiskData structureDiskData = stack.get(ModComponents.STRUCTURE_DISK_DATA); if (structureDiskData != null) { @@ -45,10 +43,10 @@ public void appendHoverText( // 检查结构是否超过5x5x5 if (sizeX <= 5 && sizeY <= 5 && sizeZ <= 5) { builder.accept(Component.translatable("item.anvilcraft.structure_disk.fit_placer") - .withStyle(net.minecraft.ChatFormatting.GREEN)); + .withStyle(ChatFormatting.GREEN)); } else { builder.accept(Component.translatable("item.anvilcraft.structure_disk.too_large_for_placer") - .withStyle(net.minecraft.ChatFormatting.RED)); + .withStyle(ChatFormatting.RED)); } } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/amulet/AmuletBoxItem.java b/src/main/java/dev/dubhe/anvilcraft/item/amulet/AmuletBoxItem.java index 01f60af475..8df122fe76 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/amulet/AmuletBoxItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/amulet/AmuletBoxItem.java @@ -44,11 +44,11 @@ public boolean overrideStackedOnOther(ItemStack itemStack, Slot slot, ClickActio ItemStack popped = mutable.pop(); if (popped.isEmpty()) return false; slot.set(popped); - playRemoveOneSound(player); + AmuletBoxItem.playRemoveOneSound(player); } else { Optional remain = mutable.tryInsert(other); if (remain.isEmpty()) return false; - playInsertSound(player); + AmuletBoxItem.playInsertSound(player); slot.set(remain.get()); } itemStack.set(ModComponents.BOX_CONTENTS, mutable.immutable()); @@ -70,12 +70,12 @@ public boolean overrideOtherStackedOnMe( ItemStack itemStack = contents.pop(); if (itemStack.isEmpty()) return false; slotAccess.set(itemStack); - playRemoveOneSound(player); + AmuletBoxItem.playRemoveOneSound(player); this.broadcastChangesOnContainerMenu(player); } else { Optional remain = contents.tryInsert(other); if (remain.isEmpty()) return false; - playInsertSound(player); + AmuletBoxItem.playInsertSound(player); this.broadcastChangesOnContainerMenu(player); slotAccess.set(remain.get()); } @@ -98,7 +98,7 @@ public InteractionResult use(Level level, Player player, InteractionHand usedHan if (remain.isEmpty()) continue; inventory.setItem(i, remain.get()); } - playInsertSound(player); + AmuletBoxItem.playInsertSound(player); box.set(ModComponents.BOX_CONTENTS, mutable.immutable()); } else if (AnvilCraft.CONFIG.amuletBoxTakeOutAllTotem) { boolean dropped = false; @@ -109,7 +109,7 @@ public InteractionResult use(Level level, Player player, InteractionHand usedHan dropped = true; } if (dropped) { - playDropContentsSound(level, player); + AmuletBoxItem.playDropContentsSound(level, player); } box.set(ModComponents.BOX_CONTENTS, mutable.immutable()); } @@ -134,7 +134,7 @@ public int getBarWidth(ItemStack itemStack) { @Override public int getBarColor(ItemStack itemStack) { BoxContents contents = itemStack.getOrDefault(ModComponents.BOX_CONTENTS, BoxContents.EMPTY); - return ColorUtil.lerpColor(contents.usage() / (float) BoxContents.CAPACITY, BAR_COLOR, FULL_BAR_COLOR); + return ColorUtil.lerpColor(contents.usage() / (float) BoxContents.CAPACITY, AmuletBoxItem.BAR_COLOR, AmuletBoxItem.FULL_BAR_COLOR); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/item/armor/IonoCraftBackpackItem.java b/src/main/java/dev/dubhe/anvilcraft/item/armor/IonoCraftBackpackItem.java index 5e80ab4e16..229dfb99a8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/armor/IonoCraftBackpackItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/armor/IonoCraftBackpackItem.java @@ -4,6 +4,7 @@ import dev.dubhe.anvilcraft.api.power.DynamicPowerComponent; import dev.dubhe.anvilcraft.api.power.IDynamicPowerComponentHolder; import dev.dubhe.anvilcraft.api.power.PowerGrid; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.init.item.ModItemTags; import dev.dubhe.anvilcraft.init.item.ModItems; @@ -38,7 +39,7 @@ import java.util.function.Consumer; import java.util.function.Function; -public class IonoCraftBackpackItem extends Item implements IInventoryCarriedAware { +public class IonoCraftBackpackItem extends Item implements IInventoryCarriedAware, IItemTooltipProvider { public static final int MAX_ENERGY = 120000000; public static final int FLIGHT_CONSUMPTION = 5000; @@ -52,7 +53,7 @@ public class IonoCraftBackpackItem extends Item implements IInventoryCarriedAwar public static final Identifier CREATIVE_FLIGHT_ID = AnvilCraft.of("creative_flight"); public static final AttributeModifier CREATIVE_FLIGHT = new AttributeModifier( - CREATIVE_FLIGHT_ID, + IonoCraftBackpackItem.CREATIVE_FLIGHT_ID, 1, AttributeModifier.Operation.ADD_VALUE ); @@ -63,16 +64,16 @@ public class IonoCraftBackpackItem extends Item implements IInventoryCarriedAwar /** 玩家退出时清理飞行追踪器,防止内存泄漏 */ public static void onPlayerLoggedOut(UUID uuid) { - FLYING_TRACKER.remove(uuid); + IonoCraftBackpackItem.FLYING_TRACKER.remove(uuid); } public IonoCraftBackpackItem(Properties properties) { super( properties .repairable(ModItemTags.TIN_INGOTS) - .component(ModComponents.STORED_ENERGY, new StoredEnergy(MAX_ENERGY)) + .component(ModComponents.STORED_ENERGY, new StoredEnergy(IonoCraftBackpackItem.MAX_ENERGY)) ); - addStackProvider(player -> player.getItemBySlot(EquipmentSlot.CHEST)); + IonoCraftBackpackItem.addStackProvider(player -> player.getItemBySlot(EquipmentSlot.CHEST)); } @Override @@ -85,12 +86,15 @@ public static int getEnergyStored(ItemStack stack) { } public static void setEnergyStored(ItemStack stack, int energy) { - stack.set(ModComponents.STORED_ENERGY, new StoredEnergy(Math.clamp(energy, 0, MAX_ENERGY))); + stack.set( + ModComponents.STORED_ENERGY, + new StoredEnergy(Math.clamp(energy, 0, IonoCraftBackpackItem.MAX_ENERGY)) + ); } public static void addEnergy(ItemStack stack, int amount) { - int current = getEnergyStored(stack); - setEnergyStored(stack, current + amount); + int current = IonoCraftBackpackItem.getEnergyStored(stack); + IonoCraftBackpackItem.setEnergyStored(stack, current + amount); } public static boolean canModify(ItemStack stack, DynamicPowerComponent component) { @@ -100,11 +104,11 @@ public static boolean canModify(ItemStack stack, DynamicPowerComponent component } public static void addStackProvider(Function provider) { - STACK_PROVIDERS.add(provider); + IonoCraftBackpackItem.STACK_PROVIDERS.add(provider); } public static ItemStack getByPlayer(Player player) { - for (Function provider : STACK_PROVIDERS) { + for (Function provider : IonoCraftBackpackItem.STACK_PROVIDERS) { ItemStack stack = provider.apply(player); if (stack.is(ModItems.IONOCRAFT_BACKPACK)) { return stack; @@ -120,21 +124,22 @@ public static void refreshPower(ServerPlayer player) { if (instance == null) return; DynamicPowerComponent powerComponent = holder.anvilcraft$getPowerComponent(); - ItemStack equipped = getByPlayer(player); + ItemStack equipped = IonoCraftBackpackItem.getByPlayer(player); if (equipped.isEmpty()) { - powerComponent.getPowerConsumptions().remove(CONSUMPTION_64); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_128); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_256); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_512); - if (instance.hasModifier(CREATIVE_FLIGHT_ID)) { - instance.removeModifier(CREATIVE_FLIGHT); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_64); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_128); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_256); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_512); + if (instance.hasModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT_ID)) { + instance.removeModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT); } return; - } else if (getEnergyStored(equipped) >= MAX_ENERGY && !player.getAbilities().flying) { - powerComponent.getPowerConsumptions().remove(CONSUMPTION_64); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_128); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_256); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_512); + } else if (IonoCraftBackpackItem.getEnergyStored(equipped) >= IonoCraftBackpackItem.MAX_ENERGY + && !player.getAbilities().flying) { + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_64); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_128); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_256); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_512); return; } @@ -142,10 +147,14 @@ public static void refreshPower(ServerPlayer player) { PowerGrid powerGrid = powerComponent.getPowerGrid(); if (powerGrid.isWorking()) { - boolean hasConsumption = powerComponent.getPowerConsumptions().contains(CONSUMPTION_64) - || powerComponent.getPowerConsumptions().contains(CONSUMPTION_128) - || powerComponent.getPowerConsumptions().contains(CONSUMPTION_256) - || powerComponent.getPowerConsumptions().contains(CONSUMPTION_512); + boolean hasConsumption = powerComponent.getPowerConsumptions() + .contains(IonoCraftBackpackItem.CONSUMPTION_64) + || powerComponent.getPowerConsumptions() + .contains(IonoCraftBackpackItem.CONSUMPTION_128) + || powerComponent.getPowerConsumptions() + .contains(IonoCraftBackpackItem.CONSUMPTION_256) + || powerComponent.getPowerConsumptions() + .contains(IonoCraftBackpackItem.CONSUMPTION_512); if (!hasConsumption) { AtomicInteger playerCount = new AtomicInteger(0); @@ -156,35 +165,35 @@ public static void refreshPower(ServerPlayer player) { }); int remaining = powerGrid.getRemaining() / playerCount.get(); if (remaining >= 512) { - powerComponent.getPowerConsumptions().add(CONSUMPTION_512); + powerComponent.getPowerConsumptions().add(IonoCraftBackpackItem.CONSUMPTION_512); } else if (remaining >= 256) { - powerComponent.getPowerConsumptions().add(CONSUMPTION_256); + powerComponent.getPowerConsumptions().add(IonoCraftBackpackItem.CONSUMPTION_256); } else if (remaining >= 128) { - powerComponent.getPowerConsumptions().add(CONSUMPTION_128); + powerComponent.getPowerConsumptions().add(IonoCraftBackpackItem.CONSUMPTION_128); } else if (remaining >= 64) { - powerComponent.getPowerConsumptions().add(CONSUMPTION_64); + powerComponent.getPowerConsumptions().add(IonoCraftBackpackItem.CONSUMPTION_64); } } } else { - powerComponent.getPowerConsumptions().remove(CONSUMPTION_64); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_128); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_256); - powerComponent.getPowerConsumptions().remove(CONSUMPTION_512); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_64); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_128); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_256); + powerComponent.getPowerConsumptions().remove(IonoCraftBackpackItem.CONSUMPTION_512); } } public static void refreshFlight(ServerPlayer player) { - ItemStack equipped = getByPlayer(player); + ItemStack equipped = IonoCraftBackpackItem.getByPlayer(player); AttributeInstance instance = player.getAttributes().getInstance(NeoForgeMod.CREATIVE_FLIGHT); if (instance == null) return; - int energy = getEnergyStored(equipped); + int energy = IonoCraftBackpackItem.getEnergyStored(equipped); if (energy > 0) { - if (!instance.hasModifier(CREATIVE_FLIGHT_ID)) { - instance.addTransientModifier(CREATIVE_FLIGHT); + if (!instance.hasModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT_ID)) { + instance.addTransientModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT); } } else { - if (instance.hasModifier(CREATIVE_FLIGHT_ID)) { - instance.removeModifier(CREATIVE_FLIGHT); + if (instance.hasModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT_ID)) { + instance.removeModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT); } } } @@ -192,17 +201,17 @@ public static void refreshFlight(ServerPlayer player) { public static void playerTick(ServerPlayer player) { final IDynamicPowerComponentHolder holder = IDynamicPowerComponentHolder.of(player); - refreshPower(player); - refreshFlight(player); + IonoCraftBackpackItem.refreshPower(player); + IonoCraftBackpackItem.refreshFlight(player); - ItemStack backpack = getByPlayer(player); + ItemStack backpack = IonoCraftBackpackItem.getByPlayer(player); boolean nowFlying = !backpack.isEmpty() && player.getAbilities().flying && !player.isCreative() && !player.isSpectator(); // 飞行状态变化时同步到周边客户端 - Boolean prevFlying = FLYING_TRACKER.put(player.getUUID(), nowFlying); + Boolean prevFlying = IonoCraftBackpackItem.FLYING_TRACKER.put(player.getUUID(), nowFlying); if (prevFlying == null || prevFlying != nowFlying) { PacketDistributor.sendToPlayersTrackingEntity( player, @@ -213,28 +222,31 @@ public static void playerTick(ServerPlayer player) { if (backpack.isEmpty()) return; if (player.getAbilities().flying && !player.isCreative() && !player.isSpectator()) { - int energy = getEnergyStored(backpack); + int energy = IonoCraftBackpackItem.getEnergyStored(backpack); if (energy > 0) { - setEnergyStored(backpack, energy - FLIGHT_CONSUMPTION); + IonoCraftBackpackItem.setEnergyStored( + backpack, + energy - IonoCraftBackpackItem.FLIGHT_CONSUMPTION + ); } else { player.getAbilities().flying = false; player.onUpdateAbilities(); } } - capacitorTick(holder, backpack); + IonoCraftBackpackItem.capacitorTick(holder, backpack); } private static void capacitorTick(IDynamicPowerComponentHolder holder, ItemStack backpack) { if (!(holder instanceof ServerPlayer player)) return; - int energy = getEnergyStored(backpack); - if (energy >= MAX_ENERGY) return; // 能量已满,不消耗电容器 + int energy = IonoCraftBackpackItem.getEnergyStored(backpack); + if (energy >= IonoCraftBackpackItem.MAX_ENERGY) return; // 能量已满,不消耗电容器 Inventory inventory = player.getInventory(); int capacitorSlot = inventory.findSlotMatchingItem(ModItems.CAPACITOR.asStack()); if (capacitorSlot >= 0) { inventory.removeItem(capacitorSlot, 1); inventory.placeItemBackInInventory(ModItems.CAPACITOR_EMPTY.asStack()); - addEnergy(backpack, 8_000_000); + IonoCraftBackpackItem.addEnergy(backpack, 8_000_000); return; } @@ -242,15 +254,15 @@ private static void capacitorTick(IDynamicPowerComponentHolder holder, ItemStack if (superSlot >= 0) { inventory.removeItem(superSlot, 1); inventory.placeItemBackInInventory(ModItems.SUPER_CAPACITOR_EMPTY.asStack()); - addEnergy(backpack, 160_000_000); + IonoCraftBackpackItem.addEnergy(backpack, 160_000_000); } } @Override public void onCarriedUpdate(HashedStack stack, ServerPlayer serverPlayer) { AttributeInstance instance = serverPlayer.getAttributes().getInstance(NeoForgeMod.CREATIVE_FLIGHT); - if (instance != null && instance.hasModifier(CREATIVE_FLIGHT_ID)) { - instance.removeModifier(CREATIVE_FLIGHT); + if (instance != null && instance.hasModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT_ID)) { + instance.removeModifier(IonoCraftBackpackItem.CREATIVE_FLIGHT); } } @@ -261,22 +273,21 @@ public boolean isBarVisible(ItemStack stack) { @Override public int getBarWidth(ItemStack stack) { - int energy = getEnergyStored(stack); - return Math.round(energy * 13.0f / MAX_ENERGY); + int energy = IonoCraftBackpackItem.getEnergyStored(stack); + return Math.round(energy * 13.0f / IonoCraftBackpackItem.MAX_ENERGY); } @Override public int getBarColor(ItemStack stack) { - float ratio = (float) getEnergyStored(stack) / MAX_ENERGY; + float ratio = (float) IonoCraftBackpackItem.getEnergyStored(stack) / IonoCraftBackpackItem.MAX_ENERGY; return ColorUtil.lerpColor(ratio, 0x7087FFFF, 0xFF5454FF); } @Override - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); - int energy = getEnergyStored(stack); - int totalSeconds = energy / FLIGHT_CONSUMPTION / 20; + int energy = IonoCraftBackpackItem.getEnergyStored(stack); + int totalSeconds = energy / IonoCraftBackpackItem.FLIGHT_CONSUMPTION / 20; int minutes = totalSeconds / 60; int seconds = totalSeconds % 60; builder.accept(Component.translatable( diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/CreativeContainerBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/CreativeContainerBlockItem.java index eb73ae80d0..367bdf4416 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/CreativeContainerBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/CreativeContainerBlockItem.java @@ -22,8 +22,8 @@ public CreativeContainerBlockItem(Block block, Properties properties) { @Override public Optional getTooltipImage(ItemStack stack) { List entries = new ArrayList<>(); - appendStoredItemTooltip(stack, entries); - appendStoredFluidsTooltip(stack, entries); + CreativeContainerBlockItem.appendStoredItemTooltip(stack, entries); + CreativeContainerBlockItem.appendStoredFluidsTooltip(stack, entries); if (entries.isEmpty()) return super.getTooltipImage(stack); return Optional.of(new CreativeContainerTooltip(entries)); } @@ -40,7 +40,7 @@ private static void appendStoredFluidsTooltip(ItemStack stack, List fluids = storedFluids.fluids(); for (FluidStack fluid : fluids) { if (fluid.isEmpty()) continue; - if (containsSameFluidBefore(fluids, fluid)) continue; + if (CreativeContainerBlockItem.containsSameFluidBefore(fluids, fluid)) continue; entries.add(CreativeContainerTooltip.Entry.fluid(fluid)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/FluidTankBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/FluidTankBlockItem.java index cdb3c2f5ba..f215718448 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/FluidTankBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/FluidTankBlockItem.java @@ -1,6 +1,7 @@ package dev.dubhe.anvilcraft.item.block; import dev.dubhe.anvilcraft.api.tooltip.FluidTankItemTooltip; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.block.entity.FluidTankBlockEntity; import net.minecraft.network.chat.Component; import net.minecraft.world.item.BlockItem; @@ -13,20 +14,19 @@ import java.util.function.Consumer; /// 流体储罐的物品形态,额外显示罐内流体 -public class FluidTankBlockItem extends BlockItem { +public class FluidTankBlockItem extends BlockItem implements IItemTooltipProvider { public FluidTankBlockItem(Block block, Properties properties) { super(block, properties); } @Override - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, Item.TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); FluidTankItemTooltip.appendExpandableTank( stack, context, diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/HasMobBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/HasMobBlockItem.java index f309f1ab4f..38a574bbb1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/HasMobBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/HasMobBlockItem.java @@ -1,6 +1,7 @@ package dev.dubhe.anvilcraft.item.block; import dev.dubhe.anvilcraft.AnvilCraft; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.block.entity.HasMobBlockEntity; import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.item.property.component.SavedEntity; @@ -32,21 +33,19 @@ import java.util.Optional; import java.util.function.Consumer; -public class HasMobBlockItem extends BlockItem { +public class HasMobBlockItem extends BlockItem implements IItemTooltipProvider { public HasMobBlockItem(Block block, Properties properties) { super(block, properties); } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); if (!HasMobBlockItem.hasMob(stack)) return; Optional.ofNullable(context.level()).ifPresent(level -> { SavedEntity savedEntity = stack.get(ModComponents.SAVED_ENTITY); @@ -68,10 +67,10 @@ public void appendHoverText( @Override protected boolean updateCustomBlockEntityTag(BlockPos pos, Level level, @Nullable Player player, ItemStack stack, BlockState state) { - if (hasMob(stack)) { + if (HasMobBlockItem.hasMob(stack)) { BlockEntity be = level.getBlockEntity(pos); if (be instanceof HasMobBlockEntity hmbe) { - hmbe.setEntity(getMobFromItem(level, stack)); + hmbe.setEntity(HasMobBlockItem.getMobFromItem(level, stack)); } } return super.updateCustomBlockEntityTag(pos, level, player, stack, state); @@ -83,7 +82,7 @@ public static boolean hasMob(ItemStack stack) { /// 获取物品中的实体 public static @Nullable Entity getMobFromItem(Level level, ItemStack stack) { - if (!hasMob(stack)) return null; + if (!HasMobBlockItem.hasMob(stack)) return null; SavedEntity savedEntity = stack.get(ModComponents.SAVED_ENTITY); // make idea happy if (savedEntity == null) return null; @@ -126,7 +125,7 @@ public static ItemStack saveMobInItem(Level level, Mob entity, @Nullable Player } public static ItemStack saveMobInItem(Level level, Mob entity, ItemStack stack) { - return saveMobInItem(level, entity, null, stack); + return HasMobBlockItem.saveMobInItem(level, entity, null, stack); } public static boolean canMobBeSaved(Mob entity, @Nullable Player player, @Nullable ItemStack stack) { @@ -138,6 +137,6 @@ public static boolean canMobBeSaved(Mob entity, @Nullable Player player, @Nullab } public static boolean canMobBeSaved(Mob entity) { - return canMobBeSaved(entity, null, null); + return HasMobBlockItem.canMobBeSaved(entity, null, null); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/HeliostatsItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/HeliostatsItem.java index 5efd555235..a9b013deca 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/HeliostatsItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/HeliostatsItem.java @@ -1,5 +1,6 @@ package dev.dubhe.anvilcraft.item.block; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.block.entity.HeliostatsBlockEntity; import dev.dubhe.anvilcraft.block.heatable.HeatableBlock; import dev.dubhe.anvilcraft.init.block.ModBlocks; @@ -30,7 +31,7 @@ import java.util.function.Consumer; -public class HeliostatsItem extends BlockItem { +public class HeliostatsItem extends BlockItem implements IItemTooltipProvider { public HeliostatsItem(Block block, Properties properties) { super(block, properties); } @@ -58,7 +59,7 @@ public boolean supportsEnchantment(ItemStack stack, Holder enchantm @Override public boolean isFoil(ItemStack stack) { - return hasDataStored(stack); + return HeliostatsItem.hasDataStored(stack); } @Override @@ -69,7 +70,7 @@ protected boolean updateCustomBlockEntityTag( ItemStack stack, BlockState state) { if (level.isClientSide()) return false; - if (!hasDataStored(stack)) { + if (!HeliostatsItem.hasDataStored(stack)) { if (player != null) { player.sendOverlayMessage( Component.translatable("block.anvilcraft.heliostats.placement_no_pos") @@ -79,7 +80,7 @@ protected boolean updateCustomBlockEntityTag( return false; } - BlockPos irritatePos = getData(stack); + BlockPos irritatePos = HeliostatsItem.getData(stack); BlockEntity entity = level.getBlockEntity(pos); if (entity instanceof HeliostatsBlockEntity e) { if (!e.setIrritatePos(irritatePos) && player != null) { @@ -94,16 +95,15 @@ protected boolean updateCustomBlockEntityTag( } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - if (hasDataStored(stack)) { - BlockPos pos = getData(stack); + if (HeliostatsItem.hasDataStored(stack)) { + BlockPos pos = HeliostatsItem.getData(stack); builder.accept( Component.translatable("item.anvilcraft.heliostats.pos_set", pos.toShortString()) .withStyle(Style.EMPTY.applyFormat(ChatFormatting.GRAY)) @@ -121,8 +121,8 @@ protected SoundEvent getPlaceSound(BlockState state, Level world, BlockPos pos, public InteractionResult useOn(UseOnContext context) { Level level = context.getLevel(); if (context.getPlayer() != null && context.getPlayer().isShiftKeyDown() - && hasDataStored(context.getItemInHand())) { - deleteData(context.getItemInHand()); + && HeliostatsItem.hasDataStored(context.getItemInHand())) { + HeliostatsItem.deleteData(context.getItemInHand()); return InteractionResult.SUCCESS; } BlockState blockState = level.getBlockState(context.getClickedPos()); @@ -130,7 +130,7 @@ && hasDataStored(context.getItemInHand())) { || blockState.getBlock() instanceof HeatableBlock ) { ItemStack stack = context.getItemInHand(); - if (hasDataStored(stack)) { + if (HeliostatsItem.hasDataStored(stack)) { InteractionResult result = super.useOn(context); if (result != InteractionResult.FAIL) { level.playSound( @@ -156,8 +156,8 @@ public InteractionResult use( Level level, Player player, InteractionHand usedHand) { if (!level.isClientSide() && player.isShiftKeyDown()) { ItemStack itemStack = player.getItemInHand(usedHand); - if (hasDataStored(itemStack)) { - deleteData(itemStack); + if (HeliostatsItem.hasDataStored(itemStack)) { + HeliostatsItem.deleteData(itemStack); } return InteractionResult.SUCCESS; } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/LargeFluidTankBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/LargeFluidTankBlockItem.java index 9b4cf37d33..cb2d6aee14 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/LargeFluidTankBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/LargeFluidTankBlockItem.java @@ -1,6 +1,7 @@ package dev.dubhe.anvilcraft.item.block; import dev.dubhe.anvilcraft.api.tooltip.FluidTankItemTooltip; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.block.container.LargeFluidTankBlock; import dev.dubhe.anvilcraft.block.entity.LargeFluidTankBlockEntity; import dev.dubhe.anvilcraft.block.state.Cube3x3PartHalf; @@ -18,20 +19,19 @@ import java.util.function.Consumer; /// 大型流体储罐的物品形态,额外显示罐内流体 -public class LargeFluidTankBlockItem extends SimpleMultiPartBlockItem { +public class LargeFluidTankBlockItem extends SimpleMultiPartBlockItem implements IItemTooltipProvider { public LargeFluidTankBlockItem(LargeFluidTankBlock block, Properties properties) { super(block, properties); } @Override - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, Item.TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); FluidTankItemTooltip.appendMultiTank( stack, context, diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/MultiphaseMatterBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/MultiphaseMatterBlockItem.java index f62f2992ae..6d68166c61 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/MultiphaseMatterBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/MultiphaseMatterBlockItem.java @@ -24,11 +24,11 @@ public MultiphaseMatterBlockItem(Block block, Properties properties) { @Override public Component getInputTooltip(ItemStack material) { - return MISSING_TOOLTIP; + return MultiphaseMatterBlockItem.MISSING_TOOLTIP; } @Override public List getEmptySlotTextures() { - return EMPTY_SLOT_TEXTURES; + return MultiphaseMatterBlockItem.EMPTY_SLOT_TEXTURES; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/PipeBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/PipeBlockItem.java index 6db531ad93..b2364ea430 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/PipeBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/PipeBlockItem.java @@ -98,16 +98,16 @@ private boolean tryConnectAdjacent(BlockPlaceContext context) { boolean modified = false; Player player = context.getPlayer(); if (targetIsPipe) { - BlockState newState = modifyPipeToConnect(level, targetPos, targetState, clickedFace, placeIsPipe); + BlockState newState = PipeBlockItem.modifyPipeToConnect(level, targetPos, targetState, clickedFace, placeIsPipe); if (newState != null) { - playPlaceSound(level, targetPos, newState, player); + PipeBlockItem.playPlaceSound(level, targetPos, newState, player); modified = true; } } if (placeIsPipe) { - BlockState newState = modifyPipeToConnect(level, placePos, placeState, clickedFace.getOpposite(), targetIsPipe); + BlockState newState = PipeBlockItem.modifyPipeToConnect(level, placePos, placeState, clickedFace.getOpposite(), targetIsPipe); if (newState != null) { - playPlaceSound(level, placePos, newState, player); + PipeBlockItem.playPlaceSound(level, placePos, newState, player); modified = true; } } @@ -128,14 +128,14 @@ private boolean tryConnectAdjacent(BlockPlaceContext context) { */ @Nullable private static BlockState modifyPipeToConnect(Level level, BlockPos pos, BlockState state, Direction toward, boolean towardIsPipe) { - if (hasOpenConnectionToward(state, toward)) { + if (PipeBlockItem.hasOpenConnectionToward(state, toward)) { return null; } if (state.getBlock() instanceof PipeStraightBlock) { - return modifyStraightToConnect(level, pos, state, toward, towardIsPipe); + return PipeBlockItem.modifyStraightToConnect(level, pos, state, toward, towardIsPipe); } else if (state.getBlock() instanceof PipeCornerBlock) { - return modifyCornerToConnect(level, pos, state, toward, towardIsPipe); + return PipeBlockItem.modifyCornerToConnect(level, pos, state, toward, towardIsPipe); } else if (state.getBlock() instanceof PipeNodeBlock) { PipeBlock.NodePipe value = towardIsPipe ? PipeBlock.NodePipe.PIPE : PipeBlock.NodePipe.END; BlockState newState = state.setValue(PipeBlock.getPropertyForDirection(toward), value); @@ -164,9 +164,9 @@ private static BlockState modifyPipeToConnect(Level level, BlockPos pos, BlockSt Direction endDir = Direction.get(Direction.AxisDirection.POSITIVE, axis); if (toward.getAxis() == axis) { - return getContainsDirectionBlockState(level, pos, state, toward, towardIsPipe, startDir); + return PipeBlockItem.getContainsDirectionBlockState(level, pos, state, toward, towardIsPipe, startDir); } - return getConnectedBlockState(level, pos, state, toward, towardIsPipe, startDir, endDir); + return PipeBlockItem.getConnectedBlockState(level, pos, state, toward, towardIsPipe, startDir, endDir); } /** @@ -188,9 +188,9 @@ private static BlockState modifyPipeToConnect(Level level, BlockPos pos, BlockSt Direction second = corner.getSecondDirection(); if (corner.containsDirection(toward)) { - return getContainsDirectionBlockState(level, pos, state, toward, towardIsPipe, first); + return PipeBlockItem.getContainsDirectionBlockState(level, pos, state, toward, towardIsPipe, first); } - return getConnectedBlockState(level, pos, state, toward, towardIsPipe, first, second); + return PipeBlockItem.getConnectedBlockState(level, pos, state, toward, towardIsPipe, first, second); } /** @@ -243,7 +243,7 @@ private static BlockState getConnectedBlockState( boolean endOccupied = PipeBlock.isNeighborOccupied(level, pos, endDir); if (startOccupied && endOccupied) { - return convertToNode(level, pos, state, toward, towardIsPipe, startDir, endDir); + return PipeBlockItem.convertToNode(level, pos, state, toward, towardIsPipe, startDir, endDir); } else { Direction occupiedEnd = startOccupied ? startDir : endDir; boolean occupiedEndIsPipe = PipeBlock.isNeighborPipeToward(level, pos, occupiedEnd); @@ -370,7 +370,7 @@ protected BlockState getPlacementState(BlockPlaceContext context) { boolean shiftDown = player != null && player.isShiftKeyDown() && !clickedOnEntityFluidHandler; if (shiftDown || (!clickedOnPipe && !clickedOnFluidHandler)) { - Direction.Axis axis = getLookAxis(player); + Direction.Axis axis = PipeBlockItem.getLookAxis(player); return this.makeStraightState(level, placePos, axis, true, true); } @@ -458,7 +458,7 @@ private BlockState handleCornerPlacement( ); nodeState = nodeState.setValue(PipeBlock.getPropertyForDirection(clickedFace), PipeBlock.NodePipe.PIPE); PipeBlock.setBlockPreservingValve(level, cornerPos, nodeState); - playPlaceSound(level, cornerPos, nodeState, player); + PipeBlockItem.playPlaceSound(level, cornerPos, nodeState, player); } else if (bothFree || oppositeOccupied) { Direction.Axis axis = clickedFace.getAxis(); Direction startDir = PipeBlock.getDirectionFromAxis(axis, Direction.AxisDirection.NEGATIVE); @@ -479,7 +479,7 @@ private BlockState handleCornerPlacement( .setValue(PipeBlock.HAS_END_END, !endIsPipe) .setValue(PipeBlock.WATERLOGGED, cornerState.getValue(PipeBlock.WATERLOGGED)); PipeBlock.setBlockPreservingValve(level, cornerPos, straightState); - playPlaceSound(level, cornerPos, straightState, player); + PipeBlockItem.playPlaceSound(level, cornerPos, straightState, player); } else if (!directionMatches) { Direction occupiedEnd = firstOccupied ? first : second; PipeBlock.CornerEnded newCorner = PipeBlock.CornerEnded.fromDirections(occupiedEnd, clickedFace); @@ -493,7 +493,7 @@ private BlockState handleCornerPlacement( .setValue(PipeBlock.HAS_END_START, firstIsOccupied && !occupiedEndIsPipe) .setValue(PipeBlock.HAS_END_END, !firstIsOccupied && !occupiedEndIsPipe); PipeBlock.setBlockPreservingValve(level, cornerPos, newCornerState); - playPlaceSound(level, cornerPos, newCornerState, player); + PipeBlockItem.playPlaceSound(level, cornerPos, newCornerState, player); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/PlaceInWaterBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/PlaceInWaterBlockItem.java index 18d2b5d187..ac7f9bc884 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/PlaceInWaterBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/PlaceInWaterBlockItem.java @@ -4,6 +4,7 @@ import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; @@ -27,7 +28,7 @@ public InteractionResult use( Player player, InteractionHand usedHand ) { - BlockHitResult fluidHit = getPlayerPOVHitResult(level, player, ClipContext.Fluid.SOURCE_ONLY); + BlockHitResult fluidHit = Item.getPlayerPOVHitResult(level, player, ClipContext.Fluid.SOURCE_ONLY); BlockHitResult blockHitResult2 = fluidHit.withPosition(fluidHit.getBlockPos()); if (blockHitResult2.miss) return InteractionResult.PASS; InteractionResult interactionResult = super.useOn(new UseOnContext(player, usedHand, blockHitResult2)); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/block/ResinBlockItem.java b/src/main/java/dev/dubhe/anvilcraft/item/block/ResinBlockItem.java index f52ecd1d17..d1bcb30c21 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/block/ResinBlockItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/block/ResinBlockItem.java @@ -39,7 +39,7 @@ public InteractionResult useOn(UseOnContext context) { if (!ResinBlockItem.hasMob(stack) && context.getLevel().getBlockEntity(context.getClickedPos()) instanceof SpawnerBlockEntity spawner ) { - return captureSpawner(context, spawner); + return ResinBlockItem.captureSpawner(context, spawner); } if (!ResinBlockItem.hasMob(stack)) return super.useOn(context); Level level = context.getLevel(); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/EmberMetalIngotItem.java b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/EmberMetalIngotItem.java index 20d7f393e1..768ad1d150 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/EmberMetalIngotItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/EmberMetalIngotItem.java @@ -26,11 +26,11 @@ public EmberMetalIngotItem(Properties properties) { @Override public Component getInputTooltip(ItemStack material) { - return MISSING_TOOLTIP; + return EmberMetalIngotItem.MISSING_TOOLTIP; } @Override public List getEmptySlotTextures() { - return EMPTY_SLOT_TEXTURES; + return EmberMetalIngotItem.EMPTY_SLOT_TEXTURES; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ExpGemItem.java b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ExpGemItem.java index 4bf44e0483..a0647c22e9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ExpGemItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ExpGemItem.java @@ -46,18 +46,18 @@ public static InteractionResult useEntity(Player player, Entity target, ItemStac if (villagerData.profession() == VillagerProfession.NONE) return InteractionResult.PASS; if (!VillagerData.canLevelUp(villagerLevel)) return InteractionResult.PASS; - updateVillager(villager); + ExpGemItem.updateVillager(villager); stack.consume(1, player); return InteractionResult.SUCCESS; } else { - villager.ageUp(AGE_ADDITION, true); + villager.ageUp(ExpGemItem.AGE_ADDITION, true); stack.consume(1, player); return InteractionResult.SUCCESS; } } public static void updateVillager(Villager villager) { - int villagerXp = villager.getVillagerXp() + VILLAGER_XP; + int villagerXp = villager.getVillagerXp() + ExpGemItem.VILLAGER_XP; villager.setVillagerXp(villagerXp); VillagerAccessor accessor = Util.cast(villager); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/HeavyHalberdCoreItem.java b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/HeavyHalberdCoreItem.java index f024b4ac1f..45c5834e46 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/HeavyHalberdCoreItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/HeavyHalberdCoreItem.java @@ -25,7 +25,9 @@ public class HeavyHalberdCoreItem extends Item implements IMultipleMaterial { private static final Component MISSING_TOOLS_TOOLTIP = Component.translatable( "screen.anvilcraft.ember_smithing.heavy_halberd_core.missing_tools"); private static final List EMPTY_SLOT_TEXTURES = List.of( - EMPTY_SLOT_SWORD, EMPTY_SLOT_SPEAR, EMPTY_SLOT_TRIDENT, EMPTY_SLOT_MACE); + HeavyHalberdCoreItem.EMPTY_SLOT_SWORD, HeavyHalberdCoreItem.EMPTY_SLOT_SPEAR, HeavyHalberdCoreItem.EMPTY_SLOT_TRIDENT, + HeavyHalberdCoreItem.EMPTY_SLOT_MACE + ); public HeavyHalberdCoreItem(Properties properties) { super(properties); @@ -33,21 +35,21 @@ public HeavyHalberdCoreItem(Properties properties) { @Override public Component getInputTooltip(ItemStack template, List inputs) { - return MISSING_TOOLS_TOOLTIP; + return HeavyHalberdCoreItem.MISSING_TOOLS_TOOLTIP; } @Override public List getEmptySlotTextures(ItemStack template, int id, List inputs) { - List textures = ListUtil.cycle(EMPTY_SLOT_TEXTURES, id); + List textures = ListUtil.cycle(HeavyHalberdCoreItem.EMPTY_SLOT_TEXTURES, id); for (ItemStack input : inputs) { if (input.is(ItemTags.SWORDS)) { - textures.remove(EMPTY_SLOT_SWORD); + textures.remove(HeavyHalberdCoreItem.EMPTY_SLOT_SWORD); } else if (input.is(ItemTags.SPEARS)) { - textures.remove(EMPTY_SLOT_SPEAR); + textures.remove(HeavyHalberdCoreItem.EMPTY_SLOT_SPEAR); } else if (input.is(Items.TRIDENT)) { - textures.remove(EMPTY_SLOT_TRIDENT); + textures.remove(HeavyHalberdCoreItem.EMPTY_SLOT_TRIDENT); } else if (input.is(Tags.Items.TOOLS_MACE)) { - textures.remove(EMPTY_SLOT_MACE); + textures.remove(HeavyHalberdCoreItem.EMPTY_SLOT_MACE); } } return textures; diff --git a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseMatterItem.java b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseMatterItem.java index 91550ffdbc..91fe635081 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseMatterItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseMatterItem.java @@ -47,29 +47,29 @@ public MultiphaseMatterItem(Properties properties) { @Override public Component getInputTooltip(ItemStack template, List inputs) { - return EMBER_MISSING_TOOLTIP; + return MultiphaseMatterItem.EMBER_MISSING_TOOLTIP; } @Override public Component getInputTooltip(ItemStack material) { - return FROST_MISSING_TOOLTIP; + return MultiphaseMatterItem.FROST_MISSING_TOOLTIP; } @Override public List getEmptySlotTextures(ItemStack template, int id, List inputs) { List result = new ArrayList<>(); EMPTY_SLOTS_TEXTURES_CHECK: - for (Item item : EMBER_EMPTY_SLOT_TEXTURES.keySet()) { + for (Item item : MultiphaseMatterItem.EMBER_EMPTY_SLOT_TEXTURES.keySet()) { for (ItemStack input : inputs) { if (input.is(item)) continue EMPTY_SLOTS_TEXTURES_CHECK; } - result.add(EMBER_EMPTY_SLOT_TEXTURES.get(item)); + result.add(MultiphaseMatterItem.EMBER_EMPTY_SLOT_TEXTURES.get(item)); } return result; } @Override public List getEmptySlotTextures() { - return FROST_EMPTY_SLOT_TEXTURES; + return MultiphaseMatterItem.FROST_EMPTY_SLOT_TEXTURES; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseTranscendiumItem.java b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseTranscendiumItem.java index bf86459340..19e4ebc1d9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseTranscendiumItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/MultiphaseTranscendiumItem.java @@ -26,8 +26,8 @@ public class MultiphaseTranscendiumItem extends Item implements IMultipleMateria private static final Component HEAVY_HALBERD_MISSING_TOOLS_TOOLTIP = Component.translatable( "screen.anvilcraft.ember_smithing.multiphase_transcendium.heavy_halberd_missing_tools"); private static final List EMPTY_SLOT_TEXTURES = List.of( - EMPTY_SLOT_RESONATOR, - EMPTY_SLOT_HEAVY_HALBERD + MultiphaseTranscendiumItem.EMPTY_SLOT_RESONATOR, + MultiphaseTranscendiumItem.EMPTY_SLOT_HEAVY_HALBERD ); public MultiphaseTranscendiumItem(Properties properties) { @@ -48,18 +48,18 @@ public Component getInputTooltip(ItemStack template, List inputs) { } } return switch (tool) { - case DEFAULT -> MISSING_TOOLS_TOOLTIP; - case TRUE -> RESONATOR_MISSING_TOOLS_TOOLTIP; - case FALSE -> HEAVY_HALBERD_MISSING_TOOLS_TOOLTIP; + case DEFAULT -> MultiphaseTranscendiumItem.MISSING_TOOLS_TOOLTIP; + case TRUE -> MultiphaseTranscendiumItem.RESONATOR_MISSING_TOOLS_TOOLTIP; + case FALSE -> MultiphaseTranscendiumItem.HEAVY_HALBERD_MISSING_TOOLS_TOOLTIP; }; } @Override public List getEmptySlotTextures(ItemStack template, int id, List inputs) { for (ItemStack input : inputs) { - if (input.is(ModItemTags.RESONATOR)) return List.of(EMPTY_SLOT_RESONATOR); - if (input.is(ModItemTags.HEAVY_HALBERD)) return List.of(EMPTY_SLOT_HEAVY_HALBERD); + if (input.is(ModItemTags.RESONATOR)) return List.of(MultiphaseTranscendiumItem.EMPTY_SLOT_RESONATOR); + if (input.is(ModItemTags.HEAVY_HALBERD)) return List.of(MultiphaseTranscendiumItem.EMPTY_SLOT_HEAVY_HALBERD); } - return ListUtil.cycle(EMPTY_SLOT_TEXTURES, id); + return ListUtil.cycle(MultiphaseTranscendiumItem.EMPTY_SLOT_TEXTURES, id); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ResonatorCoreItem.java b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ResonatorCoreItem.java index afb0397832..55d128fe04 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ResonatorCoreItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/ResonatorCoreItem.java @@ -22,10 +22,10 @@ public class ResonatorCoreItem extends Item implements IMultipleMaterial { private static final Component MISSING_TOOLS_TOOLTIP = Component.translatable( "screen.anvilcraft.ember_smithing.resonator_core.missing_tools"); private static final List EMPTY_SLOT_TEXTURES = List.of( - EMPTY_SLOT_AXE, - EMPTY_SLOT_SHOVEL, - EMPTY_SLOT_HOE, - EMPTY_SLOT_PICKAXE + ResonatorCoreItem.EMPTY_SLOT_AXE, + ResonatorCoreItem.EMPTY_SLOT_SHOVEL, + ResonatorCoreItem.EMPTY_SLOT_HOE, + ResonatorCoreItem.EMPTY_SLOT_PICKAXE ); public ResonatorCoreItem(Properties properties) { @@ -34,21 +34,21 @@ public ResonatorCoreItem(Properties properties) { @Override public Component getInputTooltip(ItemStack template, List inputs) { - return MISSING_TOOLS_TOOLTIP; + return ResonatorCoreItem.MISSING_TOOLS_TOOLTIP; } @Override public List getEmptySlotTextures(ItemStack template, int id, List inputs) { - List textures = ListUtil.cycle(EMPTY_SLOT_TEXTURES, id); + List textures = ListUtil.cycle(ResonatorCoreItem.EMPTY_SLOT_TEXTURES, id); for (ItemStack input : inputs) { if (input.is(ItemTags.AXES)) { - textures.remove(EMPTY_SLOT_AXE); + textures.remove(ResonatorCoreItem.EMPTY_SLOT_AXE); } else if (input.is(ItemTags.SHOVELS)) { - textures.remove(EMPTY_SLOT_SHOVEL); + textures.remove(ResonatorCoreItem.EMPTY_SLOT_SHOVEL); } else if (input.is(ItemTags.HOES)) { - textures.remove(EMPTY_SLOT_HOE); + textures.remove(ResonatorCoreItem.EMPTY_SLOT_HOE); } else if (input.is(ItemTags.PICKAXES)) { - textures.remove(EMPTY_SLOT_PICKAXE); + textures.remove(ResonatorCoreItem.EMPTY_SLOT_PICKAXE); } } return textures; diff --git a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/RoyalSteelIngotItem.java b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/RoyalSteelIngotItem.java index 8eedfd9e14..e1ff4dcf9c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/ingredients/RoyalSteelIngotItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/ingredients/RoyalSteelIngotItem.java @@ -26,11 +26,11 @@ public RoyalSteelIngotItem(Properties properties) { @Override public Component getInputTooltip(ItemStack material) { - return MISSING_TOOLTIP; + return RoyalSteelIngotItem.MISSING_TOOLTIP; } @Override public List getEmptySlotTextures() { - return EMPTY_SLOT_TEXTURES; + return RoyalSteelIngotItem.EMPTY_SLOT_TEXTURES; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/BoxContents.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/BoxContents.java index 86e5edd708..786665c894 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/BoxContents.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/BoxContents.java @@ -44,7 +44,7 @@ public record BoxContents(List amulets, List totems, int s ); BoxContents(List amulets, List totems, int selectedItemIndex) { - this(amulets, totems, selectedItemIndex, computeUsage(amulets, totems)); + this(amulets, totems, selectedItemIndex, BoxContents.computeUsage(amulets, totems)); } public static int sum(List amulets, List totems, ToIntFunction fn) { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Ferocious.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Ferocious.java index ec71b33e72..02e1c38c96 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Ferocious.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Ferocious.java @@ -61,19 +61,19 @@ private static void tick(ItemStack stack) { if (attackDamage != 0) { builder.add( Attributes.ATTACK_DAMAGE, - new AttributeModifier(FEROCIOUS_ID, attackDamage, AttributeModifier.Operation.ADD_VALUE), + new AttributeModifier(Ferocious.FEROCIOUS_ID, attackDamage, AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND ); } if (miningEfficiency != 0) { builder.add( Attributes.MINING_EFFICIENCY, - new AttributeModifier(FEROCIOUS_ID, miningEfficiency, AttributeModifier.Operation.ADD_VALUE), + new AttributeModifier(Ferocious.FEROCIOUS_ID, miningEfficiency, AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND ); } for (ItemAttributeModifiers.Entry entry : stack.getAttributeModifiers().modifiers()) { - if (!entry.modifier().is(FEROCIOUS_ID)) { + if (!entry.modifier().is(Ferocious.FEROCIOUS_ID)) { builder.add(entry.attribute(), entry.modifier(), entry.slot()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/FireReforging.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/FireReforging.java index 38f1bd2e82..d0a05ab72b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/FireReforging.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/FireReforging.java @@ -14,7 +14,7 @@ public record FireReforging() implements TooltipProvider { public static final FireReforging DEFAULT = new FireReforging(); - public static final MapCodec CODEC = MapCodec.unit(DEFAULT); + public static final MapCodec CODEC = MapCodec.unit(FireReforging.DEFAULT); public static final StreamCodec STREAM_CODEC = StreamCodec.unit(new FireReforging()); @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Merciless.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Merciless.java index 1836b23060..02188f4faf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Merciless.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Merciless.java @@ -41,12 +41,12 @@ public static void tick(ServerPlayer player) { } private static void tick(ItemStack stack) { - absorbEnchantments(stack); + Merciless.absorbEnchantments(stack); } public static void enable(ItemStack stack) { - stack.set(ModComponents.MERCILESS, DEFAULT); - absorbEnchantments(stack); + stack.set(ModComponents.MERCILESS, Merciless.DEFAULT); + Merciless.absorbEnchantments(stack); } public static void disable(ItemStack stack) { @@ -59,7 +59,7 @@ public static void disable(ItemStack stack) { stack.set(DataComponents.ENCHANTMENTS, enchantments); } stack.remove(ModComponents.MERCILESS_ENCHANTMENTS); - removeAttributeModifiers(stack); + Merciless.removeAttributeModifiers(stack); } public static void absorbEnchantments(ItemStack stack) { @@ -69,7 +69,7 @@ public static void absorbEnchantments(ItemStack stack) { ItemEnchantments.EMPTY ); if (enchantments.isEmpty()) { - if (mercilessEnchs.isEmpty()) removeAttributeModifiers(stack); + if (mercilessEnchs.isEmpty()) Merciless.removeAttributeModifiers(stack); return; } @@ -112,19 +112,19 @@ public static void absorbEnchantments(ItemStack stack) { if (attackDamage != 0) { builder.add( Attributes.ATTACK_DAMAGE, - new AttributeModifier(MERCILESS_ID, attackDamage, AttributeModifier.Operation.ADD_VALUE), + new AttributeModifier(Merciless.MERCILESS_ID, attackDamage, AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND ); } if (miningEfficiency != 0) { builder.add( Attributes.MINING_EFFICIENCY, - new AttributeModifier(MERCILESS_ID, miningEfficiency, AttributeModifier.Operation.ADD_VALUE), + new AttributeModifier(Merciless.MERCILESS_ID, miningEfficiency, AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND ); } for (ItemAttributeModifiers.Entry entry : stack.getAttributeModifiers().modifiers()) { - if (!entry.modifier().is(MERCILESS_ID)) { + if (!entry.modifier().is(Merciless.MERCILESS_ID)) { builder.add(entry.attribute(), entry.modifier(), entry.slot()); } } @@ -135,7 +135,7 @@ private static void removeAttributeModifiers(ItemStack stack) { ItemAttributeModifiers.Builder builder = ItemAttributeModifiers.builder(); boolean found = false; for (ItemAttributeModifiers.Entry entry : stack.getAttributeModifiers().modifiers()) { - if (entry.modifier().is(MERCILESS_ID)) { + if (entry.modifier().is(Merciless.MERCILESS_ID)) { found = true; } else { builder.add(entry.attribute(), entry.modifier(), entry.slot()); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Multiphase.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Multiphase.java index 929d4cc2be..24530607e4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Multiphase.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Multiphase.java @@ -38,10 +38,10 @@ public record Multiphase(List phases, int activePhase) implements Tooltip Codec.BOOL.optionalFieldOf("merciless", false).forGetter(ignored -> false) ).apply(instance, (phases, activePhase, ignored) -> new Multiphase(phases, activePhase))); private static final MapCodec LEGACY_CODEC = Codec.PASSTHROUGH.fieldOf("id").xmap( - ignored -> create(), + ignored -> Multiphase.create(), ignored -> new Dynamic<>(JsonOps.INSTANCE, JsonOps.INSTANCE.emptyMap()) ); - public static final MapCodec CODEC = Codec.mapEither(DATA_CODEC, LEGACY_CODEC).xmap( + public static final MapCodec CODEC = Codec.mapEither(Multiphase.DATA_CODEC, Multiphase.LEGACY_CODEC).xmap( either -> either.map(multiphase -> multiphase, multiphase -> multiphase), Either::left ); @@ -55,7 +55,7 @@ public record Multiphase(List phases, int activePhase) implements Tooltip public Multiphase { phases = List.copyOf(phases); - if (phases.size() < MIN_PHASE_COUNT || phases.size() > MAX_PHASE_COUNT) { + if (phases.size() < Multiphase.MIN_PHASE_COUNT || phases.size() > Multiphase.MAX_PHASE_COUNT) { throw new IllegalArgumentException("Multiphase phase count must be between 2 and 4"); } if (activePhase < 0 || activePhase >= phases.size()) { @@ -70,25 +70,25 @@ public static Multiphase create() { public static Component makeName(int index) { return Component.translatableWithFallback( "tooltip.anvilcraft.property.multiphase.name." + index, - DEFAULT_NAMES.get(index) + Multiphase.DEFAULT_NAMES.get(index) ); } public static Component makeSuffix(int index) { return Component.translatableWithFallback( "tooltip.anvilcraft.property.multiphase.suffix." + index, - "-" + DEFAULT_NAMES.get(index) + "-" + Multiphase.DEFAULT_NAMES.get(index) ); } public static Component firstPhaseName(Component name) { - return name.copy().append(makeSuffix(0)); + return name.copy().append(Multiphase.makeSuffix(0)); } public Component phaseDisplayName(int index) { return this.phases.get(index).customName().isPresent() ? this.phases.get(index).customName().get().copy() - : makeName(index); + : Multiphase.makeName(index); } public Multiphase capture(ItemStack stack) { @@ -128,7 +128,7 @@ public void initialize(ItemStack stack) { public boolean addPhase(ItemStack stack) { Multiphase captured = this.capture(stack); - if (captured.phases.size() >= MAX_PHASE_COUNT) return false; + if (captured.phases.size() >= Multiphase.MAX_PHASE_COUNT) return false; List expanded = new ArrayList<>(captured.phases); expanded.add(Phase.EMPTY); stack.set(ModComponents.MULTIPHASE, new Multiphase(expanded, captured.activePhase)); @@ -149,7 +149,7 @@ private void applyToStack(ItemStack stack) { this.phases.get(this.activePhase).applyToStack(stack); stack.set( DataComponents.ITEM_NAME, - stack.getItem().getName(stack.getItem().getDefaultInstance()).copy().append(makeSuffix(this.activePhase)) + stack.getItem().getName(stack.getItem().getDefaultInstance()).copy().append(Multiphase.makeSuffix(this.activePhase)) ); } @@ -188,7 +188,7 @@ public record Phase(Optional customName, int repairCost, ItemEnchantm } public static Phase fromInput(ItemStack stack) { - return capture( + return Phase.capture( stack, EnchantmentUtil.merge( stack.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY), diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/OverLimitItemContainerContents.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/OverLimitItemContainerContents.java index 61c4f972ad..5a0529f2e8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/OverLimitItemContainerContents.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/OverLimitItemContainerContents.java @@ -31,17 +31,17 @@ public class OverLimitItemContainerContents implements TooltipProvider { private static final int MAX_SIZE = 256; public static final OverLimitItemContainerContents EMPTY = new OverLimitItemContainerContents(NonNullList.create()); public static final Codec CODEC = Slot.CODEC - .sizeLimitedListOf(MAX_SIZE) + .sizeLimitedListOf(OverLimitItemContainerContents.MAX_SIZE) .xmap(OverLimitItemContainerContents::fromSlots, OverLimitItemContainerContents::asSlots); public static final StreamCodec STREAM_CODEC = UnlimitedItemStack .OPTIONAL_STREAM_CODEC - .apply(ByteBufCodecs.list(MAX_SIZE)) + .apply(ByteBufCodecs.list(OverLimitItemContainerContents.MAX_SIZE)) .map(OverLimitItemContainerContents::new, OverLimitItemContainerContents::getItems); private final NonNullList items; private OverLimitItemContainerContents(NonNullList items) { - if (items.size() > MAX_SIZE) { - throw new IllegalArgumentException("Got " + items.size() + " items, but maximum is " + MAX_SIZE); + if (items.size() > OverLimitItemContainerContents.MAX_SIZE) { + throw new IllegalArgumentException("Got " + items.size() + " items, but maximum is " + OverLimitItemContainerContents.MAX_SIZE); } else { this.items = items; } @@ -61,7 +61,7 @@ private OverLimitItemContainerContents(List items) { private static OverLimitItemContainerContents fromSlots(List slots) { OptionalInt maxSlot = slots.stream().mapToInt(Slot::index).max(); - if (maxSlot.isEmpty()) return EMPTY; + if (maxSlot.isEmpty()) return OverLimitItemContainerContents.EMPTY; OverLimitItemContainerContents contents = new OverLimitItemContainerContents(maxSlot.getAsInt() + 1); for (Slot slot : slots) { @@ -72,8 +72,8 @@ private static OverLimitItemContainerContents fromSlots(List slots) { } public static OverLimitItemContainerContents fromItems(List items) { - int i = findLastNonEmptySlot(items); - if (i == NO_SLOT) return EMPTY; + int i = OverLimitItemContainerContents.findLastNonEmptySlot(items); + if (i == OverLimitItemContainerContents.NO_SLOT) return OverLimitItemContainerContents.EMPTY; OverLimitItemContainerContents contents = new OverLimitItemContainerContents(i + 1); for (int j = 0; j <= i; j++) { @@ -84,8 +84,8 @@ public static OverLimitItemContainerContents fromItems(List } public static OverLimitItemContainerContents fromItems(OverLimitItemHandler items) { - int i = findLastNonEmptySlot(items); - if (i == NO_SLOT) return EMPTY; + int i = OverLimitItemContainerContents.findLastNonEmptySlot(items); + if (i == OverLimitItemContainerContents.NO_SLOT) return OverLimitItemContainerContents.EMPTY; OverLimitItemContainerContents contents = new OverLimitItemContainerContents(i + 1); for (int j = 0; j <= i; j++) { @@ -100,7 +100,7 @@ private static int findLastNonEmptySlot(List items) { if (!items.get(i).isEmpty()) return i; } - return NO_SLOT; + return OverLimitItemContainerContents.NO_SLOT; } private static int findLastNonEmptySlot(OverLimitItemHandler items) { @@ -108,7 +108,7 @@ private static int findLastNonEmptySlot(OverLimitItemHandler items) { if (!items.peek(i).isEmpty()) return i; } - return NO_SLOT; + return OverLimitItemContainerContents.NO_SLOT; } private List asSlots() { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Providence.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Providence.java index 14c86f91ed..909369ac8f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/Providence.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/Providence.java @@ -6,6 +6,6 @@ public record Providence() { public static final Providence INSTANCE = new Providence(); - public static final MapCodec CODEC = MapCodec.unit(INSTANCE); - public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); + public static final MapCodec CODEC = MapCodec.unit(Providence.INSTANCE); + public static final StreamCodec STREAM_CODEC = StreamCodec.unit(Providence.INSTANCE); } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/SavedEntity.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/SavedEntity.java index b468f2a460..84810495ec 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/SavedEntity.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/SavedEntity.java @@ -45,7 +45,7 @@ public record SavedEntity(EntityType type, CompoundTag tag, boolean isMonster public Entity toEntity(Level level) { Entity entity = this.type.create(level, EntitySpawnReason.TRIGGERED); if (entity == null) return null; - try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(entity.problemPath(), log)) { + try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(entity.problemPath(), SavedEntity.log)) { entity.load(TagValueInput.create(reporter, level.registryAccess(), this.tag)); } return entity; @@ -54,7 +54,7 @@ public Entity toEntity(Level level) { public static SavedEntity fromEntity(Entity entity) { if (entity instanceof Mob mob) ResentmentUtil.initializeBaseResentment(mob); CompoundTag entityTag; - try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(entity.problemPath(), log)) { + try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(entity.problemPath(), SavedEntity.log)) { TagValueOutput output = TagValueOutput.createWithContext(reporter, entity.level().registryAccess()); entity.saveAsPassenger(output); entityTag = output.buildResult(); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/component/StoredFluids.java b/src/main/java/dev/dubhe/anvilcraft/item/property/component/StoredFluids.java index ccb38a8368..31a5b96388 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/component/StoredFluids.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/component/StoredFluids.java @@ -32,8 +32,7 @@ public boolean isEmpty() { @Override public boolean equals(Object obj) { - if (!(obj instanceof StoredFluids other)) return false; - List otherFluids = other.fluids; + if (!(obj instanceof StoredFluids(List otherFluids))) return false; if (this.fluids.size() != otherFluids.size()) return false; for (int i = 0; i < this.fluids.size(); i++) { if (!FluidStack.matches(this.fluids.get(i), otherFluids.get(i))) return false; diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/PreventShrinkingConsumeEffect.java b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/PreventShrinkingConsumeEffect.java index 79aced5400..2295f27799 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/PreventShrinkingConsumeEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/PreventShrinkingConsumeEffect.java @@ -14,8 +14,9 @@ public class PreventShrinkingConsumeEffect implements ConsumeEffect { public static final ThreadLocal<@Nullable InteractionHand> USED_HAND = new ThreadLocal<>(); public static final PreventShrinkingConsumeEffect INSTANCE = new PreventShrinkingConsumeEffect(); - public static final MapCodec CODEC = MapCodec.unit(INSTANCE); - public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); + public static final MapCodec CODEC = MapCodec.unit(PreventShrinkingConsumeEffect.INSTANCE); + public static final StreamCodec STREAM_CODEC = StreamCodec.unit( + PreventShrinkingConsumeEffect.INSTANCE); @Override public Type getType() { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/SetRagedConsumeEffect.java b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/SetRagedConsumeEffect.java index 35dfd48dbd..ffd26877ec 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/SetRagedConsumeEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/SetRagedConsumeEffect.java @@ -11,8 +11,8 @@ public class SetRagedConsumeEffect implements ConsumeEffect { public static final SetRagedConsumeEffect INSTANCE = new SetRagedConsumeEffect(); - public static final MapCodec CODEC = MapCodec.unit(INSTANCE); - public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); + public static final MapCodec CODEC = MapCodec.unit(SetRagedConsumeEffect.INSTANCE); + public static final StreamCodec STREAM_CODEC = StreamCodec.unit(SetRagedConsumeEffect.INSTANCE); @Override public Type getType() { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TeleportToRespawnPointConsumeEffect.java b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TeleportToRespawnPointConsumeEffect.java index 279ccbd14c..767bed95b5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TeleportToRespawnPointConsumeEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TeleportToRespawnPointConsumeEffect.java @@ -26,8 +26,9 @@ public class TeleportToRespawnPointConsumeEffect implements ConsumeEffect { public static final TeleportToRespawnPointConsumeEffect INSTANCE = new TeleportToRespawnPointConsumeEffect(); - public static final MapCodec CODEC = MapCodec.unit(INSTANCE); - public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); + public static final MapCodec CODEC = MapCodec.unit(TeleportToRespawnPointConsumeEffect.INSTANCE); + public static final StreamCodec STREAM_CODEC = StreamCodec.unit( + TeleportToRespawnPointConsumeEffect.INSTANCE); @Override public Type getType() { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TryTotemsInBoxConsumeEffect.java b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TryTotemsInBoxConsumeEffect.java index 0efba5e3d8..af9abfd8ae 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TryTotemsInBoxConsumeEffect.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/consume/TryTotemsInBoxConsumeEffect.java @@ -14,8 +14,9 @@ public class TryTotemsInBoxConsumeEffect implements ConsumeEffect { public static final TryTotemsInBoxConsumeEffect INSTANCE = new TryTotemsInBoxConsumeEffect(); - public static final MapCodec CODEC = MapCodec.unit(INSTANCE); - public static final StreamCodec STREAM_CODEC = StreamCodec.unit(INSTANCE); + public static final MapCodec CODEC = MapCodec.unit(TryTotemsInBoxConsumeEffect.INSTANCE); + public static final StreamCodec STREAM_CODEC = StreamCodec.unit( + TryTotemsInBoxConsumeEffect.INSTANCE); @Override public Type getType() { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/property/predicate/ExtraEnchantmentsPredicate.java b/src/main/java/dev/dubhe/anvilcraft/item/property/predicate/ExtraEnchantmentsPredicate.java index 8437f8becf..46b6892c13 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/property/predicate/ExtraEnchantmentsPredicate.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/property/predicate/ExtraEnchantmentsPredicate.java @@ -20,7 +20,7 @@ public static DisabledEnchantments disabled(List enchantme } public static class MercilessEnchantments extends EnchantmentsPredicate { - public static final Codec CODEC = codec(MercilessEnchantments::new); + public static final Codec CODEC = EnchantmentsPredicate.codec(MercilessEnchantments::new); protected MercilessEnchantments(List enchantments) { super(enchantments); @@ -46,7 +46,7 @@ public int hashCode() { } public static class DisabledEnchantments extends EnchantmentsPredicate { - public static final Codec CODEC = codec(DisabledEnchantments::new); + public static final Codec CODEC = EnchantmentsPredicate.codec(DisabledEnchantments::new); protected DisabledEnchantments(List enchantments) { super(enchantments); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/template/EmberMetalUpgradeTemplateItem.java b/src/main/java/dev/dubhe/anvilcraft/item/template/EmberMetalUpgradeTemplateItem.java index 407c0b4ab0..e11709310b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/template/EmberMetalUpgradeTemplateItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/template/EmberMetalUpgradeTemplateItem.java @@ -13,14 +13,14 @@ public class EmberMetalUpgradeTemplateItem extends SmithingTemplateItem { private static final ChatFormatting DESCRIPTION_FORMAT = ChatFormatting.BLUE; private static final Component APPLIES_TO = Component.translatable( "screen.anvilcraft.smithing_template.ember_metal_upgrade_smithing_template.applies_to" - ).withStyle(DESCRIPTION_FORMAT); + ).withStyle(EmberMetalUpgradeTemplateItem.DESCRIPTION_FORMAT); private static final Component UPGRADE_INGREDIENTS = Component.translatable("screen.anvilcraft.smithing_template.ember_metal_upgrade_smithing_template" + ".upgrade_ingredients") - .withStyle(DESCRIPTION_FORMAT); + .withStyle(EmberMetalUpgradeTemplateItem.DESCRIPTION_FORMAT); private static final Component UPGRADE = Component.translatable( "screen.anvilcraft.ember_metal_upgrade_smithing_template") - .withStyle(TITLE_FORMAT); + .withStyle(EmberMetalUpgradeTemplateItem.TITLE_FORMAT); private static final Component UPGRADE_BASE_SLOT_DESCRIPTION = Component.translatable( "screen.anvilcraft.smithing_template.ember_metal_upgrade_smithing_template.base_slot_description"); private static final Component UPGRADE_ADDITIONS_SLOT_DESCRIPTION = Component.translatable( @@ -34,12 +34,12 @@ public class EmberMetalUpgradeTemplateItem extends SmithingTemplateItem { public EmberMetalUpgradeTemplateItem(Properties properties) { super( - APPLIES_TO, - UPGRADE_INGREDIENTS, - UPGRADE_BASE_SLOT_DESCRIPTION, - UPGRADE_ADDITIONS_SLOT_DESCRIPTION, - List.of(EMPTY_SLOT_PICKAXE, EMPTY_SLOT_HAMMER), - List.of(EMPTY_SLOT_INGOT, EMPTY_SLOT_BLOCK), + EmberMetalUpgradeTemplateItem.APPLIES_TO, + EmberMetalUpgradeTemplateItem.UPGRADE_INGREDIENTS, + EmberMetalUpgradeTemplateItem.UPGRADE_BASE_SLOT_DESCRIPTION, + EmberMetalUpgradeTemplateItem.UPGRADE_ADDITIONS_SLOT_DESCRIPTION, + List.of(EmberMetalUpgradeTemplateItem.EMPTY_SLOT_PICKAXE, EmberMetalUpgradeTemplateItem.EMPTY_SLOT_HAMMER), + List.of(EmberMetalUpgradeTemplateItem.EMPTY_SLOT_INGOT, EmberMetalUpgradeTemplateItem.EMPTY_SLOT_BLOCK), properties); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/template/FrostMetalUpgradeTemplateItem.java b/src/main/java/dev/dubhe/anvilcraft/item/template/FrostMetalUpgradeTemplateItem.java index 1ddff8763f..ce7e23bec9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/template/FrostMetalUpgradeTemplateItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/template/FrostMetalUpgradeTemplateItem.java @@ -14,11 +14,11 @@ public class FrostMetalUpgradeTemplateItem extends SmithingTemplateItem { private static final ChatFormatting DESCRIPTION_FORMAT = ChatFormatting.BLUE; private static final Component APPLIES_TO = Component.translatable( "screen.anvilcraft.smithing_template.frost_metal_upgrade_smithing_template.applies_to") - .withStyle(DESCRIPTION_FORMAT); + .withStyle(FrostMetalUpgradeTemplateItem.DESCRIPTION_FORMAT); private static final Component UPGRADE_INGREDIENTS = Component.translatable("screen.anvilcraft.smithing_template.frost_metal_upgrade_smithing_template" + ".upgrade_ingredients") - .withStyle(DESCRIPTION_FORMAT); + .withStyle(FrostMetalUpgradeTemplateItem.DESCRIPTION_FORMAT); private static final Component UPGRADE_BASE_SLOT_DESCRIPTION = Component.translatable( "screen.anvilcraft.smithing_template.frost_metal_upgrade_smithing_template.base_slot_description"); private static final Component UPGRADE_ADDITIONS_SLOT_DESCRIPTION = Component.translatable( @@ -32,12 +32,12 @@ public class FrostMetalUpgradeTemplateItem extends SmithingTemplateItem { public FrostMetalUpgradeTemplateItem(Properties properties) { super( - APPLIES_TO, - UPGRADE_INGREDIENTS, - UPGRADE_BASE_SLOT_DESCRIPTION, - UPGRADE_ADDITIONS_SLOT_DESCRIPTION, - List.of(EMPTY_SLOT_PICKAXE, EMPTY_SLOT_HAMMER), - List.of(EMPTY_SLOT_INGOT, EMPTY_SLOT_BLOCK), + FrostMetalUpgradeTemplateItem.APPLIES_TO, + FrostMetalUpgradeTemplateItem.UPGRADE_INGREDIENTS, + FrostMetalUpgradeTemplateItem.UPGRADE_BASE_SLOT_DESCRIPTION, + FrostMetalUpgradeTemplateItem.UPGRADE_ADDITIONS_SLOT_DESCRIPTION, + List.of(FrostMetalUpgradeTemplateItem.EMPTY_SLOT_PICKAXE, FrostMetalUpgradeTemplateItem.EMPTY_SLOT_HAMMER), + List.of(FrostMetalUpgradeTemplateItem.EMPTY_SLOT_INGOT, FrostMetalUpgradeTemplateItem.EMPTY_SLOT_BLOCK), properties); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/template/RoyalSteelUpgradeTemplateItem.java b/src/main/java/dev/dubhe/anvilcraft/item/template/RoyalSteelUpgradeTemplateItem.java index 7fad87c7ec..fcf3f73097 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/template/RoyalSteelUpgradeTemplateItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/template/RoyalSteelUpgradeTemplateItem.java @@ -14,11 +14,11 @@ public class RoyalSteelUpgradeTemplateItem extends SmithingTemplateItem { private static final ChatFormatting DESCRIPTION_FORMAT = ChatFormatting.BLUE; private static final Component APPLIES_TO = Component.translatable( "screen.anvilcraft.smithing_template.royal_steel_upgrade_smithing_template.applies_to") - .withStyle(DESCRIPTION_FORMAT); + .withStyle(RoyalSteelUpgradeTemplateItem.DESCRIPTION_FORMAT); private static final Component UPGRADE_INGREDIENTS = Component.translatable("screen.anvilcraft.smithing_template.royal_steel_upgrade_smithing_template" + ".upgrade_ingredients") - .withStyle(DESCRIPTION_FORMAT); + .withStyle(RoyalSteelUpgradeTemplateItem.DESCRIPTION_FORMAT); private static final Component UPGRADE_BASE_SLOT_DESCRIPTION = Component.translatable( "screen.anvilcraft.smithing_template.royal_steel_upgrade_smithing_template.base_slot_description"); private static final Component UPGRADE_ADDITIONS_SLOT_DESCRIPTION = Component.translatable( @@ -32,12 +32,12 @@ public class RoyalSteelUpgradeTemplateItem extends SmithingTemplateItem { public RoyalSteelUpgradeTemplateItem(Properties properties) { super( - APPLIES_TO, - UPGRADE_INGREDIENTS, - UPGRADE_BASE_SLOT_DESCRIPTION, - UPGRADE_ADDITIONS_SLOT_DESCRIPTION, - List.of(EMPTY_SLOT_PICKAXE, EMPTY_SLOT_HAMMER), - List.of(EMPTY_SLOT_INGOT, EMPTY_SLOT_BLOCK), + RoyalSteelUpgradeTemplateItem.APPLIES_TO, + RoyalSteelUpgradeTemplateItem.UPGRADE_INGREDIENTS, + RoyalSteelUpgradeTemplateItem.UPGRADE_BASE_SLOT_DESCRIPTION, + RoyalSteelUpgradeTemplateItem.UPGRADE_ADDITIONS_SLOT_DESCRIPTION, + List.of(RoyalSteelUpgradeTemplateItem.EMPTY_SLOT_PICKAXE, RoyalSteelUpgradeTemplateItem.EMPTY_SLOT_HAMMER), + List.of(RoyalSteelUpgradeTemplateItem.EMPTY_SLOT_INGOT, RoyalSteelUpgradeTemplateItem.EMPTY_SLOT_BLOCK), properties); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/template/mto/EightToOneTemplateItem.java b/src/main/java/dev/dubhe/anvilcraft/item/template/mto/EightToOneTemplateItem.java index bfbc75900a..4e1dce809c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/template/mto/EightToOneTemplateItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/template/mto/EightToOneTemplateItem.java @@ -21,44 +21,45 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; public class EightToOneTemplateItem extends BaseMultipleToOneTemplateItem { private final Map, Item> enchantmentMappings = new Object2ObjectOpenHashMap<>() { { - put(Enchantments.SOUL_SPEED, Items.SNOUT_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.FIRE_PROTECTION, Items.RIB_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.FIRE_ASPECT, Items.RIB_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.FLAME, Items.RIB_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.BLAST_PROTECTION, Items.DUNE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.SWIFT_SNEAK, Items.SILENCE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.PROTECTION, Items.WARD_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.MENDING, Items.VEX_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.INFINITY, Items.SENTRY_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.DENSITY, Items.BOLT_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.BREACH, Items.BOLT_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.WIND_BURST, Items.FLOW_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.PROJECTILE_PROTECTION, Items.WILD_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.FORTUNE, Items.SPIRE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.LOOTING, Items.EYE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.LUCK_OF_THE_SEA, Items.COAST_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.LURE, Items.COAST_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.DEPTH_STRIDER, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.RESPIRATION, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.AQUA_AFFINITY, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.IMPALING, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); - put(Enchantments.RIPTIDE, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.SOUL_SPEED, Items.SNOUT_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.FIRE_PROTECTION, Items.RIB_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.FIRE_ASPECT, Items.RIB_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.FLAME, Items.RIB_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.BLAST_PROTECTION, Items.DUNE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.SWIFT_SNEAK, Items.SILENCE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.PROTECTION, Items.WARD_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.MENDING, Items.VEX_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.INFINITY, Items.SENTRY_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.DENSITY, Items.BOLT_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.BREACH, Items.BOLT_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.WIND_BURST, Items.FLOW_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.PROJECTILE_PROTECTION, Items.WILD_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.FORTUNE, Items.SPIRE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.LOOTING, Items.EYE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.LUCK_OF_THE_SEA, Items.COAST_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.LURE, Items.COAST_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.DEPTH_STRIDER, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.RESPIRATION, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.AQUA_AFFINITY, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.IMPALING, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); + this.put(Enchantments.RIPTIDE, Items.TIDE_ARMOR_TRIM_SMITHING_TEMPLATE); } }; private final List otherTemplate = new ArrayList<>() { { - add(Items.WAYFINDER_ARMOR_TRIM_SMITHING_TEMPLATE); - add(Items.RAISER_ARMOR_TRIM_SMITHING_TEMPLATE); - add(Items.HOST_ARMOR_TRIM_SMITHING_TEMPLATE); - add(Items.SHAPER_ARMOR_TRIM_SMITHING_TEMPLATE); + this.add(Items.WAYFINDER_ARMOR_TRIM_SMITHING_TEMPLATE); + this.add(Items.RAISER_ARMOR_TRIM_SMITHING_TEMPLATE); + this.add(Items.HOST_ARMOR_TRIM_SMITHING_TEMPLATE); + this.add(Items.SHAPER_ARMOR_TRIM_SMITHING_TEMPLATE); } }; - private final List randomTemplates = java.util.stream.Stream.concat( + private final List randomTemplates = Stream.concat( this.enchantmentMappings.values().stream(), this.otherTemplate.stream() ).distinct().toList(); @@ -74,12 +75,12 @@ public EightToOneTemplateItem(Properties properties) { @Override public Component getMaterialTooltip() { - return MISSING_TOOLTIP; + return EightToOneTemplateItem.MISSING_TOOLTIP; } @Override public List getEmptySlotTextures() { - return EMPTY_SLOT_TEXTURES; + return EightToOneTemplateItem.EMPTY_SLOT_TEXTURES; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/item/template/mto/FourToOneTemplateItem.java b/src/main/java/dev/dubhe/anvilcraft/item/template/mto/FourToOneTemplateItem.java index cbd6f4bb3f..a1a7a88af3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/template/mto/FourToOneTemplateItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/template/mto/FourToOneTemplateItem.java @@ -20,11 +20,11 @@ public FourToOneTemplateItem(Properties properties) { @Override public Component getMaterialTooltip() { - return MISSING_TOOLTIP; + return FourToOneTemplateItem.MISSING_TOOLTIP; } @Override public List getEmptySlotTextures() { - return EMPTY_SLOT_TEXTURES; + return FourToOneTemplateItem.EMPTY_SLOT_TEXTURES; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/template/mto/TwoToOneTemplateItem.java b/src/main/java/dev/dubhe/anvilcraft/item/template/mto/TwoToOneTemplateItem.java index 04deceef24..4a678d7a6f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/template/mto/TwoToOneTemplateItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/template/mto/TwoToOneTemplateItem.java @@ -19,11 +19,11 @@ public TwoToOneTemplateItem(Properties properties) { @Override public Component getMaterialTooltip() { - return MISSING_TOOLTIP; + return TwoToOneTemplateItem.MISSING_TOOLTIP; } @Override public List getEmptySlotTextures() { - return EMPTY_SLOT_TEXTURES; + return TwoToOneTemplateItem.EMPTY_SLOT_TEXTURES; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/AnvilHammerItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/AnvilHammerItem.java index 999477b0be..09a5596aa7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/AnvilHammerItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/AnvilHammerItem.java @@ -17,6 +17,7 @@ import dev.dubhe.anvilcraft.mixin.invoker.BlockBehaviourInvoker; import dev.dubhe.anvilcraft.network.RocketJumpPacket; import dev.dubhe.anvilcraft.util.BreakBlockUtil; +import dev.dubhe.anvilcraft.util.EntityUtil; import dev.dubhe.anvilcraft.util.InfiniteFluidTankBreakProtection; import dev.dubhe.anvilcraft.util.MultiPartBlockUtil; import dev.dubhe.anvilcraft.util.TriggerUtil; @@ -84,7 +85,7 @@ public class AnvilHammerItem extends Item { public static boolean goggleEnabled = false; static { - IS_WEARING_PREDICATES.add(player -> player.getItemBySlot(EquipmentSlot.HEAD).getItem() instanceof AnvilHammerItem); + AnvilHammerItem.IS_WEARING_PREDICATES.add(player -> player.getItemBySlot(EquipmentSlot.HEAD).getItem() instanceof AnvilHammerItem); } private final ItemAttributeModifiers modifiers; @@ -102,11 +103,11 @@ public AnvilHammerItem(Item.Properties properties) { ); this.modifiers = ItemAttributeModifiers.builder().add( Attributes.ATTACK_DAMAGE, new AttributeModifier( - BASE_ATTACK_DAMAGE_ID, this.getAttackDamageModifierAmount(), + Item.BASE_ATTACK_DAMAGE_ID, this.getAttackDamageModifierAmount(), AttributeModifier.Operation.ADD_VALUE ), EquipmentSlotGroup.MAINHAND ).add( - Attributes.ATTACK_SPEED, new AttributeModifier(BASE_ATTACK_SPEED_ID, -3F, AttributeModifier.Operation.ADD_VALUE), + Attributes.ATTACK_SPEED, new AttributeModifier(Item.BASE_ATTACK_SPEED_ID, -3F, AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND ).build(); } @@ -159,7 +160,7 @@ public static Property findModifyableProperty(BlockState state) { if (result != null) { return result; } - for (Property supportedProperty : SUPPORTED_PROPERTIES) { + for (Property supportedProperty : AnvilHammerItem.SUPPORTED_PROPERTIES) { if (state.hasProperty(supportedProperty)) { return supportedProperty; } @@ -189,7 +190,7 @@ public static boolean dropAnvil(@Nullable Player player, Level level, BlockPos b public static void openPortableAnvil(Player player, int inventorySlot) { if (!(player instanceof ServerPlayer serverPlayer)) return; OpenedHammerSource source = OpenedHammerSource.fromInventory(serverPlayer.getInventory(), inventorySlot); - openPortableAnvil(serverPlayer, source); + AnvilHammerItem.openPortableAnvil(serverPlayer, source); } private static void openPortableAnvil(ServerPlayer serverPlayer, @Nullable OpenedHammerSource source) { @@ -199,7 +200,7 @@ private static void openPortableAnvil(ServerPlayer serverPlayer, @Nullable Opene serverPlayer.closeContainer(); } MenuProvider provider = new SimpleMenuProvider( - (id, playerInventory, menuPlayer) -> createPortableAnvilMenu(id, playerInventory, source), + (id, playerInventory, menuPlayer) -> AnvilHammerItem.createPortableAnvilMenu(id, playerInventory, source), Component.translatable("container.repair") ); ModMenuTypes.open(serverPlayer, provider); @@ -211,7 +212,7 @@ public static void openPortableAnvilFromMenuSlot(Player player, int menuSlotId) if (menuSlotId < 0 || menuSlotId >= serverPlayer.containerMenu.slots.size()) return; Slot slot = serverPlayer.containerMenu.getSlot(menuSlotId); OpenedHammerSource source = OpenedHammerSource.fromMenuSlot(slot, serverPlayer.getInventory()); - openPortableAnvil(serverPlayer, source); + AnvilHammerItem.openPortableAnvil(serverPlayer, source); } private static AbstractContainerMenu createPortableAnvilMenu( @@ -240,16 +241,16 @@ public static void useBlock( ServerPlayer player, BlockPos blockPos, ServerLevel level, ItemStack anvilHammer, InteractionHand hand, BlockHitResult result ) { - if (rocketJump(player, level, result)) return; + if (AnvilHammerItem.rocketJump(player, level, result)) return; if (!level.mayInteract(player, blockPos)) return; if (!player.getAbilities().mayBuild) return; if (player.isShiftKeyDown()) { TriggerUtil.anvilHammerClickBlock(level, blockPos, "shift_right_click"); - breakBlock(player, blockPos, level, anvilHammer); + AnvilHammerItem.breakBlock(player, blockPos, level, anvilHammer); return; } TriggerUtil.anvilHammerClickBlock(level, blockPos, "right_click"); - if (interactWithBlock(player, blockPos, level, anvilHammer, hand, result)) return; + if (AnvilHammerItem.interactWithBlock(player, blockPos, level, anvilHammer, hand, result)) return; HammerManager.getChange(level.getBlockState(blockPos).getBlock()).change(player, blockPos, level, anvilHammer); } @@ -286,14 +287,14 @@ public ItemStack finishUsingItem(ItemStack stack, Level level, LivingEntity livi int slot = player.getUsedItemHand() == InteractionHand.MAIN_HAND ? player.getInventory().getSelectedSlot() : Inventory.SLOT_OFFHAND; - openPortableAnvil(player, slot); + AnvilHammerItem.openPortableAnvil(player, slot); } return stack; } @Override public int getUseDuration(ItemStack stack, LivingEntity entity) { - return PORTABLE_ANVIL_USE_TICKS; + return AnvilHammerItem.PORTABLE_ANVIL_USE_TICKS; } @Override @@ -338,7 +339,7 @@ public static boolean canRocketJump(@Nullable Player player) { } public static void addIsWearingPredicate(Predicate predicate) { - IS_WEARING_PREDICATES.add(predicate); + AnvilHammerItem.IS_WEARING_PREDICATES.add(predicate); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") @@ -396,8 +397,7 @@ public void hurtEnemy(ItemStack stack, LivingEntity target, LivingEntity attacke if (level instanceof ServerLevel serverLevel) { EnchantmentHelper.modifyFallBasedDamage(serverLevel, stack, attacker, level.damageSources().anvil(attacker), damageBonus); } - // noinspection deprecation - target.hurtOrSimulate(target.level().damageSources().anvil(attacker), damageBonus); + EntityUtil.hurtOrSimulate(target, target.level().damageSources().anvil(attacker), damageBonus); if (attacker.fallDistance >= 3) { attacker.level().playSound( null, diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/DragonRodItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/DragonRodItem.java index 95a106cf6a..9a836da953 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/DragonRodItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/DragonRodItem.java @@ -101,7 +101,7 @@ public static void devourBlock( if (centerState.is(ModBlockTags.DEVOUR_BLACKLIST)) return; if (centerState.getDestroySpeed(level, centerPos) < 0.0F) return; ItemStack dragonRod = player.getItemInHand(hand); - if (!canDevour(player, dragonRod)) return; + if (!DragonRodItem.canDevour(player, dragonRod)) return; int range = dragonRod.getOrDefault(ModComponents.DEVOUR_RANGE, DevourRange.THREE).getRange(); range = (range - 1) / 2; @@ -204,18 +204,18 @@ public static void devourBlock( if (dragonRod.is(ModItems.TRANSCENDENCE_DRAGON_ROD)) { long currentTick = level.getGameTime(); - Long lastTick = LAST_TRANSCENDENCE_DEVOUR_TICK.put(player.getUUID(), currentTick); + Long lastTick = DragonRodItem.LAST_TRANSCENDENCE_DEVOUR_TICK.put(player.getUUID(), currentTick); boolean warmedUp = lastTick != null && currentTick - lastTick < 15; player.getCooldowns().addCooldown(DragonRodItem.COOLDOWN_GROUP, warmedUp ? 0 : 10); if (warmedUp) { - CONTINUOUS_DEVOUR_PLAYERS.add(player.getUUID()); + DragonRodItem.CONTINUOUS_DEVOUR_PLAYERS.add(player.getUUID()); } } else { - player.getCooldowns().addCooldown(DragonRodItem.COOLDOWN_GROUP, calculateCooldown(player, dragonRod)); + player.getCooldowns().addCooldown(DragonRodItem.COOLDOWN_GROUP, DragonRodItem.calculateCooldown(player, dragonRod)); } dragonRod.hurtAndBreak( - calculateDamage(dragonRod), level, player, item -> { + DragonRodItem.calculateDamage(dragonRod), level, player, item -> { player.onEquippedItemBroken(item, hand.asEquipmentSlot()); EventHooks.onPlayerDestroyItem(player, dragonRod, hand); } @@ -251,12 +251,12 @@ public static int calculateCooldown(Player player, ItemStack dragonRod) { } public static void stopContinuousMode(Player player) { - CONTINUOUS_DEVOUR_PLAYERS.remove(player.getUUID()); + DragonRodItem.CONTINUOUS_DEVOUR_PLAYERS.remove(player.getUUID()); } public static void tickContinuousDevour(ServerPlayer player) { UUID playerId = player.getUUID(); - if (!CONTINUOUS_DEVOUR_PLAYERS.contains(playerId)) return; + if (!DragonRodItem.CONTINUOUS_DEVOUR_PLAYERS.contains(playerId)) return; ItemStack rod = player.getMainHandItem(); InteractionHand hand = InteractionHand.MAIN_HAND; @@ -264,12 +264,12 @@ public static void tickContinuousDevour(ServerPlayer player) { rod = player.getOffhandItem(); hand = InteractionHand.OFF_HAND; if (!rod.is(ModItems.TRANSCENDENCE_DRAGON_ROD)) { - CONTINUOUS_DEVOUR_PLAYERS.remove(playerId); + DragonRodItem.CONTINUOUS_DEVOUR_PLAYERS.remove(playerId); return; } } - if (!canDevour(player, rod)) { - CONTINUOUS_DEVOUR_PLAYERS.remove(playerId); + if (!DragonRodItem.canDevour(player, rod)) { + DragonRodItem.CONTINUOUS_DEVOUR_PLAYERS.remove(playerId); return; } HitResult hit = player.pick(player.blockInteractionRange(), 0.0F, false); @@ -278,6 +278,6 @@ public static void tickContinuousDevour(ServerPlayer player) { ServerLevel level = player.level(); BlockState targetState = level.getBlockState(targetPos); if (targetState.isAir() || !BlockDevourerBlock.canDevour(targetState)) return; - devourBlock(level, player, hand, targetPos, targetState, blockHit.getDirection()); + DragonRodItem.devourBlock(level, player, hand, targetPos, targetState, blockHit.getDirection()); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/HeavyHalberdItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/HeavyHalberdItem.java index ab1d233766..692b43d4cd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/HeavyHalberdItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/HeavyHalberdItem.java @@ -1,5 +1,6 @@ package dev.dubhe.anvilcraft.item.tool; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.entity.ThrownHeavyHalberdEntity; import dev.dubhe.anvilcraft.init.enchantment.ModEnchantmentTags; import dev.dubhe.anvilcraft.init.item.ModComponents; @@ -70,7 +71,7 @@ import java.util.Iterator; import java.util.function.Consumer; -public abstract class HeavyHalberdItem extends Item implements ProjectileItem { +public abstract class HeavyHalberdItem extends Item implements ProjectileItem, IItemTooltipProvider { private final ToolMaterial material; private final float attackDamage; @@ -261,14 +262,13 @@ public void inventoryTick(ItemStack stack, ServerLevel level, Entity owner, @Nul } @Override - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); builder.accept(Component.translatable( "tooltip.anvilcraft.heavy_halberd.desc", Component.keybind("key.anvilcraft.switch_tool_mode") diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/MultitoolItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/MultitoolItem.java index 4e4223052d..34619c1977 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/MultitoolItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/MultitoolItem.java @@ -2,6 +2,7 @@ import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.init.item.ModItems; +import dev.dubhe.anvilcraft.util.EntityUtil; import dev.dubhe.anvilcraft.util.MagnetUtil; import dev.dubhe.anvilcraft.util.Util; import net.minecraft.advancements.CriteriaTriggers; @@ -114,8 +115,7 @@ public InteractionResult use(Level level, Player player, InteractionHand usedHan case CARROT_ON_A_STICK -> this.useAsCarrotOnAStick(level, player, usedHand); case WARPED_FUNGUS_ON_A_STICK -> this.useAsWarpedFungusOnAStick(level, player, usedHand); case ALL -> { - // noinspection deprecation - player.hurtOrSimulate(level.damageSources().playerAttack(player), 1); + EntityUtil.hurtOrSimulate(player, level.damageSources().playerAttack(player), 1); yield InteractionResult.PASS; } default -> super.use(level, player, usedHand); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/ResonatorItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/ResonatorItem.java index 20a7f4614c..882dc36070 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/ResonatorItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/ResonatorItem.java @@ -1,5 +1,6 @@ package dev.dubhe.anvilcraft.item.tool; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.init.enchantment.ModEnchantmentTags; import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.init.item.ModItemTags; @@ -66,7 +67,7 @@ import java.util.function.Consumer; @Getter -public abstract class ResonatorItem extends Item { +public abstract class ResonatorItem extends Item implements IItemTooltipProvider { private final ToolMaterial material; private final float attackDamage; @@ -86,15 +87,13 @@ private boolean isTranscendence(ItemStack stack) { } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - super.appendHoverText(stack, context, display, builder, tooltipFlag); if (this.isTranscendence(stack)) { builder.accept( Component.translatable( @@ -119,12 +118,12 @@ public static ItemAttributeModifiers createAttributes(ToolMaterial material, flo .add( Attributes.ATTACK_DAMAGE, new AttributeModifier( - BASE_ATTACK_DAMAGE_ID, attackDamage + material.attackDamageBonus(), AttributeModifier.Operation.ADD_VALUE), + Item.BASE_ATTACK_DAMAGE_ID, attackDamage + material.attackDamageBonus(), AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND ) .add( Attributes.ATTACK_SPEED, - new AttributeModifier(BASE_ATTACK_SPEED_ID, attackSpeed, AttributeModifier.Operation.ADD_VALUE), + new AttributeModifier(Item.BASE_ATTACK_SPEED_ID, attackSpeed, AttributeModifier.Operation.ADD_VALUE), EquipmentSlotGroup.MAINHAND ) .build(); @@ -152,7 +151,7 @@ public static Tool createToolProperties(ToolMaterial material) { public static Tool createToolProperties(ResonateMode mode, ToolMaterial material, HolderGetter lookup) { return switch (mode) { - case AUTO -> createToolProperties(material); + case AUTO -> ResonatorItem.createToolProperties(material); case AXE -> new Tool( List.of(Tool.Rule.minesAndDrops(lookup.getOrThrow(BlockTags.MINEABLE_WITH_AXE), material.speed())), 1.0F, @@ -214,7 +213,7 @@ public static void checkTooDamaged(ToolMaterial material, ItemStack stack, Holde if (stack.has(DataComponents.ATTRIBUTE_MODIFIERS)) { ItemAttributeModifiers.Builder builder = ItemAttributeModifiers.builder(); for (ItemAttributeModifiers.Entry entry : stack.getAttributeModifiers().modifiers()) { - if (!entry.modifier().is(BASE_ATTACK_DAMAGE_ID)) { + if (!entry.modifier().is(Item.BASE_ATTACK_DAMAGE_ID)) { builder.add(entry.attribute(), entry.modifier(), entry.slot()); } } @@ -239,7 +238,7 @@ public static void checkTooDamaged(ToolMaterial material, ItemStack stack, Holde .withModifierAdded( Attributes.ATTACK_DAMAGE, new AttributeModifier( - BASE_ATTACK_DAMAGE_ID, + Item.BASE_ATTACK_DAMAGE_ID, resonator.attackDamage + material.attackDamageBonus(), AttributeModifier.Operation.ADD_VALUE ), @@ -281,7 +280,7 @@ public InteractionResult useOn(UseOnContext context) { ResonateMode mode = ResonatorItem.getMode(stack); return switch (mode) { case AUTO -> { - if (this.isTranscendence(stack) && !isTooDamagedToUse(stack)) { + if (this.isTranscendence(stack) && !ResonatorItem.isTooDamagedToUse(stack)) { Player player = context.getPlayer(); if (player != null) { player.startUsingItem(context.getHand()); @@ -446,7 +445,7 @@ public static void setMode(Player player, InteractionHand hand, ResonateMode mod resonator.set(ModComponents.RESONATE_MODE, mode); resonator.set( DataComponents.TOOL, - createToolProperties(mode, resonatorItem.getMaterial(), player.registryAccess().lookupOrThrow(Registries.BLOCK)) + ResonatorItem.createToolProperties(mode, resonatorItem.getMaterial(), player.registryAccess().lookupOrThrow(Registries.BLOCK)) ); } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/SpectralSlingshotItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/SpectralSlingshotItem.java index 700d641ec7..eaba6bd940 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/SpectralSlingshotItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/SpectralSlingshotItem.java @@ -160,8 +160,8 @@ private static float getShootingPower() { @Override public boolean releaseUsing(ItemStack stack, Level level, LivingEntity entityLiving, int timeLeft) { int i = this.getUseDuration(stack, entityLiving) - timeLeft; - float f = getPowerForTime(i, stack, entityLiving); - if (f >= 1.0F && !isCharged(stack) && tryLoadProjectiles(entityLiving, stack)) { + float f = SpectralSlingshotItem.getPowerForTime(i, stack, entityLiving); + if (f >= 1.0F && !SpectralSlingshotItem.isCharged(stack) && SpectralSlingshotItem.tryLoadProjectiles(entityLiving, stack)) { CrossbowItem.ChargingSounds sounds = this.getChargingSounds(stack); sounds.end().ifPresent( sound -> level.playSound( @@ -177,7 +177,7 @@ public boolean releaseUsing(ItemStack stack, Level level, LivingEntity entityLiv ); } int timeHeld = this.getUseDuration(stack, entityLiving) - timeLeft; - return getPowerForTime(timeHeld, stack, entityLiving) >= 1.0F && isCharged(stack); + return SpectralSlingshotItem.getPowerForTime(timeHeld, stack, entityLiving) >= 1.0F && SpectralSlingshotItem.isCharged(stack); } private static boolean tryLoadProjectiles(LivingEntity shooter, ItemStack crossbowStack) { @@ -222,7 +222,7 @@ protected void shootProjectile( double d1 = target.getZ() - shooter.getZ(); double d2 = Math.sqrt(d0 * d0 + d1 * d1); double d3 = target.getY(0.3333333333333333) - projectile.getY() + d2 * 0.2F; - vector3f = getProjectileShotVector(shooter, new Vec3(d0, d3, d1), angle); + vector3f = SpectralSlingshotItem.getProjectileShotVector(shooter, new Vec3(d0, d3, d1), angle); } else { Vec3 vec3 = shooter.getUpVector(1.0F); Quaternionf quaternionf = new Quaternionf().setAngleAxis((angle * (float) (Math.PI / 180.0)), vec3.x, vec3.y, vec3.z); @@ -231,7 +231,7 @@ protected void shootProjectile( } projectile.shoot(vector3f.x(), vector3f.y(), vector3f.z(), velocity, inaccuracy); - float f = getShotPitch(shooter.getRandom(), index); + float f = SpectralSlingshotItem.getShotPitch(shooter.getRandom(), index); shooter.level().playSound( null, shooter.getX(), @@ -307,7 +307,7 @@ public void performShooting( } private static float getShotPitch(RandomSource random, int index) { - return index == 0 ? 1.0F : getRandomShotPitch((index & 1) == 1, random); + return index == 0 ? 1.0F : SpectralSlingshotItem.getRandomShotPitch((index & 1) == 1, random); } private static float getRandomShotPitch(boolean isHighPitched, RandomSource random) { @@ -321,7 +321,8 @@ public void onUseTick(Level level, LivingEntity entity, ItemStack stack, int tic // 这个应该只用来播放音效了,所以应该不用改 if (!level.isClientSide()) { CrossbowItem.ChargingSounds sounds = this.getChargingSounds(stack); - float tickPercent = (float) (stack.getUseDuration(entity) - ticksRemaining) / getChargeDuration(stack, entity); + float tickPercent = (float) (stack.getUseDuration(entity) - ticksRemaining) / SpectralSlingshotItem.getChargeDuration( + stack, entity); if (tickPercent < 0.2F) { this.startSoundPlayed = false; this.midLoadSoundPlayed = false; @@ -355,7 +356,7 @@ public void onUseTick(Level level, LivingEntity entity, ItemStack stack, int tic )); } - if (tickPercent >= 1.0F && !isCharged(stack) && tryLoadProjectiles(entity, stack)) { + if (tickPercent >= 1.0F && !SpectralSlingshotItem.isCharged(stack) && SpectralSlingshotItem.tryLoadProjectiles(entity, stack)) { sounds.end().ifPresent( sound -> level.playSound( null, @@ -374,7 +375,7 @@ public void onUseTick(Level level, LivingEntity entity, ItemStack stack, int tic @Override public int getUseDuration(ItemStack stack, LivingEntity entity) { - return getChargeDuration(stack, entity) + 3; + return SpectralSlingshotItem.getChargeDuration(stack, entity) + 3; } public static int getChargeDuration(ItemStack stack, LivingEntity shooter) { @@ -389,11 +390,12 @@ public ItemUseAnimation getUseAnimation(ItemStack stack) { } CrossbowItem.ChargingSounds getChargingSounds(ItemStack stack) { - return EnchantmentHelper.pickHighestLevel(stack, EnchantmentEffectComponents.CROSSBOW_CHARGING_SOUNDS).orElse(DEFAULT_SOUNDS); + return EnchantmentHelper.pickHighestLevel(stack, EnchantmentEffectComponents.CROSSBOW_CHARGING_SOUNDS).orElse( + SpectralSlingshotItem.DEFAULT_SOUNDS); } private static float getPowerForTime(int timeLeft, ItemStack stack, LivingEntity shooter) { - float f = (float) timeLeft / (float) getChargeDuration(stack, shooter); + float f = (float) timeLeft / (float) SpectralSlingshotItem.getChargeDuration(stack, shooter); if (f > 1.0F) { f = 1.0F; } @@ -504,7 +506,7 @@ protected void shoot( level.addFreshEntity(projectile); // 插入的代码,预存一下里面的东西 ChargedProjectiles chargedProjectiles = weapon.get(DataComponents.CHARGED_PROJECTILES); - boolean canTakeOut = canTakeOutAmmo(weapon); + boolean canTakeOut = SpectralSlingshotItem.canTakeOutAmmo(weapon); ItemStack stack1 = ItemStack.EMPTY; if (canTakeOut && chargedProjectiles != null) stack1 = chargedProjectiles.itemCopies().getFirst().copy(); // 原版的hurtAndBreak() diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceAnvilHammerItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceAnvilHammerItem.java index 91985a2e21..8935e955f1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceAnvilHammerItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceAnvilHammerItem.java @@ -20,7 +20,7 @@ public TranscendenceAnvilHammerItem(Properties properties) { super( properties.fireResistant() .component(ModComponents.MULTIPHASE, Multiphase.create()) - .component(DataComponents.ITEM_NAME, Multiphase.firstPhaseName(NAME)) + .component(DataComponents.ITEM_NAME, Multiphase.firstPhaseName(TranscendenceAnvilHammerItem.NAME)) .component(ModComponents.ETERNAL, Eternal.DEFAULT) .component(DataComponents.UNBREAKABLE, Unit.INSTANCE) .component(ModComponents.PROVIDENCE, Unit.INSTANCE)); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceHeavyHalberdItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceHeavyHalberdItem.java index c9c642f215..55a596a1a7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceHeavyHalberdItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceHeavyHalberdItem.java @@ -25,7 +25,7 @@ public TranscendenceHeavyHalberdItem(Properties properties) { -2.4F, properties.fireResistant() .component(ModComponents.MULTIPHASE, Multiphase.create()) - .component(DataComponents.ITEM_NAME, Multiphase.firstPhaseName(NAME)) + .component(DataComponents.ITEM_NAME, Multiphase.firstPhaseName(TranscendenceHeavyHalberdItem.NAME)) .component(ModComponents.ETERNAL, Eternal.DEFAULT) .component(DataComponents.UNBREAKABLE, Unit.INSTANCE) .component(ModComponents.PROVIDENCE, Unit.INSTANCE) diff --git a/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceResonatorItem.java b/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceResonatorItem.java index b5e0bc33da..5f25633bb4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceResonatorItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/tool/trascendence/TranscendenceResonatorItem.java @@ -54,7 +54,7 @@ public TranscendenceResonatorItem(Properties properties) { -3F, properties.fireResistant() .component(ModComponents.MULTIPHASE, Multiphase.create()) - .component(DataComponents.ITEM_NAME, Multiphase.firstPhaseName(NAME)) + .component(DataComponents.ITEM_NAME, Multiphase.firstPhaseName(TranscendenceResonatorItem.NAME)) .component(ModComponents.ETERNAL, Eternal.DEFAULT) .component(DataComponents.UNBREAKABLE, Unit.INSTANCE) .component(ModComponents.PROVIDENCE, Unit.INSTANCE) @@ -65,7 +65,7 @@ public TranscendenceResonatorItem(Properties properties) { @Override public InteractionResult use(Level level, Player player, InteractionHand usedHand) { ItemStack stack = player.getItemInHand(usedHand); - if (ResonatorItem.getMode(stack) == ResonateMode.AUTO && !isTooDamagedToUse(stack)) { + if (ResonatorItem.getMode(stack) == ResonateMode.AUTO && !ResonatorItem.isTooDamagedToUse(stack)) { return InteractionResult.FAIL; } return super.use(level, player, usedHand); @@ -73,7 +73,7 @@ public InteractionResult use(Level level, Player player, InteractionHand usedHan @Override public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) { - if (ResonatorItem.getMode(stack) != ResonateMode.AUTO || isTooDamagedToUse(stack)) { + if (ResonatorItem.getMode(stack) != ResonateMode.AUTO || ResonatorItem.isTooDamagedToUse(stack)) { return super.onItemUseFirst(stack, context); } return this.startResonanceMining(context); @@ -82,7 +82,7 @@ public InteractionResult onItemUseFirst(ItemStack stack, UseOnContext context) { @Override public InteractionResult useOn(UseOnContext context) { ItemStack stack = context.getItemInHand(); - if (ResonatorItem.getMode(stack) != ResonateMode.AUTO || isTooDamagedToUse(stack)) { + if (ResonatorItem.getMode(stack) != ResonateMode.AUTO || ResonatorItem.isTooDamagedToUse(stack)) { return super.useOn(context); } return this.startResonanceMining(context); @@ -91,7 +91,7 @@ public InteractionResult useOn(UseOnContext context) { private InteractionResult startResonanceMining(UseOnContext context) { Level level = context.getLevel(); BlockPos pos = context.getClickedPos(); - if (!canResonanceMine(level.getBlockState(pos), level, pos)) return InteractionResult.PASS; + if (!TranscendenceResonatorItem.canResonanceMine(level.getBlockState(pos), level, pos)) return InteractionResult.PASS; Player player = context.getPlayer(); if (player == null) return InteractionResult.PASS; @@ -102,21 +102,22 @@ private InteractionResult startResonanceMining(UseOnContext context) { pos.immutable(), context.isInside() ); - MiningTarget target = new MiningTarget(hitResult, context.getHand(), getEffectPositions(level, pos)); + MiningTarget target = new MiningTarget(hitResult, context.getHand(), TranscendenceResonatorItem.getEffectPositions(level, pos)); this.miningTargets(level).put(player, target); player.startUsingItem(context.getHand()); - sendMiningEffects(level, target.effectPositions(), RESONANCE_MINING_TICKS + 2); + TranscendenceResonatorItem.sendMiningEffects( + level, target.effectPositions(), TranscendenceResonatorItem.RESONANCE_MINING_TICKS + 2); return InteractionResult.CONSUME; } @Override public int getUseDuration(ItemStack stack, LivingEntity entity) { - return USE_DURATION; + return TranscendenceResonatorItem.USE_DURATION; } @Override public ItemUseAnimation getUseAnimation(ItemStack stack) { - return getMode(stack) == ResonateMode.AUTO ? ItemUseAnimation.CROSSBOW : ItemUseAnimation.NONE; + return ResonatorItem.getMode(stack) == ResonateMode.AUTO ? ItemUseAnimation.CROSSBOW : ItemUseAnimation.NONE; } public static float resonanceMiningProgress(Level level, Player player, float partialTick) { @@ -125,7 +126,7 @@ public static float resonanceMiningProgress(Level level, Player player, float pa ItemStack stack = player.getUseItem(); int elapsedTicks = stack.getUseDuration(player) - player.getUseItemRemainingTicks(); - return Math.min(1.0F, (elapsedTicks + partialTick) / RESONANCE_MINING_TICKS); + return Math.min(1.0F, (elapsedTicks + partialTick) / TranscendenceResonatorItem.RESONANCE_MINING_TICKS); } @Override @@ -137,14 +138,14 @@ public void onUseTick(Level level, LivingEntity livingEntity, ItemStack stack, i return; } - BlockHitResult hit = getTargetedBlock(livingEntity); + BlockHitResult hit = TranscendenceResonatorItem.getTargetedBlock(livingEntity); if (hit == null || !target.hitPos().equals(hit.getBlockPos())) { this.stopResonanceMining(level, livingEntity, target); return; } BlockState state = level.getBlockState(target.hitPos()); - if (!canResonanceMine(state, level, target.hitPos())) { + if (!TranscendenceResonatorItem.canResonanceMine(state, level, target.hitPos())) { this.stopResonanceMining(level, livingEntity, target); return; } @@ -154,7 +155,7 @@ public void onUseTick(Level level, LivingEntity livingEntity, ItemStack stack, i float pitch = 0.75F + 0.04F * elapsedTicks; level.playSound(null, target.hitPos(), SoundEvents.AMETHYST_BLOCK_RESONATE, SoundSource.BLOCKS, 0.8F, pitch); } - if (elapsedTicks < RESONANCE_MINING_TICKS) return; + if (elapsedTicks < TranscendenceResonatorItem.RESONANCE_MINING_TICKS) return; boolean destroyed = livingEntity instanceof ServerPlayer player && player.gameMode.destroyBlock(target.hitPos()); @@ -162,7 +163,7 @@ public void onUseTick(Level level, LivingEntity livingEntity, ItemStack stack, i if (destroyed) { level.playSound(null, target.hitPos(), SoundEvents.AMETHYST_CLUSTER_BREAK, SoundSource.BLOCKS, 1.0F, 0.7F); } - sendMiningEffects(level, target.effectPositions(), 0); + TranscendenceResonatorItem.sendMiningEffects(level, target.effectPositions(), 0); livingEntity.stopUsingItem(); } @@ -171,11 +172,13 @@ public boolean releaseUsing(ItemStack stack, Level level, LivingEntity livingEnt MiningTarget target = this.miningTargets(level).remove(livingEntity); if (target == null) return false; - sendMiningEffects(level, target.effectPositions(), 0); + TranscendenceResonatorItem.sendMiningEffects(level, target.effectPositions(), 0); int elapsedTicks = this.getUseDuration(stack, livingEntity) - remainingUseDuration; - if (elapsedTicks >= RESONANCE_MINING_TICKS || !(livingEntity instanceof ServerPlayer player)) return true; + if (elapsedTicks >= TranscendenceResonatorItem.RESONANCE_MINING_TICKS || !(livingEntity instanceof ServerPlayer player)) { + return true; + } - BlockHitResult hit = getTargetedBlock(player); + BlockHitResult hit = TranscendenceResonatorItem.getTargetedBlock(player); if (hit == null || !target.hitPos().equals(hit.getBlockPos())) return true; AnvilHammerItem.useBlock(player, target.hitPos(), player.level(), stack, target.hand(), target.hitResult()); return true; @@ -193,7 +196,7 @@ public static boolean isResonanceMining(Level level, Player player, BlockPos pos private void stopResonanceMining(Level level, LivingEntity livingEntity, MiningTarget target) { this.miningTargets(level).remove(livingEntity); - sendMiningEffects(level, target.effectPositions(), 0); + TranscendenceResonatorItem.sendMiningEffects(level, target.effectPositions(), 0); livingEntity.stopUsingItem(); } @@ -203,7 +206,7 @@ private static List getEffectPositions(Level level, BlockPos hitPos) { if (!(state.getBlock() instanceof AbstractMultiPartBlock multiPartBlock)) { return List.of(hitPos.immutable()); } - return getMultiPartEffectPositions(level, hitPos, state, multiPartBlock); + return TranscendenceResonatorItem.getMultiPartEffectPositions(level, hitPos, state, multiPartBlock); } private static

> List getMultiPartEffectPositions( @@ -222,7 +225,7 @@ private static

> List getMultiPartEffectPositions( private static void sendMiningEffects(Level level, List positions, int durationTicks) { for (BlockPos pos : positions) { - sendMiningEffect(level, pos, durationTicks); + TranscendenceResonatorItem.sendMiningEffect(level, pos, durationTicks); } } @@ -241,6 +244,7 @@ private static void sendMiningEffect(Level level, BlockPos pos, int durationTick return hit.getType() == HitResult.Type.BLOCK ? (BlockHitResult) hit : null; } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") private static boolean canResonanceMine(BlockState state, Level level, BlockPos pos) { if (state.isAir()) return false; return state.getDestroySpeed(level, pos) >= 0.0F; diff --git a/src/main/java/dev/dubhe/anvilcraft/item/utility/CrabClawItem.java b/src/main/java/dev/dubhe/anvilcraft/item/utility/CrabClawItem.java index ef4dd5ae19..be0339e3b1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/utility/CrabClawItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/utility/CrabClawItem.java @@ -28,15 +28,15 @@ public class CrabClawItem extends Item { AttributeModifier.Operation.ADD_VALUE ); private static final Supplier, AttributeModifier>> RANGE_MODIFIER_SUPPLIER = - EntityReachAttribute.getRangeModifierSupplier(RANGE_ATTRIBUTE_MODIFIER); + EntityReachAttribute.getRangeModifierSupplier(CrabClawItem.RANGE_ATTRIBUTE_MODIFIER); public static final String CRAB_CLAW_MARKER = "crabClaw"; public static final String DUAL_CRAB_CLAW_MARKER = "dualCrabClaw"; public CrabClawItem(Properties properties) { super(properties.attributes( ItemAttributeModifiers.builder() - .add(Attributes.BLOCK_INTERACTION_RANGE, RANGE_ATTRIBUTE_MODIFIER, EquipmentSlotGroup.HAND) - .add(Attributes.ENTITY_INTERACTION_RANGE, RANGE_ATTRIBUTE_MODIFIER, EquipmentSlotGroup.HAND) + .add(Attributes.BLOCK_INTERACTION_RANGE, CrabClawItem.RANGE_ATTRIBUTE_MODIFIER, EquipmentSlotGroup.HAND) + .add(Attributes.ENTITY_INTERACTION_RANGE, CrabClawItem.RANGE_ATTRIBUTE_MODIFIER, EquipmentSlotGroup.HAND) .build() )); } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/utility/DiskItem.java b/src/main/java/dev/dubhe/anvilcraft/item/utility/DiskItem.java index ff36e9305b..774eaab892 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/utility/DiskItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/utility/DiskItem.java @@ -1,6 +1,7 @@ package dev.dubhe.anvilcraft.item.utility; import dev.dubhe.anvilcraft.api.item.IDiskCloneable; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.item.property.component.DiskData; import lombok.extern.slf4j.Slf4j; @@ -30,14 +31,14 @@ import java.util.function.Consumer; @Slf4j -public class DiskItem extends Item { +public class DiskItem extends Item implements IItemTooltipProvider { private static final String MESSAGE_PREFIX = "message.anvilcraft.disk."; private static final Component TOOLTIP_STORE = Component.translatable("tooltip.anvilcraft.item.disk.store") .withStyle(ChatFormatting.GRAY); - private static final Component MESSAGE_STORED = message("data_stored"); - private static final Component MESSAGE_CLEARED = message("data_cleared"); - private static final Component MESSAGE_APPLIED = message("data_applied"); - private static final Component MESSAGE_INCOMPATIBLE = messageFailed("data_incompatible"); + private static final Component MESSAGE_STORED = DiskItem.message("data_stored"); + private static final Component MESSAGE_CLEARED = DiskItem.message("data_cleared"); + private static final Component MESSAGE_APPLIED = DiskItem.message("data_applied"); + private static final Component MESSAGE_INCOMPATIBLE = DiskItem.messageFailed("data_incompatible"); public DiskItem(Properties properties) { super(properties); @@ -58,19 +59,18 @@ public static void deleteData(ItemStack stack) { @Override public boolean isFoil(ItemStack stack) { - return hasDataStored(stack); + return DiskItem.hasDataStored(stack); } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer builder, TooltipFlag tooltipFlag ) { - if (!hasDataStored(stack)) builder.accept(TOOLTIP_STORE); + if (!DiskItem.hasDataStored(stack)) builder.accept(DiskItem.TOOLTIP_STORE); } @Override @@ -84,27 +84,28 @@ public InteractionResult useOn(UseOnContext context) { BlockEntity blockEntity = level.getBlockEntity(clickedPos); if (!(blockEntity instanceof IDiskCloneable diskCloneable)) return InteractionResult.PASS; ItemStack stack = context.getItemInHand(); - if (hasDataStored(stack)) { + if (DiskItem.hasDataStored(stack)) { CompoundTag tag = stack.getOrDefault(ModComponents.DISK_DATA, new DiskData(new CompoundTag())).tag(); - if (!isCompatible(tag, blockEntity, diskCloneable)) { - player.sendOverlayMessage(MESSAGE_INCOMPATIBLE); + if (!DiskItem.isCompatible(tag, blockEntity, diskCloneable)) { + player.sendOverlayMessage(DiskItem.MESSAGE_INCOMPATIBLE); return InteractionResult.FAIL; } ValueInput input = TagValueInput.create( - new ProblemReporter.ScopedCollector(log), + new ProblemReporter.ScopedCollector(DiskItem.log), level.registryAccess(), tag ); diskCloneable.applyDiskData(input); - player.sendOverlayMessage(MESSAGE_APPLIED); + player.sendOverlayMessage(DiskItem.MESSAGE_APPLIED); } else { - TagValueOutput output = TagValueOutput.createWithContext(new ProblemReporter.ScopedCollector(log), level.registryAccess()); + TagValueOutput output = TagValueOutput.createWithContext( + new ProblemReporter.ScopedCollector(DiskItem.log), level.registryAccess()); output.store("StoredFrom", BuiltInRegistries.BLOCK_ENTITY_TYPE.byNameCodec(), blockEntity.getType()); diskCloneable.storeDiskData(output); CompoundTag tag = output.buildResult(); - saveCompatibleGroups(tag, diskCloneable.getDiskCompatibleGroups()); + DiskItem.saveCompatibleGroups(tag, diskCloneable.getDiskCompatibleGroups()); stack.set(ModComponents.DISK_DATA, new DiskData(tag)); - player.sendOverlayMessage(MESSAGE_STORED); + player.sendOverlayMessage(DiskItem.MESSAGE_STORED); } return InteractionResult.SUCCESS; } @@ -125,9 +126,9 @@ public InteractionResult use( ) { if (!level.isClientSide() && player.isShiftKeyDown()) { ItemStack itemStack = player.getItemInHand(usedHand); - if (hasDataStored(itemStack)) { - deleteData(itemStack); - player.sendOverlayMessage(MESSAGE_CLEARED); + if (DiskItem.hasDataStored(itemStack)) { + DiskItem.deleteData(itemStack); + player.sendOverlayMessage(DiskItem.MESSAGE_CLEARED); return InteractionResult.SUCCESS; } } @@ -135,12 +136,12 @@ public InteractionResult use( } private static Component message(String suffix) { - return Component.translatable(MESSAGE_PREFIX + suffix); + return Component.translatable(DiskItem.MESSAGE_PREFIX + suffix); } @SuppressWarnings("SameParameterValue") private static Component messageFailed(String suffix) { - return Component.translatable(MESSAGE_PREFIX + suffix) + return Component.translatable(DiskItem.MESSAGE_PREFIX + suffix) .withStyle(ChatFormatting.RED); } @@ -148,23 +149,23 @@ public static void onBlockPlaced(BlockEvent.EntityPlaceEvent event) { if (event.getLevel().isClientSide()) return; if (!(event.getEntity() instanceof Player player)) return; ItemStack offhand = player.getOffhandItem(); - if (!(offhand.getItem() instanceof DiskItem) || !hasDataStored(offhand)) return; + if (!(offhand.getItem() instanceof DiskItem) || !DiskItem.hasDataStored(offhand)) return; BlockPos pos = event.getPos(); Level level = (Level) event.getLevel(); BlockEntity blockEntity = level.getBlockEntity(pos); if (!(blockEntity instanceof IDiskCloneable diskCloneable)) return; - CompoundTag tag = getData(offhand); - if (!isCompatible(tag, blockEntity, diskCloneable)) { - player.sendOverlayMessage(MESSAGE_INCOMPATIBLE); + CompoundTag tag = DiskItem.getData(offhand); + if (!DiskItem.isCompatible(tag, blockEntity, diskCloneable)) { + player.sendOverlayMessage(DiskItem.MESSAGE_INCOMPATIBLE); return; } ValueInput input = TagValueInput.create( - new ProblemReporter.ScopedCollector(log), + new ProblemReporter.ScopedCollector(DiskItem.log), level.registryAccess(), tag ); diskCloneable.applyDiskData(input); - player.sendOverlayMessage(MESSAGE_APPLIED); + player.sendOverlayMessage(DiskItem.MESSAGE_APPLIED); } private static void saveCompatibleGroups(CompoundTag tag, List groups) { @@ -195,12 +196,14 @@ private static List loadCompatibleGroups(CompoundTag tag) { .toList(); } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") private static boolean isCompatible(CompoundTag tag, BlockEntity blockEntity, IDiskCloneable diskCloneable) { String storedFrom = tag.getStringOr("StoredFrom", ""); - String targetType = BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(blockEntity.getType()).toString(); - if (storedFrom.equals(targetType)) return true; + var targetType = BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(blockEntity.getType()); + if (targetType == null) return false; + if (storedFrom.equals(targetType.toString())) return true; - List storedGroups = loadCompatibleGroups(tag); + List storedGroups = DiskItem.loadCompatibleGroups(tag); if (storedGroups.isEmpty()) return false; List targetGroups = diskCloneable.getDiskCompatibleGroups(); return storedGroups.stream().anyMatch(targetGroups::contains); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/utility/GuideBookItem.java b/src/main/java/dev/dubhe/anvilcraft/item/utility/GuideBookItem.java index d0bdc6fde5..d5b3a5bb03 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/utility/GuideBookItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/utility/GuideBookItem.java @@ -1,6 +1,7 @@ package dev.dubhe.anvilcraft.item.utility; import dev.dubhe.anvilcraft.api.thought.Thinkable; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.integration.IntegrationUtil; import dev.dubhe.anvilcraft.network.OpenIntegrationScreenPacket; import dev.dubhe.anvilcraft.util.ModEventUtil; @@ -17,7 +18,7 @@ import java.util.function.Consumer; -public class GuideBookItem extends Item implements Thinkable { +public class GuideBookItem extends Item implements Thinkable, IItemTooltipProvider { public GuideBookItem(Properties properties) { super(properties); } @@ -36,15 +37,13 @@ public InteractionResult use(Level level, Player player, InteractionHand usedHan } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, Consumer consumer, TooltipFlag flag ) { - super.appendHoverText(stack, context, display, consumer, flag); this.appendHoverText(consumer); } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/utility/IonoCraftItem.java b/src/main/java/dev/dubhe/anvilcraft/item/utility/IonoCraftItem.java index 7238d1619c..9432fedf90 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/utility/IonoCraftItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/utility/IonoCraftItem.java @@ -30,14 +30,14 @@ public IonoCraftItem(Properties properties) { @Override public InteractionResult use(Level level, Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); - HitResult hitresult = getPlayerPOVHitResult(level, player, ClipContext.Fluid.ANY); + HitResult hitresult = Item.getPlayerPOVHitResult(level, player, ClipContext.Fluid.ANY); if (hitresult.getType() == HitResult.Type.MISS) { return InteractionResult.PASS; } else { Vec3 vec3 = player.getViewVector(1.0F); List list = level.getEntities( player, - player.getBoundingBox().expandTowards(vec3.scale(5.0)).inflate(1.0), ENTITY_PREDICATE + player.getBoundingBox().expandTowards(vec3.scale(5.0)).inflate(1.0), IonoCraftItem.ENTITY_PREDICATE ); if (!list.isEmpty()) { Vec3 vec31 = player.getEyePosition(); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/utility/PillBoxItem.java b/src/main/java/dev/dubhe/anvilcraft/item/utility/PillBoxItem.java index 0f5c630172..a800d02516 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/utility/PillBoxItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/utility/PillBoxItem.java @@ -27,7 +27,7 @@ public PillBoxItem(Properties properties) { @Override public InteractionResult use(Level level, Player player, InteractionHand usedHand) { ItemStack itemStack = player.getItemInHand(usedHand); - return use(itemStack, player); + return PillBoxItem.use(itemStack, player); } public static InteractionResult use(ItemStack pillBox, Player player) { diff --git a/src/main/java/dev/dubhe/anvilcraft/item/utility/StructureToolItem.java b/src/main/java/dev/dubhe/anvilcraft/item/utility/StructureToolItem.java index 6447b2058f..2fb363c683 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/utility/StructureToolItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/utility/StructureToolItem.java @@ -4,6 +4,7 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import dev.dubhe.anvilcraft.api.tooltip.TooltipRenderHelper; import dev.dubhe.anvilcraft.api.tooltip.providers.IHandHeldItemTooltipProvider; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.init.ModMenuTypes; import dev.dubhe.anvilcraft.init.item.ModComponents; import dev.dubhe.anvilcraft.inventory.StructureToolMenu; @@ -32,7 +33,7 @@ import java.util.function.Consumer; -public class StructureToolItem extends Item implements IHandHeldItemTooltipProvider { +public class StructureToolItem extends Item implements IHandHeldItemTooltipProvider, IItemTooltipProvider { public StructureToolItem(Properties properties) { super(properties); } @@ -117,8 +118,7 @@ public InteractionResult use(Level level, Player player, InteractionHand usedHan } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, TooltipContext context, TooltipDisplay display, @@ -131,11 +131,11 @@ public void appendHoverText( "tooltip.anvilcraft.item.structure_tool.min_pos", data.minX(), data.minY(), data.minZ())); builder.accept(Component.translatable( "tooltip.anvilcraft.item.structure_tool.max_pos", data.maxX(), data.maxY(), data.maxZ())); - builder.accept(SHIFT_TO_CLEAR_TOOLTIP); + builder.accept(StructureToolItem.SHIFT_TO_CLEAR_TOOLTIP); } else { - builder.accept(DEVELOPER_TOOLTIP); - builder.accept(SELECT_TOOLTIP); - builder.accept(INPUT_TOOLTIP); + builder.accept(StructureToolItem.DEVELOPER_TOOLTIP); + builder.accept(StructureToolItem.SELECT_TOOLTIP); + builder.accept(StructureToolItem.INPUT_TOOLTIP); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/weapon/AnvilRailgunItem.java b/src/main/java/dev/dubhe/anvilcraft/item/weapon/AnvilRailgunItem.java index 8565d67c89..6a80d5792d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/weapon/AnvilRailgunItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/weapon/AnvilRailgunItem.java @@ -1,5 +1,6 @@ package dev.dubhe.anvilcraft.item.weapon; +import dev.dubhe.anvilcraft.api.tooltip.providers.IItemTooltipProvider; import dev.dubhe.anvilcraft.entity.RailgunAnvilEntity; import dev.dubhe.anvilcraft.init.block.ModBlocks; import dev.dubhe.anvilcraft.init.item.ModComponents; @@ -9,6 +10,7 @@ import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; @@ -36,7 +38,7 @@ import java.util.List; import java.util.function.Consumer; -public class AnvilRailgunItem extends EnergyWeaponItem { +public class AnvilRailgunItem extends EnergyWeaponItem implements IItemTooltipProvider { private static final int MAX_AMMO = 16; private static final int MIN_SHOT_ENERGY = 2_000_000; private static final float MIN_FIRE_CHARGE_PROGRESS = 0.2F; @@ -48,10 +50,10 @@ public AnvilRailgunItem(Properties properties) { @Override public InteractionResult use(Level level, Player player, InteractionHand hand) { ItemStack weapon = player.getItemInHand(hand); - if (!this.canStartUsing(player, weapon, MIN_SHOT_ENERGY)) return InteractionResult.FAIL; - if (ammo(weapon).isEmpty() - && !isValidAnvil(otherHand(player, hand)) - && findNormalAnvil(player) < 0 + if (!this.canStartUsing(player, weapon, AnvilRailgunItem.MIN_SHOT_ENERGY)) return InteractionResult.FAIL; + if (AnvilRailgunItem.ammo(weapon).isEmpty() + && !AnvilRailgunItem.isValidAnvil(AnvilRailgunItem.otherHand(player, hand)) + && AnvilRailgunItem.findNormalAnvil(player) < 0 ) { return InteractionResult.FAIL; } @@ -61,12 +63,12 @@ && findNormalAnvil(player) < 0 @Override public void onUseTick(Level level, LivingEntity user, ItemStack weapon, int remaining) { - if (!(user instanceof ServerPlayer player) || isLoading(player, weapon, player.getUsedItemHand())) return; + if (!(user instanceof ServerPlayer player) || AnvilRailgunItem.isLoading(player, weapon, player.getUsedItemHand())) return; int elapsed = this.getUseDuration(weapon, user) - remaining; - int fullTicks = fullChargeTicks(level, weapon); + int fullTicks = AnvilRailgunItem.fullChargeTicks(level, weapon); if (elapsed > 0 && elapsed % fullTicks == 0) { this.fire((ServerLevel) level, player, weapon, 1.0F); - if (ammo(weapon).isEmpty()) player.releaseUsingItem(); + if (AnvilRailgunItem.ammo(weapon).isEmpty()) player.releaseUsingItem(); } } @@ -75,43 +77,43 @@ public boolean releaseUsing(ItemStack weapon, Level level, LivingEntity user, in if (!(user instanceof ServerPlayer player) || !(level instanceof ServerLevel serverLevel)) return false; int elapsed = this.getUseDuration(weapon, user) - remaining; InteractionHand hand = player.getUsedItemHand(); - if (isLoading(player, weapon, hand)) { - if (elapsed >= loadTicks(level, weapon)) load(player, weapon, hand); + if (AnvilRailgunItem.isLoading(player, weapon, hand)) { + if (elapsed >= AnvilRailgunItem.loadTicks(level, weapon)) AnvilRailgunItem.load(player, weapon, hand); return false; } - float progress = chargeProgress(level, weapon, elapsed, 0.0F); - if (progress >= MIN_FIRE_CHARGE_PROGRESS) this.fire(serverLevel, player, weapon, progress); + float progress = AnvilRailgunItem.chargeProgress(level, weapon, elapsed, 0.0F); + if (progress >= AnvilRailgunItem.MIN_FIRE_CHARGE_PROGRESS) this.fire(serverLevel, player, weapon, progress); return false; } public static boolean isLoading(Player player, ItemStack weapon, InteractionHand hand) { - List ammo = ammo(weapon); - if (ammo.size() >= MAX_AMMO) return false; - ItemStack supplied = otherHand(player, hand); - if (ammo.isEmpty()) return isValidAnvil(supplied) || findNormalAnvil(player) >= 0; - return isValidAnvil(supplied) && ItemStack.isSameItemSameComponents(ammo.getFirst(), supplied); + List ammo = AnvilRailgunItem.ammo(weapon); + if (ammo.size() >= AnvilRailgunItem.MAX_AMMO) return false; + ItemStack supplied = AnvilRailgunItem.otherHand(player, hand); + if (ammo.isEmpty()) return AnvilRailgunItem.isValidAnvil(supplied) || AnvilRailgunItem.findNormalAnvil(player) >= 0; + return AnvilRailgunItem.isValidAnvil(supplied) && ItemStack.isSameItemSameComponents(ammo.getFirst(), supplied); } private static void load(ServerPlayer player, ItemStack weapon, InteractionHand hand) { - List loaded = new ArrayList<>(ammo(weapon)); - ItemStack source = otherHand(player, hand); + List loaded = new ArrayList<>(AnvilRailgunItem.ammo(weapon)); + ItemStack source = AnvilRailgunItem.otherHand(player, hand); int inventorySlot = -1; - if (!isValidAnvil(source)) { - inventorySlot = findNormalAnvil(player); + if (!AnvilRailgunItem.isValidAnvil(source)) { + inventorySlot = AnvilRailgunItem.findNormalAnvil(player); if (inventorySlot < 0) return; source = player.getInventory().getItem(inventorySlot); } - boolean infinity = enchantmentLevel(player.level(), weapon, Enchantments.INFINITY) > 0 + boolean infinity = AnvilRailgunItem.enchantmentLevel(player.level(), weapon, Enchantments.INFINITY) > 0 && source.is(Items.ANVIL); int amount = infinity - ? MAX_AMMO - loaded.size() - : Math.min(source.getCount(), MAX_AMMO - loaded.size()); - int infiniteAmmoMask = infiniteAmmoMask(weapon, loaded.size()); + ? AnvilRailgunItem.MAX_AMMO - loaded.size() + : Math.min(source.getCount(), AnvilRailgunItem.MAX_AMMO - loaded.size()); + int infiniteAmmoMask = AnvilRailgunItem.infiniteAmmoMask(weapon, loaded.size()); for (int i = 0; i < amount; i++) loaded.add(source.copyWithCount(1)); - if (infinity) infiniteAmmoMask |= ammoMask(amount) << (loaded.size() - amount); + if (infinity) infiniteAmmoMask |= AnvilRailgunItem.ammoMask(amount) << (loaded.size() - amount); if (!infinity && !player.hasInfiniteMaterials()) source.shrink(amount); if (inventorySlot >= 0 && source.isEmpty()) player.getInventory().removeItem(inventorySlot, 1); - setAmmo(weapon, loaded, infiniteAmmoMask); + AnvilRailgunItem.setAmmo(weapon, loaded, infiniteAmmoMask); player.level().playSound( null, player.blockPosition(), @@ -123,27 +125,27 @@ private static void load(ServerPlayer player, ItemStack weapon, InteractionHand } private void fire(ServerLevel level, ServerPlayer player, ItemStack weapon, float progress) { - List loaded = new ArrayList<>(ammo(weapon)); + List loaded = new ArrayList<>(AnvilRailgunItem.ammo(weapon)); if (loaded.isEmpty()) return; int energy = Math.round(progress * 20_000_000.0F); if (!this.consumeEnergy(player, weapon, energy, 160_000_000)) return; ItemStack projectileStack = loaded.getFirst(); - boolean infinity = enchantmentLevel(level, weapon, Enchantments.INFINITY) > 0 + boolean infinity = AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.INFINITY) > 0 && projectileStack.is(Items.ANVIL); - int infiniteAmmoMask = infiniteAmmoMask(weapon, loaded.size()); + int infiniteAmmoMask = AnvilRailgunItem.infiniteAmmoMask(weapon, loaded.size()); boolean loadedByInfinity = (infiniteAmmoMask & 1) != 0; if (!infinity) { loaded.removeFirst(); infiniteAmmoMask >>>= 1; } - setAmmo(weapon, loaded, infiniteAmmoMask); + AnvilRailgunItem.setAmmo(weapon, loaded, infiniteAmmoMask); - int projectileCount = enchantmentLevel(level, weapon, Enchantments.MULTISHOT) > 0 ? 3 : 1; - int piercing = enchantmentLevel(level, weapon, Enchantments.PIERCING); - int knockback = enchantmentLevel(level, weapon, Enchantments.PUNCH); - boolean loyalty = enchantmentLevel(level, weapon, Enchantments.LOYALTY) > 0; - int power = enchantmentLevel(level, weapon, Enchantments.POWER); + int projectileCount = AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.MULTISHOT) > 0 ? 3 : 1; + int piercing = AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.PIERCING); + int knockback = AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.PUNCH); + boolean loyalty = AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.LOYALTY) > 0; + int power = AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.POWER); double speed = Math.sqrt(progress) * 8.0 * (1.0 + Math.min(10, power) * 0.1); Block block = ((BlockItem) projectileStack.getItem()).getBlock(); for (int i = 0; i < projectileCount; i++) { @@ -173,30 +175,30 @@ private void fire(ServerLevel level, ServerPlayer player, ItemStack weapon, floa } private static int loadTicks(Level level, ItemStack weapon) { - return Math.max(5, 25 - enchantmentLevel(level, weapon, Enchantments.QUICK_CHARGE) * 5); + return Math.max(5, 25 - AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.QUICK_CHARGE) * 5); } public static int fullChargeTicks(Level level, ItemStack weapon) { - return (int) Math.ceil(100.0 / chargePercentPerTick(level, weapon)); + return (int) Math.ceil(100.0 / AnvilRailgunItem.chargePercentPerTick(level, weapon)); } public static float chargeProgress(Level level, ItemStack weapon, int elapsedTicks, float partialTick) { - int fullTicks = fullChargeTicks(level, weapon); + int fullTicks = AnvilRailgunItem.fullChargeTicks(level, weapon); return Math.min( 1.0F, - ((elapsedTicks % fullTicks) + partialTick) * chargePercentPerTick(level, weapon) / 100.0F + ((elapsedTicks % fullTicks) + partialTick) * AnvilRailgunItem.chargePercentPerTick(level, weapon) / 100.0F ); } private static float chargePercentPerTick(Level level, ItemStack weapon) { - int quickCharge = enchantmentLevel(level, weapon, Enchantments.QUICK_CHARGE); + int quickCharge = AnvilRailgunItem.enchantmentLevel(level, weapon, Enchantments.QUICK_CHARGE); return Math.min(4.0F, 1.0F + quickCharge * 0.2F); } private static int enchantmentLevel( Level level, ItemStack stack, - net.minecraft.resources.ResourceKey key + ResourceKey key ) { Holder enchantment = level.holderLookup(Registries.ENCHANTMENT).getOrThrow(key); return stack.getEnchantmentLevel(enchantment); @@ -228,12 +230,12 @@ private static List ammo(ItemStack weapon) { private static void setAmmo(ItemStack weapon, List ammo, int infiniteAmmoMask) { weapon.set(ModComponents.RAILGUN_AMMO, ChargedProjectiles.ofNonEmpty(ammo)); - weapon.set(ModComponents.RAILGUN_INFINITE_AMMO_MASK, infiniteAmmoMask & ammoMask(ammo.size())); + weapon.set(ModComponents.RAILGUN_INFINITE_AMMO_MASK, infiniteAmmoMask & AnvilRailgunItem.ammoMask(ammo.size())); weapon.remove(DataComponents.CHARGED_PROJECTILES); } private static int infiniteAmmoMask(ItemStack weapon, int ammoSize) { - int validMask = ammoMask(ammoSize); + int validMask = AnvilRailgunItem.ammoMask(ammoSize); Integer stored = weapon.get(ModComponents.RAILGUN_INFINITE_AMMO_MASK); if (stored == null) { // 升级前装填的弹药视作无限弹,避免凭空生成的铁砧被回收 @@ -243,7 +245,7 @@ private static int infiniteAmmoMask(ItemStack weapon, int ammoSize) { } private static int ammoMask(int ammoSize) { - return (1 << Math.min(ammoSize, MAX_AMMO)) - 1; + return (1 << Math.min(ammoSize, AnvilRailgunItem.MAX_AMMO)) - 1; } @Override @@ -257,16 +259,14 @@ public ItemUseAnimation getUseAnimation(ItemStack stack) { } @Override - @SuppressWarnings("deprecation") - public void appendHoverText( + public void appendItemTooltip( ItemStack stack, Item.TooltipContext context, TooltipDisplay display, Consumer tooltip, TooltipFlag flag ) { - super.appendHoverText(stack, context, display, tooltip, flag); - List loaded = ammo(stack); + List loaded = AnvilRailgunItem.ammo(stack); if (!loaded.isEmpty()) { tooltip.accept(Component.translatable("item.minecraft.crossbow.projectile") .append(CommonComponents.SPACE) diff --git a/src/main/java/dev/dubhe/anvilcraft/item/weapon/CorruptedBeaconActivatorItem.java b/src/main/java/dev/dubhe/anvilcraft/item/weapon/CorruptedBeaconActivatorItem.java index 1e71891a7c..9b288bccaf 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/weapon/CorruptedBeaconActivatorItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/weapon/CorruptedBeaconActivatorItem.java @@ -29,7 +29,7 @@ public CorruptedBeaconActivatorItem(Properties properties) { @Override public InteractionResult use(Level level, Player player, InteractionHand hand) { ItemStack stack = player.getItemInHand(hand); - if (!this.canStartUsing(player, stack, ENERGY_PER_PULSE)) return InteractionResult.FAIL; + if (!this.canStartUsing(player, stack, CorruptedBeaconActivatorItem.ENERGY_PER_PULSE)) return InteractionResult.FAIL; player.startUsingItem(hand); return InteractionResult.CONSUME; } @@ -42,7 +42,7 @@ public void onUseTick(Level level, LivingEntity user, ItemStack stack, int remai level.holderLookup(Registries.ENCHANTMENT).getOrThrow(Enchantments.QUICK_CHARGE)); int period = 20 - Math.min(quickCharge, 10); boolean pulse = elapsed > 0 && elapsed % period == 0; - if (pulse && !this.consumeEnergy(player, stack, ENERGY_PER_PULSE, 160_000_000)) return; + if (pulse && !this.consumeEnergy(player, stack, CorruptedBeaconActivatorItem.ENERGY_PER_PULSE, 160_000_000)) return; WeaponRaycastUtil.Ray fullRay = WeaponRaycastUtil.ray(player, 64.0); Vec3 end = WeaponRaycastUtil.laserBlockHit(level, player, fullRay).getLocation(); diff --git a/src/main/java/dev/dubhe/anvilcraft/item/weapon/EnergyWeaponItem.java b/src/main/java/dev/dubhe/anvilcraft/item/weapon/EnergyWeaponItem.java index 76e6b23ba6..ee5e71bc49 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/weapon/EnergyWeaponItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/weapon/EnergyWeaponItem.java @@ -19,53 +19,54 @@ public abstract class EnergyWeaponItem extends Item { .withStyle(ChatFormatting.RED); protected EnergyWeaponItem(Properties properties) { - super(properties.component(ModComponents.STORED_ENERGY, new StoredEnergy(MAX_ENERGY))); + super(properties.component(ModComponents.STORED_ENERGY, new StoredEnergy(EnergyWeaponItem.MAX_ENERGY))); } protected boolean consumeEnergy(Player player, ItemStack weapon, int amount, int refillAmount) { - int energy = getEnergy(weapon); - if (energy < REFILL_THRESHOLD) { + int energy = EnergyWeaponItem.getEnergy(weapon); + if (energy < EnergyWeaponItem.REFILL_THRESHOLD) { int slot = player.getInventory().findSlotMatchingItem(ModItems.SUPER_CAPACITOR.asStack()); if (slot >= 0) { if (!player.hasInfiniteMaterials()) { player.getInventory().removeItem(slot, 1); player.getInventory().placeItemBackInInventory(ModItems.SUPER_CAPACITOR_EMPTY.asStack()); } - energy = Math.min(MAX_ENERGY, energy + refillAmount); + energy = Math.min(EnergyWeaponItem.MAX_ENERGY, energy + refillAmount); } } if (energy < amount) { - setEnergy(weapon, energy); + EnergyWeaponItem.setEnergy(weapon, energy); this.stopForInsufficientPower(player); return false; } - setEnergy(weapon, energy - amount); + EnergyWeaponItem.setEnergy(weapon, energy - amount); if (!this.hasEnergyAvailable(player, weapon, amount)) { this.stopForInsufficientPower(player); } return true; } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") protected boolean canStartUsing(Player player, ItemStack weapon, int minimumEnergy) { if (this.hasEnergyAvailable(player, weapon, minimumEnergy)) return true; - showInsufficientPower(player); + EnergyWeaponItem.showInsufficientPower(player); return false; } protected boolean hasEnergyAvailable(Player player, ItemStack weapon, int amount) { - int energy = getEnergy(weapon); + int energy = EnergyWeaponItem.getEnergy(weapon); if (energy >= amount) return true; - return energy < REFILL_THRESHOLD + return energy < EnergyWeaponItem.REFILL_THRESHOLD && player.getInventory().findSlotMatchingItem(ModItems.SUPER_CAPACITOR.asStack()) >= 0; } protected void stopForInsufficientPower(Player player) { - showInsufficientPower(player); + EnergyWeaponItem.showInsufficientPower(player); player.stopUsingItem(); } public static void showInsufficientPower(Player player) { - player.sendOverlayMessage(INSUFFICIENT_POWER); + player.sendOverlayMessage(EnergyWeaponItem.INSUFFICIENT_POWER); } private static int getEnergy(ItemStack stack) { @@ -83,11 +84,14 @@ public boolean isBarVisible(ItemStack stack) { @Override public int getBarWidth(ItemStack stack) { - return Math.round(Math.clamp((float) getEnergy(stack) / MAX_ENERGY, 0, 1) * 13); + return Math.round(Math.clamp((float) EnergyWeaponItem.getEnergy(stack) / EnergyWeaponItem.MAX_ENERGY, 0, 1) * 13); } @Override public int getBarColor(ItemStack stack) { - return ColorUtil.lerpColor((float) getEnergy(stack) / MAX_ENERGY, BAR_COLOR, FULL_BAR_COLOR); + return ColorUtil.lerpColor( + (float) EnergyWeaponItem.getEnergy(stack) / EnergyWeaponItem.MAX_ENERGY, EnergyWeaponItem.BAR_COLOR, + EnergyWeaponItem.FULL_BAR_COLOR + ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/weapon/LaserGunItem.java b/src/main/java/dev/dubhe/anvilcraft/item/weapon/LaserGunItem.java index 23ef2e585a..c0bec51680 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/weapon/LaserGunItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/weapon/LaserGunItem.java @@ -49,7 +49,7 @@ public LaserGunItem(Properties properties) { @Override public InteractionResult use(Level level, Player player, InteractionHand hand) { ItemStack stack = player.getItemInHand(hand); - if (!this.canStartUsing(player, stack, ENERGY[0])) return InteractionResult.FAIL; + if (!this.canStartUsing(player, stack, LaserGunItem.ENERGY[0])) return InteractionResult.FAIL; player.startUsingItem(hand); return InteractionResult.CONSUME; } @@ -57,7 +57,7 @@ public InteractionResult use(Level level, Player player, InteractionHand hand) { @Override public void onUseTick(Level level, LivingEntity user, ItemStack stack, int remaining) { if (!(user instanceof ServerPlayer player) || !(level instanceof ServerLevel serverLevel)) return; - LaserState state = STATES.computeIfAbsent(player.getUUID(), ignored -> new LaserState()); + LaserState state = LaserGunItem.STATES.computeIfAbsent(player.getUUID(), ignored -> new LaserState()); WeaponRaycastUtil.Ray fullRay = WeaponRaycastUtil.ray(player, 48.0); BlockHitResult blockHit = WeaponRaycastUtil.laserBlockHit(level, player, fullRay); WeaponRaycastUtil.Ray ray = new WeaponRaycastUtil.Ray(fullRay.start(), blockHit.getLocation()); @@ -69,15 +69,15 @@ public void onUseTick(Level level, LivingEntity user, ItemStack stack, int remai int visualStage = targets.isEmpty() ? 0 : Math.min(4, state.targetTicks / 100); Vec3 visualStart = WeaponRaycastUtil.visualStart(player, WeaponRaycastUtil.MUZZLE_RIGHT_OFFSET); WeaponBeamEntity.showContinuous( - level, visualStart, end, WeaponBeamEntity.LASER, VISUAL_LEVEL[visualStage], player); + level, visualStart, end, WeaponBeamEntity.LASER, LaserGunItem.VISUAL_LEVEL[visualStage], player); if (!targets.isEmpty()) { state.resetMining(); - hurtTargets(serverLevel, player, stack, targets, state); + LaserGunItem.hurtTargets(serverLevel, player, stack, targets, state); return; } state.resetTarget(); - mine(serverLevel, player, stack, blockHit, state); + LaserGunItem.mine(serverLevel, player, stack, blockHit, state); } private static void hurtTargets( @@ -99,7 +99,7 @@ private static void hurtTargets( if (state.targetTicks % period != 0) return; int stage = Math.min(4, state.targetTicks / 100); EnergyWeaponItem weapon = (EnergyWeaponItem) stack.getItem(); - if (!weapon.consumeEnergy(player, stack, ENERGY[stage], 80_000_000)) return; + if (!weapon.consumeEnergy(player, stack, LaserGunItem.ENERGY[stage], 80_000_000)) return; if (stage >= 3) { player.igniteForSeconds(5.0F); @@ -111,7 +111,7 @@ private static void hurtTargets( } for (LivingEntity target : targets) { DamageSource source = ModDamageTypes.laser(level, player); - if (target.hurtServer(level, source, DAMAGE[stage])) { + if (target.hurtServer(level, source, LaserGunItem.DAMAGE[stage])) { EnchantmentHelper.doPostAttackEffectsWithItemSource(level, target, source, stack); } } @@ -139,11 +139,11 @@ private static void mine( } state.idleTicks = 0; state.miningAnchor = origin.immutable(); - state.vein.addAll(findVein( + state.vein.addAll(LaserGunItem.findVein( level, origin, ore, AnvilCraft.CONFIG.laserOreClusterMaxSize, player.position())); } state.miningTicks++; - if (state.miningTicks % miningPeriod(level, stack) != 0 || state.vein.isEmpty()) return; + if (state.miningTicks % LaserGunItem.miningPeriod(level, stack) != 0 || state.vein.isEmpty()) return; if (!((EnergyWeaponItem) stack.getItem()).consumeEnergy( player, stack, 400_000, 80_000_000)) { return; @@ -200,22 +200,22 @@ public static List findVein( @Override public boolean releaseUsing(ItemStack stack, Level level, LivingEntity entity, int timeLeft) { - STATES.remove(entity.getUUID()); + LaserGunItem.STATES.remove(entity.getUUID()); return false; } @Override protected void stopForInsufficientPower(Player player) { - STATES.remove(player.getUUID()); + LaserGunItem.STATES.remove(player.getUUID()); super.stopForInsufficientPower(player); } public static void clearState(UUID playerId) { - STATES.remove(playerId); + LaserGunItem.STATES.remove(playerId); } public static void clearStates() { - STATES.clear(); + LaserGunItem.STATES.clear(); } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/item/weapon/SpectralWeaponLauncherItem.java b/src/main/java/dev/dubhe/anvilcraft/item/weapon/SpectralWeaponLauncherItem.java index 568174bb4f..f450ee6218 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/weapon/SpectralWeaponLauncherItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/weapon/SpectralWeaponLauncherItem.java @@ -117,6 +117,9 @@ public int getBarWidth(ItemStack stack) { @Override public int getBarColor(ItemStack stack) { float energy = stack.getOrDefault(ModComponents.STORED_ENERGY, StoredEnergy.EMPTY).value(); - return ColorUtil.lerpColor(energy / SpectralWeaponLauncherItem.MAX_ENERGY, BAR_COLOR, FULL_BAR_COLOR); + return ColorUtil.lerpColor( + energy / SpectralWeaponLauncherItem.MAX_ENERGY, SpectralWeaponLauncherItem.BAR_COLOR, + SpectralWeaponLauncherItem.FULL_BAR_COLOR + ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/item/weapon/TeslaGunItem.java b/src/main/java/dev/dubhe/anvilcraft/item/weapon/TeslaGunItem.java index 3eae1d14be..ad22b9af37 100644 --- a/src/main/java/dev/dubhe/anvilcraft/item/weapon/TeslaGunItem.java +++ b/src/main/java/dev/dubhe/anvilcraft/item/weapon/TeslaGunItem.java @@ -45,7 +45,7 @@ public TeslaGunItem(Properties properties) { @Override public InteractionResult use(Level level, Player player, InteractionHand hand) { ItemStack stack = player.getItemInHand(hand); - if (!this.canStartUsing(player, stack, SHOT_ENERGY)) return InteractionResult.FAIL; + if (!this.canStartUsing(player, stack, TeslaGunItem.SHOT_ENERGY)) return InteractionResult.FAIL; player.startUsingItem(hand); return InteractionResult.CONSUME; } @@ -54,19 +54,19 @@ public InteractionResult use(Level level, Player player, InteractionHand hand) { public void onUseTick(Level level, LivingEntity user, ItemStack stack, int remaining) { if (!(user instanceof ServerPlayer player) || !(level instanceof ServerLevel serverLevel)) return; if (player.getCooldowns().isOnCooldown(stack)) return; - Target target = findTarget(level, player); + Target target = TeslaGunItem.findTarget(level, player); if (target == null) return; BlockPos rod = target.rod(); if (rod != null && !(level.getBlockState(rod).getBlock() instanceof LightningRodBlock)) return; - if (!this.consumeEnergy(player, stack, SHOT_ENERGY, 160_000_000)) return; + if (!this.consumeEnergy(player, stack, TeslaGunItem.SHOT_ENERGY, 160_000_000)) return; int quickCharge = stack.getEnchantmentLevel( level.holderLookup(Registries.ENCHANTMENT).getOrThrow(Enchantments.QUICK_CHARGE)); player.getCooldowns().addCooldown(stack, 80 - Math.min(60, quickCharge * 5)); Vec3 start = player.getEyePosition().add(player.getViewVector(1.0F).scale(0.5)); if (target.entity() != null) { - strikeChain(serverLevel, player, stack, start, target.entity()); + TeslaGunItem.strikeChain(serverLevel, player, stack, start, target.entity()); } else if (rod != null) { - strikeRod(serverLevel, start, rod); + TeslaGunItem.strikeRod(serverLevel, start, rod); } level.playSound( null, @@ -85,12 +85,12 @@ public void onUseTick(Level level, LivingEntity user, ItemStack stack, int remai LivingEntity living = level.getEntitiesOfClass(LivingEntity.class, area, entity -> { if (entity == player || !entity.isAlive()) return false; Vec3 to = entity.getBoundingBox().getCenter().subtract(eye); - return to.lengthSqr() <= 256.0 && to.normalize().dot(look) >= COS_15_DEGREES; + return to.lengthSqr() <= 256.0 && to.normalize().dot(look) >= TeslaGunItem.COS_15_DEGREES; }).stream().min(Comparator.comparingDouble(entity -> entity.distanceToSqr(player))).orElse(null); BlockPos rod = BlockPos.betweenClosedStream(area) .filter(pos -> level.getBlockState(pos).is(Blocks.LIGHTNING_ROD)) - .filter(pos -> pos.getCenter().subtract(eye).normalize().dot(look) >= COS_15_DEGREES) + .filter(pos -> pos.getCenter().subtract(eye).normalize().dot(look) >= TeslaGunItem.COS_15_DEGREES) .map(BlockPos::immutable) .min(Comparator.comparingDouble(pos -> pos.distToCenterSqr(eye))) .orElse(null); @@ -121,7 +121,7 @@ private static void strikeChain( struck.add(target.getId()); Vec3 hitPos = target.getBoundingBox().getCenter(); level.addFreshEntity(WeaponBeamEntity.create(level, start, hitPos, WeaponBeamEntity.TESLA)); - LivingEntity origin = thunderHit(level, player, weapon, target, 40.0F - jump * 10.0F); + LivingEntity origin = TeslaGunItem.thunderHit(level, player, weapon, target, 40.0F - jump * 10.0F); start = origin.getBoundingBox().getCenter(); target = level.getEntitiesOfClass( LivingEntity.class, diff --git a/src/main/java/dev/dubhe/anvilcraft/loot/functions/CurseLootItemFunction.java b/src/main/java/dev/dubhe/anvilcraft/loot/functions/CurseLootItemFunction.java index 2851090729..ffb8358dc6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/loot/functions/CurseLootItemFunction.java +++ b/src/main/java/dev/dubhe/anvilcraft/loot/functions/CurseLootItemFunction.java @@ -15,7 +15,7 @@ public class CurseLootItemFunction extends LootItemConditionalFunction { public static final MapCodec CODEC = RecordCodecBuilder.mapCodec( - ins -> commonFields(ins).apply(ins, CurseLootItemFunction::new) + ins -> LootItemConditionalFunction.commonFields(ins).apply(ins, CurseLootItemFunction::new) ); public CurseLootItemFunction(List predicates) { diff --git a/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/DisintegrationLootModifier.java b/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/DisintegrationLootModifier.java index 9fc6bb896a..de1b8d6d5d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/DisintegrationLootModifier.java +++ b/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/DisintegrationLootModifier.java @@ -51,6 +51,6 @@ protected ObjectArrayList doApply(ObjectArrayList generate @Override public MapCodec codec() { - return CODEC; + return DisintegrationLootModifier.CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/SmeltingLootModifier.java b/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/SmeltingLootModifier.java index ce0e69cb12..950d952994 100644 --- a/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/SmeltingLootModifier.java +++ b/src/main/java/dev/dubhe/anvilcraft/loot/modifiers/SmeltingLootModifier.java @@ -105,6 +105,6 @@ protected ObjectArrayList doApply(ObjectArrayList generate @Override public MapCodec codec() { - return CODEC; + return SmeltingLootModifier.CODEC; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/AbstractVillagerMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/AbstractVillagerMixin.java index e46b30e4e1..dfbf7f0687 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/AbstractVillagerMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/AbstractVillagerMixin.java @@ -41,7 +41,7 @@ void addTrades( CallbackInfo ci, @Local LootContext lootContext ) { - if (resourceKey.identifier().equals(JEWELER_TRADE_SET)) { + if (resourceKey.identifier().equals(AbstractVillagerMixin.JEWELER_TRADE_SET)) { Optional tradeSet = level.registryAccess().lookupOrThrow(Registries.VILLAGER_TRADE) .getOptional(ModVillagerTrades.EMERALD_FOR_ROYAL_STEEL_TEMPLATE.identifier()); if (tradeSet.isEmpty()) return; diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/AvoidEntityGoalMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/AvoidEntityGoalMixin.java index 2e241e1f88..f3f5cb0d41 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/AvoidEntityGoalMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/AvoidEntityGoalMixin.java @@ -71,24 +71,24 @@ private void addAvoidPlayerGoal(AvoidEntityGoal instance, @Nullable T value, this.mob.level().getEntitiesOfClass( LivingEntity.class, this.mob.getBoundingBox().inflate(this.maxDist, 3.0, this.maxDist), - entity -> Util.instanceOfAny(entity, this.avoidClass) || anvilcraft$is(this.avoidClass, entity) + entity -> Util.instanceOfAny(entity, this.avoidClass) || AvoidEntityGoalMixin.anvilcraft$is(this.avoidClass, entity) ), this.avoidEntityTargeting.selector( Optional.ofNullable(((TargetingConditionsAccessor) this.avoidEntityTargeting).getSelector()) .map(p -> ModifiedSelector.toModified( p, old -> (entity, level) -> { - if (anvilcraft$is(this.avoidClass, entity)) { - entity = anvilcraft$toDummy(this.avoidClass, entity); + if (AvoidEntityGoalMixin.anvilcraft$is(this.avoidClass, entity)) { + entity = AvoidEntityGoalMixin.anvilcraft$toDummy(this.avoidClass, entity); } return old.test(Objects.requireNonNull(entity), level); } )) .orElse((entity, _) -> { - if (anvilcraft$is(this.avoidClass, entity)) { - entity = anvilcraft$toDummy(this.avoidClass, entity); + if (AvoidEntityGoalMixin.anvilcraft$is(this.avoidClass, entity)) { + entity = AvoidEntityGoalMixin.anvilcraft$toDummy(this.avoidClass, entity); } - return Util.instanceOfAny(entity, this.avoidClass) || anvilcraft$is(this.avoidClass, entity); + return Util.instanceOfAny(entity, this.avoidClass) || AvoidEntityGoalMixin.anvilcraft$is(this.avoidClass, entity); }) ), this.mob, @@ -96,8 +96,8 @@ private void addAvoidPlayerGoal(AvoidEntityGoal instance, @Nullable T value, this.mob.getY(), this.mob.getZ() ); - if (anvilcraft$is(this.avoidClass, toAvoid)) { - toAvoid = anvilcraft$toDummy(this.avoidClass, Objects.requireNonNull(toAvoid)); + if (AvoidEntityGoalMixin.anvilcraft$is(this.avoidClass, toAvoid)) { + toAvoid = AvoidEntityGoalMixin.anvilcraft$toDummy(this.avoidClass, Objects.requireNonNull(toAvoid)); } // noinspection DataFlowIssue this.toAvoid = Util.cast(toAvoid); diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/BeaconMenuMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/BeaconMenuMixin.java index cbbabf1621..54808d492c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/BeaconMenuMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/BeaconMenuMixin.java @@ -69,7 +69,7 @@ private void updateEffects( private boolean anvilcraft$toCorrupted(Level level, BlockPos pos) { RandomSource random = level.getRandom(); double chance = random.nextDouble(); - int levels = anvilcraft$updateBase(level, pos.getX(), pos.getY(), pos.getZ()); + int levels = BeaconMenuMixin.anvilcraft$updateBase(level, pos.getX(), pos.getY(), pos.getZ()); return switch (levels) { case 1 -> chance < 0.02; case 2 -> chance < 0.05; diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/BuddingAmethystBlockMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/BuddingAmethystBlockMixin.java index 136478a696..7f25adcce3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/BuddingAmethystBlockMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/BuddingAmethystBlockMixin.java @@ -27,7 +27,7 @@ public class BuddingAmethystBlockMixin implements IBuddingAmethystBlockExtension @Override public void anvilcraft$tryGrowBuds(Level level, BlockPos pos, BlockState state) { List budDirs = new ArrayList<>(); - for (Direction dir : DIRECTIONS) { + for (Direction dir : BuddingAmethystBlockMixin.DIRECTIONS) { BlockPos neighborPos = pos.relative(dir); BlockState neighborState = level.getBlockState(neighborPos); if ( @@ -70,7 +70,7 @@ public class BuddingAmethystBlockMixin implements IBuddingAmethystBlockExtension @Override public void anvilcraft$tryBreakClusters(Level level, BlockPos pos, BlockState state, BiConsumer breaker) { - for (Direction dir : DIRECTIONS) { + for (Direction dir : BuddingAmethystBlockMixin.DIRECTIONS) { BlockPos neighborPos = pos.relative(dir); BlockState neighborState = level.getBlockState(neighborPos); if ( diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/EnchantmentHelperMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/EnchantmentHelperMixin.java index db3c991365..190758abdb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/EnchantmentHelperMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/EnchantmentHelperMixin.java @@ -116,20 +116,20 @@ private static List modifyEnchantmentResults( } if (isRoyal) { - anvilcraft$boostEnchantment(modified, Enchantments.SILK_TOUCH); - anvilcraft$boostEnchantment(modified, Enchantments.UNBREAKING); + EnchantmentHelperMixin.anvilcraft$boostEnchantment(modified, Enchantments.SILK_TOUCH); + EnchantmentHelperMixin.anvilcraft$boostEnchantment(modified, Enchantments.UNBREAKING); } else if (isFrost) { - anvilcraft$boostEnchantment(modified, ModEnchantments.DISINTEGRATION_KEY); + EnchantmentHelperMixin.anvilcraft$boostEnchantment(modified, ModEnchantments.DISINTEGRATION_KEY); } else if (isEmber) { - anvilcraft$boostEnchantment(modified, ModEnchantments.SMELTING_KEY); - anvilcraft$boostEnchantment(modified, Enchantments.FIRE_ASPECT); + EnchantmentHelperMixin.anvilcraft$boostEnchantment(modified, ModEnchantments.SMELTING_KEY); + EnchantmentHelperMixin.anvilcraft$boostEnchantment(modified, Enchantments.FIRE_ASPECT); } if (path.contains("transcendence")) { - anvilcraft$boostEnchantment(modified, Enchantments.FORTUNE); - anvilcraft$boostEnchantment(modified, Enchantments.LOOTING); - anvilcraft$addHigherLevel(modified, Enchantments.FORTUNE); - anvilcraft$addHigherLevel(modified, Enchantments.LOOTING); + EnchantmentHelperMixin.anvilcraft$boostEnchantment(modified, Enchantments.FORTUNE); + EnchantmentHelperMixin.anvilcraft$boostEnchantment(modified, Enchantments.LOOTING); + EnchantmentHelperMixin.anvilcraft$addHigherLevel(modified, Enchantments.FORTUNE); + EnchantmentHelperMixin.anvilcraft$addHigherLevel(modified, Enchantments.LOOTING); } return modified; diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockEntityMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockEntityMixin.java index a5e0f3edd9..b2d8eddf66 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockEntityMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockEntityMixin.java @@ -8,6 +8,7 @@ import dev.dubhe.anvilcraft.api.injection.entity.IFallingBlockEntityExtension; import dev.dubhe.anvilcraft.init.block.ModBlocks; import dev.dubhe.anvilcraft.util.AccelerateManager; +import dev.dubhe.anvilcraft.util.EntityUtil; import dev.dubhe.anvilcraft.util.GravityManager; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -128,7 +129,7 @@ public FallingBlockEntityMixin(EntityType entityType, Level level) { if (gravityDir == Direction.DOWN && !entityCollision) return original.call(instance); if (gravityDir != Direction.DOWN && this.anvilcraft$positionBeforeTick != null) { - this.anvilcraft$directionalFallDistance += (float) position().distanceTo(this.anvilcraft$positionBeforeTick); + this.anvilcraft$directionalFallDistance += (float) this.position().distanceTo(this.anvilcraft$positionBeforeTick); this.anvilcraft$fallDistance = Math.max(this.anvilcraft$fallDistance, this.anvilcraft$directionalFallDistance); } @@ -476,9 +477,8 @@ private void hurtEntity(CallbackInfo ci) { ); if (hitResult == null) return; if (hitResult.getType() != EntityHitResult.Type.ENTITY) return; - float hurtAmount = (float) (this.getDeltaMovement().length() * DAMAGE_FACTOR); - // noinspection deprecation - hitResult.getEntity().hurtOrSimulate(damageSources().anvil(this), hurtAmount); + float hurtAmount = (float) (this.getDeltaMovement().length() * FallingBlockEntityMixin.DAMAGE_FACTOR); + EntityUtil.hurtOrSimulate(hitResult.getEntity(), this.damageSources().anvil(this), hurtAmount); } @Inject(method = "tick", at = @At("TAIL")) @@ -507,7 +507,7 @@ private void hurtEntity(CallbackInfo ci) { @Inject(method = "tick", at = @At("HEAD"), cancellable = true) private void anvilcraft$handleAcceleration(CallbackInfo ci) { - this.anvilcraft$positionBeforeTick = position(); + this.anvilcraft$positionBeforeTick = this.position(); if (this.anvilcraft$discardLevitationPowderAboveBuildHeight()) { ci.cancel(); return; diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockMixin.java index 350ce8250c..9c9fe06688 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/FallingBlockMixin.java @@ -61,7 +61,7 @@ public FallingBlockMixin(Properties properties) { || state.getValue(GiantAnvilBlock.HALF) != Cube3x3PartHalf.BOTTOM_CENTER) { return; } - if (anvilcraft$isHeldByRing(level, pos, state)) { + if (FallingBlockMixin.anvilcraft$isHeldByRing(level, pos, state)) { ci.cancel(); return; } @@ -159,7 +159,7 @@ public FallingBlockMixin(Properties properties) { return FallingBlock.isFree(level.getBlockState(targetPos)) ? null : targetPos; } for (Cube3x3PartHalf part : Cube3x3PartHalf.values()) { - if (!anvilcraft$isOnFace(part, direction)) continue; + if (!FallingBlockMixin.anvilcraft$isOnFace(part, direction)) continue; BlockPos targetPos = pos.offset(part.getOffset()).relative(direction); if (!FallingBlock.isFree(level.getBlockState(targetPos))) return targetPos; } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/FlyingHitEntityMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/FlyingHitEntityMixin.java index 6477b21adb..d5093dafe5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/FlyingHitEntityMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/FlyingHitEntityMixin.java @@ -3,6 +3,7 @@ import dev.anvilcraft.lib.v2.util.Util; import dev.dubhe.anvilcraft.init.item.ModItems; import dev.dubhe.anvilcraft.item.tool.AnvilHammerItem; +import dev.dubhe.anvilcraft.util.EntityUtil; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; @@ -58,13 +59,12 @@ private void onFlyingHitEntity(Vec3 input, CallbackInfo ci) { } AABB headBlockBoundBox = AABB.ofSize(this.getEyePosition(), 1, 1, 1); List entities = - level().getEntitiesOfClass(LivingEntity.class, headBlockBoundBox, it -> it != (Object) this); - Vec3 movement = getDeltaMovement(); - float amount = (float) (movement.length() * DAMAGE_FACTOR); + this.level().getEntitiesOfClass(LivingEntity.class, headBlockBoundBox, it -> it != (Object) this); + Vec3 movement = this.getDeltaMovement(); + float amount = (float) (movement.length() * FlyingHitEntityMixin.DAMAGE_FACTOR); for (LivingEntity entity : entities) { - // noinspection deprecation - entity.hurtOrSimulate(damageSources().playerAttack(thiS), amount); - anvilcraft$damageItem(thiS, this.getItemBySlot(EquipmentSlot.HEAD)); + EntityUtil.hurtOrSimulate(entity, this.damageSources().playerAttack(thiS), amount); + FlyingHitEntityMixin.anvilcraft$damageItem(thiS, this.getItemBySlot(EquipmentSlot.HEAD)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/GuiGraphicsExtractorMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/GuiGraphicsExtractorMixin.java index 8ad30daddd..0d8ecbb97c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/GuiGraphicsExtractorMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/GuiGraphicsExtractorMixin.java @@ -45,9 +45,9 @@ private void renderExtra(LivingEntity owner, Level level, ItemStack itemStack, i x, y, seed, - ANVILCRAFT$RECURSION, - ANVILCRAFT$MAX_RECURSION, - i -> ANVILCRAFT$RECURSION = i + GuiGraphicsExtractorMixin.ANVILCRAFT$RECURSION, + GuiGraphicsExtractorMixin.ANVILCRAFT$MAX_RECURSION, + i -> GuiGraphicsExtractorMixin.ANVILCRAFT$RECURSION = i ); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/HopperBlockMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/HopperBlockMixin.java index ac6e3efd8e..dce4ec225c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/HopperBlockMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/HopperBlockMixin.java @@ -24,12 +24,12 @@ abstract class HopperBlockMixin implements IHammerChangeable { @Override @SuppressWarnings("AddedMixinMembersNamePattern") public boolean change(Player player, BlockPos blockPos, Level level, ItemStack anvilHammer) { - return level.setBlockAndUpdate(blockPos, level.getBlockState(blockPos).cycle(FACING)); + return level.setBlockAndUpdate(blockPos, level.getBlockState(blockPos).cycle(HopperBlockMixin.FACING)); } @Override @SuppressWarnings("AddedMixinMembersNamePattern") public @Nullable Property getChangeableProperty(BlockState blockState) { - return FACING; + return HopperBlockMixin.FACING; } } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/ItemEntityMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/ItemEntityMixin.java index 152921c969..4502a885a2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/ItemEntityMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/ItemEntityMixin.java @@ -97,17 +97,17 @@ private void voidResistant(CallbackInfo ci) { private static final Map REPAIR_EFFICIENCY = new HashMap<>(); static { - REPAIR_EFFICIENCY.put(Blocks.FIRE, 2); - REPAIR_EFFICIENCY.put(Blocks.SOUL_FIRE, 5); - REPAIR_EFFICIENCY.put(Blocks.LAVA, 10); - REPAIR_EFFICIENCY.put(Blocks.LAVA_CAULDRON, 10); + ItemEntityMixin.REPAIR_EFFICIENCY.put(Blocks.FIRE, 2); + ItemEntityMixin.REPAIR_EFFICIENCY.put(Blocks.SOUL_FIRE, 5); + ItemEntityMixin.REPAIR_EFFICIENCY.put(Blocks.LAVA, 10); + ItemEntityMixin.REPAIR_EFFICIENCY.put(Blocks.LAVA_CAULDRON, 10); } @Inject(method = "tick", at = @At("HEAD")) private void fireReforging(CallbackInfo ci) { ItemStack item = this.getItem(); Block block = this.level().getBlockState(this.blockPosition()).getBlock(); - Integer repairAmount = REPAIR_EFFICIENCY.get(block); + Integer repairAmount = ItemEntityMixin.REPAIR_EFFICIENCY.get(block); if (repairAmount == null) return; FireReforgingUtil.repair(item, repairAmount, this.level(), this.anvilcraft$blockPos); } @@ -276,51 +276,51 @@ public boolean preventMerge(ItemEntity instance, Operation original) { static { // 1. 定义材质关键词及其减速 (数值越小越慢) - MATERIAL_MAP.put("iron", 0.50); - MATERIAL_MAP.put("magnet", 0.50); - MATERIAL_MAP.put("steel", 0.75); - - MATERIAL_MAP.put("silver", 0.25); - MATERIAL_MAP.put("copper", 0.27); - MATERIAL_MAP.put("gold", 0.28); - MATERIAL_MAP.put("netherite", 0.30); - MATERIAL_MAP.put("ember", 0.30); - MATERIAL_MAP.put("aluminum", 0.30); - MATERIAL_MAP.put("tungsten", 0.38); - MATERIAL_MAP.put("zinc", 0.40); - MATERIAL_MAP.put("brass", 0.42); - MATERIAL_MAP.put("bronze", 0.45); - MATERIAL_MAP.put("royal", 0.50); - MATERIAL_MAP.put("tin", 0.55); - MATERIAL_MAP.put("lead", 0.65); - MATERIAL_MAP.put("uranium", 0.80); - MATERIAL_MAP.put("titanium", 0.88); - MATERIAL_MAP.put("frost_metal", 0.90); - MATERIAL_MAP.put("plutonium", 0.99); + ItemEntityMixin.MATERIAL_MAP.put("iron", 0.50); + ItemEntityMixin.MATERIAL_MAP.put("magnet", 0.50); + ItemEntityMixin.MATERIAL_MAP.put("steel", 0.75); + + ItemEntityMixin.MATERIAL_MAP.put("silver", 0.25); + ItemEntityMixin.MATERIAL_MAP.put("copper", 0.27); + ItemEntityMixin.MATERIAL_MAP.put("gold", 0.28); + ItemEntityMixin.MATERIAL_MAP.put("netherite", 0.30); + ItemEntityMixin.MATERIAL_MAP.put("ember", 0.30); + ItemEntityMixin.MATERIAL_MAP.put("aluminum", 0.30); + ItemEntityMixin.MATERIAL_MAP.put("tungsten", 0.38); + ItemEntityMixin.MATERIAL_MAP.put("zinc", 0.40); + ItemEntityMixin.MATERIAL_MAP.put("brass", 0.42); + ItemEntityMixin.MATERIAL_MAP.put("bronze", 0.45); + ItemEntityMixin.MATERIAL_MAP.put("royal", 0.50); + ItemEntityMixin.MATERIAL_MAP.put("tin", 0.55); + ItemEntityMixin.MATERIAL_MAP.put("lead", 0.65); + ItemEntityMixin.MATERIAL_MAP.put("uranium", 0.80); + ItemEntityMixin.MATERIAL_MAP.put("titanium", 0.88); + ItemEntityMixin.MATERIAL_MAP.put("frost_metal", 0.90); + ItemEntityMixin.MATERIAL_MAP.put("plutonium", 0.99); // 在这里继续添加材料... // 2. 将不含关键词的物品映射到上述材质 - SPECIAL_MAP.put("lightning_rod", "copper"); - SPECIAL_MAP.put("bucket", "iron"); - SPECIAL_MAP.put("hopper", "iron"); - SPECIAL_MAP.put("shears", "iron"); - SPECIAL_MAP.put("anvil", "iron"); - SPECIAL_MAP.put("minecart", "iron"); - SPECIAL_MAP.put("tripwire_hook", "iron"); - SPECIAL_MAP.put("chain", "iron"); - SPECIAL_MAP.put("chute", "iron"); - SPECIAL_MAP.put("compass", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("lightning_rod", "copper"); + ItemEntityMixin.SPECIAL_MAP.put("bucket", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("hopper", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("shears", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("anvil", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("minecart", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("tripwire_hook", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("chain", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("chute", "iron"); + ItemEntityMixin.SPECIAL_MAP.put("compass", "iron"); // 在这里继续添加特判... } @Unique private @Nullable String anvilcraft$getMaterialKey(ItemStack stack) { String id = BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath(); - for (String black : SPECIAL_BLACKLIST) { + for (String black : ItemEntityMixin.SPECIAL_BLACKLIST) { if (id.contains(black)) return null; // 黑名单检查 } - if (SPECIAL_MAP.containsKey(id)) return SPECIAL_MAP.get(id); // 别名/特判检查 - for (String key : MATERIAL_MAP.keySet()) { // 关键词匹配 + if (ItemEntityMixin.SPECIAL_MAP.containsKey(id)) return ItemEntityMixin.SPECIAL_MAP.get(id); // 别名/特判检查 + for (String key : ItemEntityMixin.MATERIAL_MAP.keySet()) { // 关键词匹配 if (id.contains(key)) return key; } return null; @@ -410,7 +410,7 @@ public boolean preventMerge(ItemEntity instance, Operation original) { } // 3. 涡流减速 if (state.is(ModBlocks.HOLLOW_MAGNET_BLOCK.get()) && !state.getValue(MagnetBlock.LIT)) { - Double speedFactor = MATERIAL_MAP.get(matKey); + Double speedFactor = ItemEntityMixin.MATERIAL_MAP.get(matKey); if (speedFactor != null) this.setDeltaMovement(this.getDeltaMovement().scale(speedFactor)); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/ItemStackMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/ItemStackMixin.java index 785c0e0131..a1b1a64b49 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/ItemStackMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/ItemStackMixin.java @@ -43,6 +43,7 @@ private void appendCustomHoverText( builder )); } + @WrapMethod(method = "typeHolder") private Holder storeStack( Operation> original, diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/PlayerHitEntityMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/PlayerHitEntityMixin.java index 4f931dbb1f..bcb328fc3c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/PlayerHitEntityMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/PlayerHitEntityMixin.java @@ -3,6 +3,7 @@ import dev.anvilcraft.lib.v2.util.Util; import dev.dubhe.anvilcraft.init.item.ModItems; import dev.dubhe.anvilcraft.item.tool.AnvilHammerItem; +import dev.dubhe.anvilcraft.util.EntityUtil; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.damagesource.DamageSource; @@ -45,22 +46,22 @@ private void onFlyingHitBlock(ServerLevel level, DamageSource source, float dama } AABB headBlockBoundBox = AABB.ofSize(this.getEyePosition(), 1, 1, 1); List entities = - level().getEntitiesOfClass(LivingEntity.class, headBlockBoundBox, it -> it != this); + this.level().getEntitiesOfClass(LivingEntity.class, headBlockBoundBox, it -> it != this); if (entities.isEmpty()) return; - Vec3 movement = getDeltaMovement(); - float hurtAmount = (float) (movement.length() * DAMAGE_FACTOR); - if (source.type().equals(level().damageSources().flyIntoWall().type())) { + Vec3 movement = this.getDeltaMovement(); + float hurtAmount = (float) (movement.length() * PlayerHitEntityMixin.DAMAGE_FACTOR); + if (source.type().equals(this.level().damageSources().flyIntoWall().type())) { for (LivingEntity entity : entities) { - entity.hurt(damageSources().playerAttack(thiS), hurtAmount); - anvilcraft$damageItem(thiS, this.getItemBySlot(EquipmentSlot.HEAD)); + EntityUtil.hurt(entity, this.damageSources().playerAttack(thiS), hurtAmount); + PlayerHitEntityMixin.anvilcraft$damageItem(thiS, this.getItemBySlot(EquipmentSlot.HEAD)); } cir.setReturnValue(false); cir.cancel(); } else { - if (source.type().equals(level().damageSources().fall().type())) { + if (source.type().equals(this.level().damageSources().fall().type())) { for (LivingEntity entity : entities) { - entity.hurt(damageSources().playerAttack(thiS), hurtAmount); - anvilcraft$damageItem(thiS, this.getItemBySlot(EquipmentSlot.HEAD)); + EntityUtil.hurt(entity, this.damageSources().playerAttack(thiS), hurtAmount); + PlayerHitEntityMixin.anvilcraft$damageItem(thiS, this.getItemBySlot(EquipmentSlot.HEAD)); } cir.setReturnValue(false); cir.cancel(); diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/RedstoneWireBlockMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/RedstoneWireBlockMixin.java index dbbbcb632c..77f73431c3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/RedstoneWireBlockMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/RedstoneWireBlockMixin.java @@ -29,7 +29,8 @@ public abstract class RedstoneWireBlockMixin implements ITooltipProviderExtensio public List anvilcraft$getTooltip(BlockState state) { final ArrayList lines = new ArrayList<>(); lines.add(Component.translatable("tooltip.anvilcraft.redstone.title").withStyle(ChatFormatting.BLUE)); - lines.add(Component.translatable("tooltip.anvilcraft.redstone.power", state.getValue(POWER)).withStyle(ChatFormatting.GRAY)); + lines.add(Component.translatable("tooltip.anvilcraft.redstone.power", state.getValue( + RedstoneWireBlockMixin.POWER)).withStyle(ChatFormatting.GRAY)); return lines; } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/piglin/PiglinMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/piglin/PiglinMixin.java index d484bac0e0..c2bbdcdf54 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/piglin/PiglinMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/piglin/PiglinMixin.java @@ -31,8 +31,8 @@ private PiglinMixin(EntityType entityType, Level level ) private void startCursedZombification(ItemStack itemStack, CallbackInfo ci) { if (!(itemStack.getItem() instanceof ICursed)) return; - this.timeInOverworld = CONVERSION_TIME - this.level().getRandom().nextIntBetweenInclusive( - MIN_CURSED_ZOMBIFICATION_TIME, MAX_CURSED_ZOMBIFICATION_TIME); + this.timeInOverworld = AbstractPiglin.CONVERSION_TIME - this.level().getRandom().nextIntBetweenInclusive( + PiglinMixin.MIN_CURSED_ZOMBIFICATION_TIME, PiglinMixin.MAX_CURSED_ZOMBIFICATION_TIME); this.setData(ModDataAttachments.ZOMBIFICATED_BY_CURSE, true); } diff --git a/src/main/java/dev/dubhe/anvilcraft/mixin/projectile/AbstractArrowMixin.java b/src/main/java/dev/dubhe/anvilcraft/mixin/projectile/AbstractArrowMixin.java index fbf2e94351..dde8fa5d8e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/mixin/projectile/AbstractArrowMixin.java +++ b/src/main/java/dev/dubhe/anvilcraft/mixin/projectile/AbstractArrowMixin.java @@ -53,7 +53,7 @@ protected AbstractArrowMixin(EntityType entityType, Level ), index = 1 ) private Vec3 anvilcraft$clipEntityTraceAtDeflectionRing(Vec3 end) { - return this.anvilcraft$clipEndAtDeflectionRing(position(), end); + return this.anvilcraft$clipEndAtDeflectionRing(this.position(), end); } @WrapOperation( @@ -63,8 +63,8 @@ protected AbstractArrowMixin(EntityType entityType, Level ) ) private AABB anvilcraft$clipEntityQueryAtDeflectionRing(AABB box, Vec3 movement, Operation original) { - Vec3 end = this.anvilcraft$clipEndAtDeflectionRing(position(), position().add(movement)); - return original.call(box, end.subtract(position())); + Vec3 end = this.anvilcraft$clipEndAtDeflectionRing(this.position(), this.position().add(movement)); + return original.call(box, end.subtract(this.position())); } @Unique diff --git a/src/main/java/dev/dubhe/anvilcraft/network/AdvancedComparatorUpdatePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/AdvancedComparatorUpdatePacket.java index e8a13ce3fd..b3a53270df 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/AdvancedComparatorUpdatePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/AdvancedComparatorUpdatePacket.java @@ -37,7 +37,7 @@ public record AdvancedComparatorUpdatePacket( @Override public Type type() { - return TYPE; + return AdvancedComparatorUpdatePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/BatchCrafterSelectPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/BatchCrafterSelectPacket.java index c5a3accc16..72bc00ca47 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/BatchCrafterSelectPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/BatchCrafterSelectPacket.java @@ -27,7 +27,7 @@ public record BatchCrafterSelectPacket(int selecting, BlockPos pos) implements I @Override public Type type() { - return TYPE; + return BatchCrafterSelectPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/BatchCutterSelectPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/BatchCutterSelectPacket.java index f209f3b83f..467a18d8d8 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/BatchCutterSelectPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/BatchCutterSelectPacket.java @@ -26,7 +26,7 @@ public record BatchCutterSelectPacket(int selecting, BlockPos pos) implements II @Override public Type type() { - return TYPE; + return BatchCutterSelectPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ChargeCollectorIncomingChargePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ChargeCollectorIncomingChargePacket.java index b60e2d7a34..fb0c66e1d4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ChargeCollectorIncomingChargePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ChargeCollectorIncomingChargePacket.java @@ -29,7 +29,7 @@ public record ChargeCollectorIncomingChargePacket(BlockPos srcPos, BlockPos dstP @Override public Type type() { - return TYPE; + return ChargeCollectorIncomingChargePacket.TYPE; } @Override @@ -38,13 +38,13 @@ public void handleOnClient(Player player) { Vec3 srcPos = this.srcPos.getCenter(); Vec3 dstPos = this.dstPos.getCenter(); Vec3 offset = dstPos.subtract(srcPos); - RANDOM.setSeed(System.nanoTime()); - final double dRandom = Math.clamp(RANDOM.nextGaussian() + 1, 1, 1.5); + ChargeCollectorIncomingChargePacket.RANDOM.setSeed(System.nanoTime()); + final double dRandom = Math.clamp(ChargeCollectorIncomingChargePacket.RANDOM.nextGaussian() + 1, 1, 1.5); level.addParticle( ParticleTypes.END_ROD, - srcPos.x + Math.clamp(RANDOM.nextGaussian(), 0, 0.3), - srcPos.y + Math.clamp(RANDOM.nextGaussian(), 0, 0.3), - srcPos.z + Math.clamp(RANDOM.nextGaussian(), 0, 0.3), + srcPos.x + Math.clamp(ChargeCollectorIncomingChargePacket.RANDOM.nextGaussian(), 0, 0.3), + srcPos.y + Math.clamp(ChargeCollectorIncomingChargePacket.RANDOM.nextGaussian(), 0, 0.3), + srcPos.z + Math.clamp(ChargeCollectorIncomingChargePacket.RANDOM.nextGaussian(), 0, 0.3), (offset.x / 20d) * dRandom, (offset.y / 20d) * dRandom, (offset.z / 20d) * dRandom diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ChargerSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ChargerSyncPacket.java index acba065548..d2482a4f0b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ChargerSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ChargerSyncPacket.java @@ -27,7 +27,7 @@ public record ChargerSyncPacket(BlockPos pos, int timeLeft, int timeTotal, boole @Override public Type type() { - return TYPE; + return ChargerSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ComparatorSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ComparatorSyncPacket.java index c7371b5cde..6c1463fe04 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ComparatorSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ComparatorSyncPacket.java @@ -23,7 +23,7 @@ public record ComparatorSyncPacket(BlockPos pos, int output) implements IClientb @Override public Type type() { - return TYPE; + return ComparatorSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ControlValveFilterPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ControlValveFilterPacket.java index 46fe8efecd..68ebe1931f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ControlValveFilterPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ControlValveFilterPacket.java @@ -2,7 +2,6 @@ import dev.anvilcraft.lib.v2.network.packet.IPacket; import dev.anvilcraft.lib.v2.network.packet.ISensitiveBiPacket; -import dev.anvilcraft.lib.v2.util.Util; import dev.dubhe.anvilcraft.AnvilCraft; import dev.dubhe.anvilcraft.client.gui.screen.ControlValveScreen; import dev.dubhe.anvilcraft.inventory.ControlValveMenu; @@ -27,7 +26,7 @@ public record ControlValveFilterPacket(int index, FluidStack fluid) implements I @Override public Type type() { - return TYPE; + return ControlValveFilterPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ControlValveInitPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ControlValveInitPacket.java index feecd17e87..6a3e552af0 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ControlValveInitPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ControlValveInitPacket.java @@ -21,7 +21,7 @@ public record ControlValveInitPacket(int maxRate, FluidStack filter) implements @Override public Type type() { - return TYPE; + return ControlValveInitPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ControlValveUpdatePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ControlValveUpdatePacket.java index bddf029572..e4c32b68a7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ControlValveUpdatePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ControlValveUpdatePacket.java @@ -20,7 +20,7 @@ public record ControlValveUpdatePacket(int maxRate) implements IServerboundPacke @Override public Type type() { - return TYPE; + return ControlValveUpdatePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/CreativeCrateAttackPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/CreativeCrateAttackPacket.java index 0eaed53255..93b8a6d278 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/CreativeCrateAttackPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/CreativeCrateAttackPacket.java @@ -21,7 +21,7 @@ public record CreativeCrateAttackPacket(BlockPos pos) implements IServerboundPac @Override public Type type() { - return TYPE; + return CreativeCrateAttackPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/CyclingValueSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/CyclingValueSyncPacket.java index 6d993d80cd..6e816f3ac3 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/CyclingValueSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/CyclingValueSyncPacket.java @@ -21,7 +21,7 @@ public record CyclingValueSyncPacket(int index, String name) implements IServerb @Override public Type type() { - return TYPE; + return CyclingValueSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/DeflectionRingUpdateLastSpeedPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/DeflectionRingUpdateLastSpeedPacket.java index 56453cde84..4e33a69b18 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/DeflectionRingUpdateLastSpeedPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/DeflectionRingUpdateLastSpeedPacket.java @@ -24,7 +24,7 @@ public record DeflectionRingUpdateLastSpeedPacket(BlockPos pos, double speed) im @Override public Type type() { - return TYPE; + return DeflectionRingUpdateLastSpeedPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/DragonRodDevourPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/DragonRodDevourPacket.java index c598324c7c..18a10b5207 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/DragonRodDevourPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/DragonRodDevourPacket.java @@ -29,7 +29,7 @@ public record DragonRodDevourPacket(InteractionHand hand, BlockPos pos, Directio @Override public Type type() { - return TYPE; + return DragonRodDevourPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/DragonRodStopDevourPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/DragonRodStopDevourPacket.java index 3909552c57..d938a6b5d2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/DragonRodStopDevourPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/DragonRodStopDevourPacket.java @@ -16,7 +16,7 @@ public record DragonRodStopDevourPacket() implements IServerboundPacket { @Override public Type type() { - return TYPE; + return DragonRodStopDevourPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/EmberGrindstoneSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/EmberGrindstoneSyncPacket.java index 97fe5cf703..801ee6f173 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/EmberGrindstoneSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/EmberGrindstoneSyncPacket.java @@ -19,7 +19,7 @@ public record EmberGrindstoneSyncPacket(int index) implements IServerboundPacket @Override public Type type() { - return TYPE; + return EmberGrindstoneSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ExpCollectorSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ExpCollectorSyncPacket.java index b85d97cafc..7edce469d4 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ExpCollectorSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ExpCollectorSyncPacket.java @@ -28,7 +28,7 @@ public record ExpCollectorSyncPacket(BlockPos pos) implements IServerboundPacket @Override public Type type() { - return TYPE; + return ExpCollectorSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/FilterContentSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/FilterContentSyncPacket.java index dc78cff71f..3efad7b566 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/FilterContentSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/FilterContentSyncPacket.java @@ -23,7 +23,7 @@ public record FilterContentSyncPacket(int slotIndex, FilterContent filterContent @Override public Type type() { - return TYPE; + return FilterContentSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/FrostGrindstoneSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/FrostGrindstoneSyncPacket.java index e33cefe465..b4611df70b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/FrostGrindstoneSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/FrostGrindstoneSyncPacket.java @@ -21,7 +21,7 @@ public record FrostGrindstoneSyncPacket(int index, boolean select) implements IS @Override public Type type() { - return TYPE; + return FrostGrindstoneSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/GiantAnvilShockEffectPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/GiantAnvilShockEffectPacket.java index a3fbaa2302..661fc4d5b2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/GiantAnvilShockEffectPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/GiantAnvilShockEffectPacket.java @@ -31,7 +31,7 @@ public record GiantAnvilShockEffectPacket(BlockPos centerPos, int radius) implem @Override public Type type() { - return TYPE; + return GiantAnvilShockEffectPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/GravitySourcesSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/GravitySourcesSyncPacket.java index 175ccae96e..7d8b038f9b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/GravitySourcesSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/GravitySourcesSyncPacket.java @@ -54,7 +54,7 @@ public void encode(FriendlyByteBuf buffer, GravitySourcesSyncPacket packet) { @Override public Type type() { - return TYPE; + return GravitySourcesSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeBlockPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeBlockPacket.java index 9c31ceffe3..432162f9f9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeBlockPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeBlockPacket.java @@ -39,7 +39,7 @@ public record HammerChangeBlockPacket(BlockPos pos, BlockState state) implements @Override public Type type() { - return TYPE; + return HammerChangeBlockPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeFlexibleMultiPartBlockPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeFlexibleMultiPartBlockPacket.java index f5361cb034..bc9767fda5 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeFlexibleMultiPartBlockPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/HammerChangeFlexibleMultiPartBlockPacket.java @@ -32,7 +32,7 @@ public record HammerChangeFlexibleMultiPartBlockPacket(BlockPos pos, BlockState @Override public Type type() { - return TYPE; + return HammerChangeFlexibleMultiPartBlockPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/HammerUsePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/HammerUsePacket.java index 8dca85dc13..bc44d43291 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/HammerUsePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/HammerUsePacket.java @@ -30,7 +30,7 @@ public record HammerUsePacket(BlockPos pos, InteractionHand hand, BlockHitResult @Override public Type type() { - return TYPE; + return HammerUsePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/HeliostatsIrradiationPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/HeliostatsIrradiationPacket.java index 3d36c0e6bf..b48bfbb91d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/HeliostatsIrradiationPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/HeliostatsIrradiationPacket.java @@ -36,7 +36,7 @@ private Optional irritatePosOptional() { @Override public Type type() { - return TYPE; + return HeliostatsIrradiationPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/InfiniteFluidTankBreakModifierPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/InfiniteFluidTankBreakModifierPacket.java index 802c12eec2..659fc84d7d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/InfiniteFluidTankBreakModifierPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/InfiniteFluidTankBreakModifierPacket.java @@ -29,7 +29,7 @@ public record InfiniteFluidTankBreakModifierPacket( @Override public Type type() { - return TYPE; + return InfiniteFluidTankBreakModifierPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/InspectionStateChangedPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/InspectionStateChangedPacket.java index 7bacbc8c51..a4e15c819f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/InspectionStateChangedPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/InspectionStateChangedPacket.java @@ -22,7 +22,7 @@ public record InspectionStateChangedPacket(Identifier id, boolean state) impleme @Override public Type type() { - return TYPE; + return InspectionStateChangedPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/IonoCraftBackpackFlyingPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/IonoCraftBackpackFlyingPacket.java index 8be39a3de6..7ce67742fe 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/IonoCraftBackpackFlyingPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/IonoCraftBackpackFlyingPacket.java @@ -29,7 +29,7 @@ public record IonoCraftBackpackFlyingPacket(int playerId, boolean flying) implem @Override public Type type() { - return TYPE; + return IonoCraftBackpackFlyingPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ItemDetectorChangeRangePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ItemDetectorChangeRangePacket.java index a509acbe29..3a45587136 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ItemDetectorChangeRangePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ItemDetectorChangeRangePacket.java @@ -19,7 +19,7 @@ public record ItemDetectorChangeRangePacket(int range) implements IServerboundPa @Override public Type type() { - return TYPE; + return ItemDetectorChangeRangePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/JewelCraftingAutoFillPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/JewelCraftingAutoFillPacket.java index 76798cf8d4..cc01dd90d6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/JewelCraftingAutoFillPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/JewelCraftingAutoFillPacket.java @@ -18,7 +18,7 @@ public record JewelCraftingAutoFillPacket() implements IServerboundPacket { @Override public Type type() { - return TYPE; + return JewelCraftingAutoFillPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/LaserEmitPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/LaserEmitPacket.java index ce278be2f3..4fa35a54ff 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/LaserEmitPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/LaserEmitPacket.java @@ -41,7 +41,7 @@ private Optional irradiatePosOptional() { @Override public Type type() { - return TYPE; + return LaserEmitPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/MachineCycleFilterModePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/MachineCycleFilterModePacket.java index dc15972e2b..5ba239da2a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/MachineCycleFilterModePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/MachineCycleFilterModePacket.java @@ -20,7 +20,7 @@ public record MachineCycleFilterModePacket(Mode filterMode) implements IServerbo @Override public Type type() { - return TYPE; + return MachineCycleFilterModePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/MachineEnableFilterPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/MachineEnableFilterPacket.java index b59a2fc336..078f76667b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/MachineEnableFilterPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/MachineEnableFilterPacket.java @@ -24,7 +24,7 @@ public record MachineEnableFilterPacket(boolean filterEnabled) implements ISensi @Override public Type type() { - return TYPE; + return MachineEnableFilterPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/MachineOutputDirectionPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/MachineOutputDirectionPacket.java index 7ee77bffe3..a8e79237fd 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/MachineOutputDirectionPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/MachineOutputDirectionPacket.java @@ -23,7 +23,7 @@ public record MachineOutputDirectionPacket(Direction direction) implements ISens @Override public Type type() { - return TYPE; + return MachineOutputDirectionPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/MutedSoundSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/MutedSoundSyncPacket.java index 7584730d9f..0cd12ea507 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/MutedSoundSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/MutedSoundSyncPacket.java @@ -23,7 +23,7 @@ public record MutedSoundSyncPacket(List sounds) implements IClientbo @Override public Type type() { - return TYPE; + return MutedSoundSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/OpenHammerAnvilPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/OpenHammerAnvilPacket.java index 8d91e21ceb..188017339d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/OpenHammerAnvilPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/OpenHammerAnvilPacket.java @@ -19,7 +19,7 @@ public record OpenHammerAnvilPacket(int menuSlotId) implements IServerboundPacke @Override public Type type() { - return TYPE; + return OpenHammerAnvilPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/PowerGridRemovePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/PowerGridRemovePacket.java index 97dba89e7b..4e1028e79a 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/PowerGridRemovePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/PowerGridRemovePacket.java @@ -26,7 +26,7 @@ public PowerGridRemovePacket(PowerGrid grid) { @Override public Type type() { - return TYPE; + return PowerGridRemovePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/PowerGridSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/PowerGridSyncPacket.java index 0eafeb1c42..9cb13d8bd6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/PowerGridSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/PowerGridSyncPacket.java @@ -24,7 +24,7 @@ public PowerGridSyncPacket(PowerGrid grid) { @Override public Type type() { - return TYPE; + return PowerGridSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/PulseGeneratorUpdatePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/PulseGeneratorUpdatePacket.java index f36e5a7dd9..3497a394ac 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/PulseGeneratorUpdatePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/PulseGeneratorUpdatePacket.java @@ -32,7 +32,7 @@ public record PulseGeneratorUpdatePacket( @Override public Type type() { - return TYPE; + return PulseGeneratorUpdatePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerRequestPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerRequestPacket.java index 161104838c..47eb65b563 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerRequestPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerRequestPacket.java @@ -35,7 +35,7 @@ public record RedstoneWirePowerRequestPacket(BlockPos pos) implements IServerbou @Override public Type type() { - return TYPE; + return RedstoneWirePowerRequestPacket.TYPE; } @Override @@ -48,7 +48,7 @@ public void handleOnServer(Player player) { return; } long gameTime = serverPlayer.level().getGameTime(); - Long lastRequest = LAST_REQUEST.put(serverPlayer, gameTime); + Long lastRequest = RedstoneWirePowerRequestPacket.LAST_REQUEST.put(serverPlayer, gameTime); if (lastRequest != null && lastRequest == gameTime) { // 客户端本地按位置限频,服务端再按玩家限频,防止修改客户端在同一 tick 批量探测网络。 return; diff --git a/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerResponsePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerResponsePacket.java index ed889226e9..906042b3f1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerResponsePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerResponsePacket.java @@ -36,7 +36,7 @@ public record RedstoneWirePowerResponsePacket(BlockPos pos, int power, int nonDu @Override public Type type() { - return TYPE; + return RedstoneWirePowerResponsePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerSyncPacket.java index 1a525cd40c..47706e99a2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/RedstoneWirePowerSyncPacket.java @@ -11,6 +11,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.ChunkPos; import java.util.ArrayList; import java.util.List; @@ -31,7 +32,7 @@ public RedstoneWirePowerSyncPacket decode(FriendlyByteBuf buffer) { long chunkPos = buffer.readLong(); boolean replace = buffer.readBoolean(); int groupCount = buffer.readVarInt(); - if (groupCount < 0 || groupCount > MAX_GROUPS) { + if (groupCount < 0 || groupCount > RedstoneWirePowerSyncPacket.MAX_GROUPS) { throw new DecoderException("Invalid redstone wire power group count: " + groupCount); } List groups = new ArrayList<>(groupCount); @@ -42,7 +43,7 @@ public RedstoneWirePowerSyncPacket decode(FriendlyByteBuf buffer) { throw new DecoderException("Invalid redstone wire power: " + power); } int count = buffer.readVarInt(); - if (count < 0 || count > MAX_POSITIONS - positionCount) { + if (count < 0 || count > RedstoneWirePowerSyncPacket.MAX_POSITIONS - positionCount) { throw new DecoderException("Invalid redstone wire power position count: " + count); } int[] positions = new int[count]; @@ -57,7 +58,7 @@ public RedstoneWirePowerSyncPacket decode(FriendlyByteBuf buffer) { @Override public void encode(FriendlyByteBuf buffer, RedstoneWirePowerSyncPacket packet) { - if (packet.groups().size() > MAX_GROUPS) { + if (packet.groups().size() > RedstoneWirePowerSyncPacket.MAX_GROUPS) { throw new IllegalArgumentException("Too many redstone wire power groups"); } buffer.writeLong(packet.chunkPos()); @@ -68,7 +69,7 @@ public void encode(FriendlyByteBuf buffer, RedstoneWirePowerSyncPacket packet) { if (group.power() < 0 || group.power() > 15) { throw new IllegalArgumentException("Invalid redstone wire power: " + group.power()); } - if (group.positions().length > MAX_POSITIONS - positionCount) { + if (group.positions().length > RedstoneWirePowerSyncPacket.MAX_POSITIONS - positionCount) { throw new IllegalArgumentException("Too many redstone wire power positions"); } buffer.writeByte(group.power()); @@ -86,7 +87,7 @@ public void encode(FriendlyByteBuf buffer, RedstoneWirePowerSyncPacket packet) { @Override public Type type() { - return TYPE; + return RedstoneWirePowerSyncPacket.TYPE; } @Override @@ -121,8 +122,8 @@ public static BlockPos unpack(long chunkPos, int packed) { if ((y & 0x8000) != 0) { y |= ~0xFFFF; } - int chunkX = net.minecraft.world.level.ChunkPos.getX(chunkPos); - int chunkZ = net.minecraft.world.level.ChunkPos.getZ(chunkPos); + int chunkX = ChunkPos.getX(chunkPos); + int chunkZ = ChunkPos.getZ(chunkPos); return new BlockPos((chunkX << 4) + (packed & 15), y, (chunkZ << 4) + ((packed >>> 4) & 15)); } diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ResonanceMiningEffectPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ResonanceMiningEffectPacket.java index 683c1826d5..6841b50319 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ResonanceMiningEffectPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ResonanceMiningEffectPacket.java @@ -24,7 +24,7 @@ public record ResonanceMiningEffectPacket(BlockPos pos, int durationTicks) imple @Override public Type type() { - return TYPE; + return ResonanceMiningEffectPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/RocketJumpPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/RocketJumpPacket.java index dd1c8c2e48..567770fd7f 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/RocketJumpPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/RocketJumpPacket.java @@ -21,7 +21,7 @@ public record RocketJumpPacket(double power) implements IClientboundPacket { @Override public Type type() { - return TYPE; + return RocketJumpPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/ScreenShakePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/ScreenShakePacket.java index 7723515d99..326f97ae71 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/ScreenShakePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/ScreenShakePacket.java @@ -71,7 +71,7 @@ public static ScreenShakePacket of(Vec3 center, float radius, ShakeType type) { @Override public Type type() { - return TYPE; + return ScreenShakePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SilencerAddMutedPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SilencerAddMutedPacket.java index 75fd5e19aa..aa3a41c255 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SilencerAddMutedPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SilencerAddMutedPacket.java @@ -19,7 +19,7 @@ public record SilencerAddMutedPacket(Identifier soundId) implements IServerbound @Override public Type type() { - return TYPE; + return SilencerAddMutedPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SilencerRemoveMutedPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SilencerRemoveMutedPacket.java index 2f9c2f0d09..dae64f416c 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SilencerRemoveMutedPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SilencerRemoveMutedPacket.java @@ -19,7 +19,7 @@ public record SilencerRemoveMutedPacket(Identifier soundId) implements IServerbo @Override public Type type() { - return TYPE; + return SilencerRemoveMutedPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SilencerSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SilencerSyncPacket.java index ddc1884c38..f3031f2f47 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SilencerSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SilencerSyncPacket.java @@ -27,7 +27,7 @@ public record SilencerSyncPacket(BlockPos pos, List sounds) implemen @Override public Type type() { - return TYPE; + return SilencerSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SliderInitPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SliderInitPacket.java index 033029c03c..b7b58756b1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SliderInitPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SliderInitPacket.java @@ -20,7 +20,7 @@ public record SliderInitPacket(int value) implements IClientboundPacket { @Override public Type type() { - return TYPE; + return SliderInitPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SliderUpdatePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SliderUpdatePacket.java index 55652df22e..72f833d96e 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SliderUpdatePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SliderUpdatePacket.java @@ -20,7 +20,7 @@ public record SliderUpdatePacket(int value) implements IServerboundPacket { @Override public Type type() { - return TYPE; + return SliderUpdatePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SlidingEntitySyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SlidingEntitySyncPacket.java index c7004535f7..22cf7962f1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SlidingEntitySyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SlidingEntitySyncPacket.java @@ -28,7 +28,7 @@ public record SlidingEntitySyncPacket(int id, List infos, Dire @Override public Type type() { - return TYPE; + return SlidingEntitySyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SlotDisableChangePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SlotDisableChangePacket.java index c99ac98a5b..469984e399 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SlotDisableChangePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SlotDisableChangePacket.java @@ -25,7 +25,7 @@ public record SlotDisableChangePacket(int index, boolean state) implements ISens @Override public Type type() { - return TYPE; + return SlotDisableChangePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterChangePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterChangePacket.java index aee0cbb89d..79d2772848 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterChangePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterChangePacket.java @@ -34,7 +34,7 @@ public SlotFilterChangePacket(int index, ItemStack filter, boolean forceCount) { @Override public Type type() { - return TYPE; + return SlotFilterChangePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterMaxStackSizeChangePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterMaxStackSizeChangePacket.java index 58e5488fba..0f78a85a90 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterMaxStackSizeChangePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SlotFilterMaxStackSizeChangePacket.java @@ -27,7 +27,7 @@ public record SlotFilterMaxStackSizeChangePacket(int index, int maxStackSize) im @Override public Type type() { - return TYPE; + return SlotFilterMaxStackSizeChangePacket.TYPE; } @Override @@ -45,9 +45,12 @@ public void handleOnServer(Player player) { filter.setSlotLimit(this.index, this.maxStackSize); if (filter instanceof BlockEntity be) { be.setChanged(); - be.getLevel().sendBlockUpdated(be.getBlockPos(), be.getBlockState(), be.getBlockState(), 3); + var level = be.getLevel(); + if (level != null) { + level.sendBlockUpdated(be.getBlockPos(), be.getBlockState(), be.getBlockState(), 3); + } } menu.flush(); PacketDistributor.sendToPlayer(Util.cast(player), this); } -} \ No newline at end of file +} diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SmartBlockPlacerActionPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SmartBlockPlacerActionPacket.java index ccd8a8fd47..db0af27fe6 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SmartBlockPlacerActionPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SmartBlockPlacerActionPacket.java @@ -40,7 +40,7 @@ public SmartBlockPlacerActionPacket(String action, int value) { @Override public Type type() { - return TYPE; + return SmartBlockPlacerActionPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerBlockEntitySyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerBlockEntitySyncPacket.java index 6de9cc55fa..4d989be5b7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerBlockEntitySyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerBlockEntitySyncPacket.java @@ -4,7 +4,9 @@ import dev.anvilcraft.lib.v2.network.packet.IPacket; import dev.dubhe.anvilcraft.AnvilCraft; import dev.dubhe.anvilcraft.block.entity.SpacetimeSupercomputerBlockEntity; +import dev.dubhe.anvilcraft.client.gui.screen.SpacetimeSupercomputerScreen; import io.netty.buffer.ByteBuf; +import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; @@ -23,7 +25,7 @@ public record SpacetimeSupercomputerBlockEntitySyncPacket(BlockPos pos) implemen @Override public Type type() { - return TYPE; + return SpacetimeSupercomputerBlockEntitySyncPacket.TYPE; } @Override @@ -36,8 +38,8 @@ public void handleOnClient(Player player) { } private void updateScreenIfOpen() { - var mc = net.minecraft.client.Minecraft.getInstance(); - if (mc.screen instanceof dev.dubhe.anvilcraft.client.gui.screen.SpacetimeSupercomputerScreen screen) { + var mc = Minecraft.getInstance(); + if (mc.screen instanceof SpacetimeSupercomputerScreen screen) { screen.updateGui(); } } diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerExecuteCommandPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerExecuteCommandPacket.java index d06ac7338e..49e61b7324 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerExecuteCommandPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SpacetimeSupercomputerExecuteCommandPacket.java @@ -28,7 +28,7 @@ public record SpacetimeSupercomputerExecuteCommandPacket(BlockPos pos, String co @Override public Type type() { - return TYPE; + return SpacetimeSupercomputerExecuteCommandPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/StructureDataSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/StructureDataSyncPacket.java index ef08483b48..34e3dbe704 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/StructureDataSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/StructureDataSyncPacket.java @@ -20,7 +20,7 @@ public record StructureDataSyncPacket(StructureData structureData) implements IC @Override public Type type() { - return TYPE; + return StructureDataSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewRequestPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewRequestPacket.java index 6e7abb6614..96ee8ded4d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewRequestPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewRequestPacket.java @@ -36,7 +36,7 @@ public record StructurePreviewRequestPacket(UUID structureUuid, String structure @Override public Type type() { - return TYPE; + return StructurePreviewRequestPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewResponsePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewResponsePacket.java index 78b70e06ff..588d1c64f2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewResponsePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/StructurePreviewResponsePacket.java @@ -32,7 +32,7 @@ public record StructurePreviewResponsePacket(UUID structureUuid, CompoundTag str @Override public Type type() { - return TYPE; + return StructurePreviewResponsePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerActionPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerActionPacket.java index 2c48ec9e4d..f9689e7e71 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerActionPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerActionPacket.java @@ -74,7 +74,7 @@ public enum RangeAxis { @Override public Type type() { - return TYPE; + return StructureScannerActionPacket.TYPE; } @Override @@ -97,9 +97,9 @@ public void handleOnServer(Player player) { } case RANGE_CHANGE -> { boolean validRange = switch (this.rangeAxis) { - case X -> validateAndApplyRange(blockEntity.getRangeX(), this.value); - case Y -> validateAndApplyRange(blockEntity.getRangeY(), this.value); - case Z -> validateAndApplyRange(blockEntity.getRangeZ(), this.value); + case X -> StructureScannerActionPacket.validateAndApplyRange(blockEntity.getRangeX(), this.value); + case Y -> StructureScannerActionPacket.validateAndApplyRange(blockEntity.getRangeY(), this.value); + case Z -> StructureScannerActionPacket.validateAndApplyRange(blockEntity.getRangeZ(), this.value); case NONE -> false; }; @@ -109,7 +109,7 @@ public void handleOnServer(Player player) { player.getName().getString(), this.value, this.rangeAxis, - this.rangeAxis != RangeAxis.NONE ? getRangeCount(blockEntity, this.rangeAxis) - 1 : 0 + this.rangeAxis != RangeAxis.NONE ? StructureScannerActionPacket.getRangeCount(blockEntity, this.rangeAxis) - 1 : 0 ); return; } diff --git a/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerRangeSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerRangeSyncPacket.java index e9ba8b636d..eec8ebad2d 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerRangeSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/StructureScannerRangeSyncPacket.java @@ -27,7 +27,7 @@ public record StructureScannerRangeSyncPacket(int rangeX, int rangeY, int rangeZ @Override public Type type() { - return TYPE; + return StructureScannerRangeSyncPacket.TYPE; } @Override @@ -35,13 +35,10 @@ public void handleOnClient(Player player) { if (Minecraft.getInstance().screen == null) { return; } - + if (player.containerMenu instanceof StructureScannerMenu menu) { StructureScannerBlockEntity blockEntity = menu.getBlockEntity(); - if (blockEntity == null) { - return; - } - + // 更新客户端的范围值 blockEntity.getRangeX().fromIndex(this.rangeX); blockEntity.getRangeY().fromIndex(this.rangeY); diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SwitchHeavyHalberdModePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SwitchHeavyHalberdModePacket.java index 7dc45a4c28..6cfdc96874 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SwitchHeavyHalberdModePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SwitchHeavyHalberdModePacket.java @@ -22,7 +22,7 @@ public record SwitchHeavyHalberdModePacket(InteractionHand hand, HeavyHalberdMod @Override public Type type() { - return TYPE; + return SwitchHeavyHalberdModePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SwitchMultitoolModePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SwitchMultitoolModePacket.java index e40c87a928..71ae0c1975 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SwitchMultitoolModePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SwitchMultitoolModePacket.java @@ -23,7 +23,7 @@ public record SwitchMultitoolModePacket(InteractionHand hand, MultitoolMode mode @Override public Type type() { - return TYPE; + return SwitchMultitoolModePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/SwitchResonateModePacket.java b/src/main/java/dev/dubhe/anvilcraft/network/SwitchResonateModePacket.java index ce58768d43..60769df9c9 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/SwitchResonateModePacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/SwitchResonateModePacket.java @@ -23,7 +23,7 @@ public record SwitchResonateModePacket(InteractionHand hand, int mode) implement @Override public Type type() { - return TYPE; + return SwitchResonateModePacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/TeslaAddFilterPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/TeslaAddFilterPacket.java index 84f7e5b91e..a4c71d8f2b 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/TeslaAddFilterPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/TeslaAddFilterPacket.java @@ -21,7 +21,7 @@ public record TeslaAddFilterPacket(String id, String arg) implements IServerboun @Override public Type type() { - return TYPE; + return TeslaAddFilterPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/TeslaFilterSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/TeslaFilterSyncPacket.java index 5f7a3ea90b..4b1244edb1 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/TeslaFilterSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/TeslaFilterSyncPacket.java @@ -29,7 +29,7 @@ public static TeslaFilterSyncPacket create(List> filte @Override public Type type() { - return TYPE; + return TeslaFilterSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/TeslaRemoveFilterPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/TeslaRemoveFilterPacket.java index 681ac63ea2..e7d687c992 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/TeslaRemoveFilterPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/TeslaRemoveFilterPacket.java @@ -21,7 +21,7 @@ public record TeslaRemoveFilterPacket(String id, String arg) implements IServerb @Override public Type type() { - return TYPE; + return TeslaRemoveFilterPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/TranscendenceGrindstoneSyncPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/TranscendenceGrindstoneSyncPacket.java index d0dafdbd28..8c2e03e6fb 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/TranscendenceGrindstoneSyncPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/TranscendenceGrindstoneSyncPacket.java @@ -23,7 +23,7 @@ public record TranscendenceGrindstoneSyncPacket(int index, boolean select) imple @Override public Type type() { - return TYPE; + return TranscendenceGrindstoneSyncPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/UpdateDisplayItemPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/UpdateDisplayItemPacket.java index 3886efa862..3665dbc1d2 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/UpdateDisplayItemPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/UpdateDisplayItemPacket.java @@ -24,7 +24,7 @@ public record UpdateDisplayItemPacket(ItemStack displayItem, BlockPos pos) imple @Override public Type type() { - return TYPE; + return UpdateDisplayItemPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/UpdatePropelPistonStoredEnergyPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/UpdatePropelPistonStoredEnergyPacket.java index 3e0d006c10..4f9eb987a7 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/UpdatePropelPistonStoredEnergyPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/UpdatePropelPistonStoredEnergyPacket.java @@ -24,7 +24,7 @@ public record UpdatePropelPistonStoredEnergyPacket(BlockPos pos, int energy) imp @Override public Type type() { - return TYPE; + return UpdatePropelPistonStoredEnergyPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/UsePillBoxPacket.java b/src/main/java/dev/dubhe/anvilcraft/network/UsePillBoxPacket.java index 43e6697aaa..40955beafc 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/UsePillBoxPacket.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/UsePillBoxPacket.java @@ -19,7 +19,7 @@ public record UsePillBoxPacket() implements IServerboundPacket { @Override public Type type() { - return TYPE; + return UsePillBoxPacket.TYPE; } @Override diff --git a/src/main/java/dev/dubhe/anvilcraft/network/multiple/EnergyWeaponMakePackets.java b/src/main/java/dev/dubhe/anvilcraft/network/multiple/EnergyWeaponMakePackets.java index 575ed18f6f..8df3e0c866 100644 --- a/src/main/java/dev/dubhe/anvilcraft/network/multiple/EnergyWeaponMakePackets.java +++ b/src/main/java/dev/dubhe/anvilcraft/network/multiple/EnergyWeaponMakePackets.java @@ -21,7 +21,7 @@ public record Make() implements IServerboundPacket { @Override public Type type() { - return TYPE; + return Make.TYPE; } @Override @@ -42,7 +42,7 @@ public record Select(int index) implements IServerboundPacket { @Override public Type