From c67b0536bcfc6da26ce13d841c2f6499cd318e01 Mon Sep 17 00:00:00 2001 From: IThundxr Date: Wed, 12 Feb 2025 20:06:12 -0500 Subject: [PATCH] Formatted perfectly - Format code with some basic inspections --- .../AbstractContraptionEntity.java | 19 +- .../content/contraptions/Contraption.java | 101 ++--- .../contraptions/ContraptionCollider.java | 9 +- .../ContraptionHandlerClient.java | 19 +- .../ControlledContraptionEntity.java | 21 +- .../OrientedContraptionEntity.java | 20 +- .../harvester/HarvesterMovementBehaviour.java | 19 +- .../plough/PloughMovementBehaviour.java | 13 +- .../actors/roller/RollerBlockEntity.java | 2 +- .../actors/trainControls/ControlsHandler.java | 8 +- .../trainControls/ControlsServerHandler.java | 12 +- .../bearing/ClockworkBearingBlockEntity.java | 6 +- .../StabilizedBearingMovementBehaviour.java | 14 +- .../chassis/ChassisBlockEntity.java | 9 +- .../chassis/ChassisRangeDisplay.java | 10 +- .../gantry/GantryCarriageBlock.java | 10 +- .../gantry/GantryContraptionEntity.java | 15 +- .../minecart/CouplingHandler.java | 6 +- .../minecart/CouplingPhysics.java | 18 +- .../minecart/MinecartCouplingItem.java | 7 +- .../capability/MinecartController.java | 14 +- .../mounted/CartAssemblerBlockEntity.java | 3 +- .../mounted/MinecartContraptionItem.java | 38 +- .../piston/PistonExtensionPoleBlock.java | 81 ++-- .../contraptions/pulley/PulleyBlock.java | 203 +++++----- .../pulley/PulleyBlockEntity.java | 11 +- .../sync/ContraptionInteractionPacket.java | 5 +- .../sync/ContraptionSeatMappingPacket.java | 3 +- .../decoration/copycat/CopycatBarsModel.java | 9 +- .../equipment/armor/BacktankArmorLayer.java | 12 +- .../equipment/armor/DivingBootsItem.java | 3 +- .../equipment/bell/BasicParticleData.java | 11 +- .../BlueprintAssignCompleteRecipePacket.java | 11 +- .../equipment/blueprint/BlueprintEntity.java | 41 +- .../equipment/blueprint/BlueprintItem.java | 23 +- .../equipment/blueprint/BlueprintMenu.java | 21 +- .../blueprint/BlueprintOverlayRenderer.java | 20 +- .../extendoGrip/ExtendoGripItem.java | 25 +- .../goggles/GoggleOverlayRenderer.java | 3 +- .../BuiltinPotatoProjectileTypes.java | 368 +++++++++--------- .../potatoCannon/PotatoProjectileEntity.java | 8 +- .../equipment/sandPaper/SandPaperItem.java | 14 +- .../symmetryWand/SymmetryWandItem.java | 7 +- .../equipment/toolbox/ToolboxBlockEntity.java | 20 +- .../toolbox/ToolboxDisposeAllPacket.java | 10 +- .../equipment/toolbox/ToolboxEquipPacket.java | 5 +- .../equipment/toolbox/ToolboxHandler.java | 11 +- .../equipment/toolbox/ToolboxMenu.java | 8 +- .../equipment/wrench/WrenchEventHandler.java | 4 +- .../content/equipment/wrench/WrenchItem.java | 7 +- .../content/fluids/drain/ItemDrainBlock.java | 12 +- .../fluids/particle/FluidParticleData.java | 6 +- .../create/content/fluids/pump/PumpBlock.java | 9 +- .../content/fluids/pump/PumpBlockEntity.java | 10 +- .../content/fluids/tank/FluidTankBlock.java | 52 +-- .../transfer/FluidDrainingBehaviour.java | 10 +- .../transfer/FluidFillingBehaviour.java | 7 +- .../content/kinetics/KineticDebugger.java | 13 +- .../content/kinetics/RotationPropagator.java | 20 +- .../base/GeneratingKineticBlockEntity.java | 3 +- .../content/kinetics/base/KineticBlock.java | 13 +- .../kinetics/base/KineticBlockEntity.java | 8 +- .../kinetics/base/KineticEffectHandler.java | 3 +- .../base/RotationIndicatorParticleData.java | 15 +- .../content/kinetics/belt/BeltBlock.java | 37 +- .../kinetics/belt/BeltBlockEntity.java | 8 +- .../content/kinetics/belt/BeltSlicer.java | 3 +- .../BeltCrusherInteractionHandler.java | 91 +++-- .../BeltFunnelInteractionHandler.java | 8 +- .../BeltTunnelInteractionHandler.java | 11 +- .../chainConveyor/ChainConveyorPackage.java | 2 +- .../crafter/ConnectedInputHandler.java | 6 +- .../kinetics/crank/HandCrankBlockEntity.java | 8 +- .../CrushingWheelControllerBlockEntity.java | 41 +- .../kinetics/deployer/DeployerFakePlayer.java | 12 +- .../kinetics/deployer/DeployerHandler.java | 20 +- .../kinetics/deployer/DeployerRenderer.java | 19 +- .../content/kinetics/fan/AirCurrent.java | 19 +- .../kinetics/fan/AirFlowParticleData.java | 23 +- .../kinetics/fan/EncasedFanBlockEntity.java | 7 +- .../kinetics/fan/NozzleBlockEntity.java | 18 +- .../content/kinetics/gauge/GaugeBlock.java | 8 +- .../AllArmInteractionPointTypes.java | 25 +- .../mechanicalArm/ArmBlockEntity.java | 5 +- .../ArmInteractionPointHandler.java | 9 +- .../mechanicalArm/ArmPlacementPacket.java | 4 +- .../kinetics/millstone/MillstoneBlock.java | 6 +- .../content/kinetics/saw/SawBlockEntity.java | 6 +- .../encased/EncasedCogRenderer.java | 7 +- .../encased/EncasedCogwheelBlock.java | 27 +- .../steamEngine/SteamJetParticleData.java | 9 +- .../kinetics/transmission/GearshiftBlock.java | 7 +- .../sequencer/SequencedGearshiftBlock.java | 13 +- .../kinetics/turntable/TurntableHandler.java | 9 +- .../content/legacy/ChromaticCompoundItem.java | 9 +- .../content/logistics/box/PackageEntity.java | 5 +- .../content/logistics/box/PackageItem.java | 23 +- .../logistics/chute/ChuteBlockEntity.java | 6 +- .../content/logistics/chute/ChuteItem.java | 3 +- .../logistics/depot/EjectorTargetHandler.java | 6 +- .../factoryBoard/FactoryPanelBehaviour.java | 31 +- .../factoryBoard/FactoryPanelConnection.java | 11 +- .../FactoryPanelSupportBehaviour.java | 9 +- .../logistics/funnel/AbstractFunnelBlock.java | 12 +- .../postbox/PostboxBlockEntity.java | 4 +- .../tableCloth/ShoppingListItem.java | 8 +- .../logistics/tunnel/BrassTunnelBlock.java | 9 +- .../logistics/vault/ItemVaultBlock.java | 8 +- .../content/processing/basin/BasinBlock.java | 17 +- .../processing/basin/BasinBlockEntity.java | 3 +- .../content/processing/basin/BasinRecipe.java | 15 +- .../processing/burner/BlazeBurnerBlock.java | 22 +- .../processing/burner/BlazeBurnerHandler.java | 7 +- .../sequenced/SequencedAssemblyRecipe.java | 3 +- .../processing/sequenced/SequencedRecipe.java | 5 +- .../content/redstone/link/LinkRenderer.java | 5 +- .../link/RedstoneLinkNetworkHandler.java | 5 +- .../LecternControllerBlockEntity.java | 14 +- .../LinkedControllerItemRenderer.java | 26 +- .../LinkedControllerServerHandler.java | 15 +- .../redstone/rail/ControllerRailBlock.java | 28 +- .../cannon/SchematicannonScreen.java | 3 +- .../schematics/client/SchematicHandler.java | 14 +- .../content/trains/CubeParticleData.java | 19 +- .../trains/display/FlapDisplayBlock.java | 28 +- .../content/trains/graph/TrackGraph.java | 19 +- .../content/trains/schedule/ScheduleItem.java | 12 +- .../ScheduleItemEntityInteraction.java | 6 +- .../content/trains/signal/EdgeGroupColor.java | 8 +- .../content/trains/station/GlobalStation.java | 5 +- .../trains/station/StationBlockEntity.java | 4 +- .../trains/station/StationRenderer.java | 12 +- .../content/trains/track/TrackBlockItem.java | 4 +- .../content/trains/track/TrackModel.java | 17 +- .../content/trains/track/TrackPlacement.java | 45 +-- .../trains/track/TrackTargetingBehaviour.java | 9 +- .../block/render/ReducedDestroyEffects.java | 4 +- .../behaviour/BlockEntityBehaviour.java | 11 +- .../blockEntity/behaviour/ValueBox.java | 2 +- .../EdgeInteractionRenderer.java | 3 +- .../filtering/FilteringRenderer.java | 8 +- .../scrollValue/ScrollValueRenderer.java | 10 +- .../foundation/data/CreateRegistrate.java | 41 +- .../create/foundation/item/ItemHelper.java | 31 +- .../foundation/particle/AirParticleData.java | 17 +- .../particle/ICustomParticleData.java | 13 +- .../ICustomParticleDataWithSprite.java | 13 +- .../command/HighlightCommand.java | 14 +- .../ReplaceInCommandBlocksCommand.java | 16 +- .../ponder/scenes/ItemVaultScenes.java | 10 +- 150 files changed, 1297 insertions(+), 1396 deletions(-) diff --git a/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java index d29961056b..395fc6b7bf 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/AbstractContraptionEntity.java @@ -244,8 +244,8 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit Vec3 transformedVector = toGlobalVector(Vec3.atLowerCornerOf(seat) .add(.5, passenger.getMyRidingOffset() + ySize - .15f, .5), partialTicks) - .add(VecHelper.getCenterOf(BlockPos.ZERO)) - .subtract(0.5, ySize, 0.5); + .add(VecHelper.getCenterOf(BlockPos.ZERO)) + .subtract(0.5, ySize, 0.5); return transformedVector; } @@ -255,7 +255,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit return true; return contraption.getSeatMapping() .size() < contraption.getSeats() - .size(); + .size(); } public Component getContraptionName() { @@ -287,7 +287,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit } public boolean handlePlayerInteraction(Player player, BlockPos localPos, Direction side, - InteractionHand interactionHand) { + InteractionHand interactionHand) { int indexOfSeat = contraption.getSeats() .indexOf(localPos); if (indexOfSeat == -1 || AllItems.WRENCH.isIn(player.getItemInHand(interactionHand))) { @@ -487,11 +487,10 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit skipActorStop = false; for (Entity entity : getPassengers()) { - if (!(entity instanceof OrientedContraptionEntity)) + if (!(entity instanceof OrientedContraptionEntity orientedCE)) continue; if (!contraption.stabilizedSubContraptions.containsKey(entity.getUUID())) continue; - OrientedContraptionEntity orientedCE = (OrientedContraptionEntity) entity; if (orientedCE.contraption != null && orientedCE.contraption.stalled) { contraption.stalled = true; break; @@ -529,7 +528,7 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit } protected boolean shouldActorTrigger(MovementContext context, StructureBlockInfo blockInfo, MovementBehaviour actor, - Vec3 actorPosition, BlockPos gridPosition) { + Vec3 actorPosition, BlockPos gridPosition) { Vec3 previousPosition = context.position; if (previousPosition == null) return false; @@ -731,7 +730,8 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit } @Override - protected void doWaterSplashEffect() {} + protected void doWaterSplashEffect() { + } public Contraption getContraption() { return contraption; @@ -798,7 +798,8 @@ public abstract class AbstractContraptionEntity extends Entity implements IEntit @Override // Make sure nothing can move contraptions out of the way - public void setDeltaMovement(Vec3 motionIn) {} + public void setDeltaMovement(Vec3 motionIn) { + } @Override public PushReaction getPistonPushReaction() { diff --git a/src/main/java/com/simibubi/create/content/contraptions/Contraption.java b/src/main/java/com/simibubi/create/content/contraptions/Contraption.java index 9a595c5b98..0572798966 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/Contraption.java +++ b/src/main/java/com/simibubi/create/content/contraptions/Contraption.java @@ -207,7 +207,7 @@ public abstract class Contraption { } protected boolean addToInitialFrontier(Level world, BlockPos pos, Direction forcedDirection, - Queue frontier) throws AssemblyException { + Queue frontier) throws AssemblyException { return true; } @@ -298,9 +298,11 @@ public abstract class Contraption { } } - /** move the first block in frontier queue */ + /** + * move the first block in frontier queue + */ protected boolean moveBlock(Level world, @Nullable Direction forcedDirection, Queue frontier, - Set visited) throws AssemblyException { + Set visited) throws AssemblyException { BlockPos pos = frontier.poll(); if (pos == null) return false; @@ -324,7 +326,7 @@ public abstract class Contraption { if (AllBlocks.BELT.has(state)) moveBelt(pos, frontier, visited, state); - if (AllBlocks.WINDMILL_BEARING.has(state) && world.getBlockEntity(pos)instanceof WindmillBearingBlockEntity wbbe) + if (AllBlocks.WINDMILL_BEARING.has(state) && world.getBlockEntity(pos) instanceof WindmillBearingBlockEntity wbbe) wbbe.disassembleForMovement(); if (AllBlocks.GANTRY_CARRIAGE.has(state)) @@ -354,7 +356,7 @@ public abstract class Contraption { } // Bogeys tend to have sticky sides - if (state.getBlock()instanceof AbstractBogeyBlock bogey) + if (state.getBlock() instanceof AbstractBogeyBlock bogey) for (Direction d : bogey.getStickySurfaces(world, pos, state)) if (!visited.contains(pos.relative(d))) frontier.add(pos.relative(d)); @@ -434,7 +436,7 @@ public abstract class Contraption { } protected void movePistonHead(Level world, BlockPos pos, Queue frontier, Set visited, - BlockState state) { + BlockState state) { Direction direction = state.getValue(MechanicalPistonHeadBlock.FACING); BlockPos offset = pos.relative(direction.getOpposite()); if (!visited.contains(offset)) { @@ -457,7 +459,7 @@ public abstract class Contraption { } protected void movePistonPole(Level world, BlockPos pos, Queue frontier, Set visited, - BlockState state) { + BlockState state) { for (Direction d : Iterate.directionsInAxis(state.getValue(PistonExtensionPoleBlock.FACING) .getAxis())) { BlockPos offset = pos.relative(d); @@ -480,7 +482,7 @@ public abstract class Contraption { } protected void moveGantryPinion(Level world, BlockPos pos, Queue frontier, Set visited, - BlockState state) { + BlockState state) { BlockPos offset = pos.relative(state.getValue(GantryCarriageBlock.FACING)); if (!visited.contains(offset)) frontier.add(offset); @@ -496,7 +498,7 @@ public abstract class Contraption { } protected void moveGantryShaft(Level world, BlockPos pos, Queue frontier, Set visited, - BlockState state) { + BlockState state) { for (Direction d : Iterate.directions) { BlockPos offset = pos.relative(d); if (!visited.contains(offset)) { @@ -570,7 +572,7 @@ public abstract class Contraption { } private boolean moveMechanicalPiston(Level world, BlockPos pos, Queue frontier, Set visited, - BlockState state) throws AssemblyException { + BlockState state) throws AssemblyException { Direction direction = state.getValue(MechanicalPistonBlock.FACING); PistonState pistonState = state.getValue(MechanicalPistonBlock.STATE); if (pistonState == PistonState.MOVING) @@ -594,11 +596,10 @@ public abstract class Contraption { } private boolean moveChassis(Level world, BlockPos pos, Direction movementDirection, Queue frontier, - Set visited) { + Set visited) { BlockEntity be = world.getBlockEntity(pos); - if (!(be instanceof ChassisBlockEntity)) + if (!(be instanceof ChassisBlockEntity chassis)) return false; - ChassisBlockEntity chassis = (ChassisBlockEntity) be; chassis.addAttachedChasses(frontier, visited); List includedBlockPositions = chassis.getIncludedBlockPositions(movementDirection, false); if (includedBlockPositions == null) @@ -669,8 +670,8 @@ public abstract class Contraption { if (be instanceof CreativeCrateBlockEntity && ((CreativeCrateBlockEntity) be).getBehaviour(FilteringBehaviour.TYPE) - .getFilter() - .isEmpty()) + .getFilter() + .isEmpty()) hasUniversalCreativeCrate = true; } @@ -680,8 +681,8 @@ public abstract class Contraption { CompoundTag nbt = structureBlockInfo.nbt(); BlockPos controllerPos = nbt.contains("Controller") ? - toLocalPos(NbtUtils.readBlockPos(nbt.getCompound("Controller"))) : - localPos; + toLocalPos(NbtUtils.readBlockPos(nbt.getCompound("Controller"))) : + localPos; nbt.put("Controller", NbtUtils.writeBlockPos(controllerPos)); if (multiBlockBE.isController() && multiBlockBE.getHeight() <= 1 && multiBlockBE.getWidth() <= 1) { @@ -731,17 +732,17 @@ public abstract class Contraption { capturedMultiblocks.clear(); nbt.getList("CapturedMultiblocks", Tag.TAG_COMPOUND).forEach(c -> { - CompoundTag tag = (CompoundTag) c; - if (!tag.contains("Controller", Tag.TAG_COMPOUND) && !tag.contains("Parts", Tag.TAG_LIST)) - return; + CompoundTag tag = (CompoundTag) c; + if (!tag.contains("Controller", Tag.TAG_COMPOUND) && !tag.contains("Parts", Tag.TAG_LIST)) + return; - BlockPos controllerPos = NbtUtils.readBlockPos(tag.getCompound("Controller")); - tag.getList("Parts", Tag.TAG_COMPOUND).forEach(part -> { - BlockPos partPos = NbtUtils.readBlockPos((CompoundTag) part); - StructureBlockInfo partInfo = this.blocks.get(partPos); - capturedMultiblocks.put(controllerPos, partInfo); - }); + BlockPos controllerPos = NbtUtils.readBlockPos(tag.getCompound("Controller")); + tag.getList("Parts", Tag.TAG_COMPOUND).forEach(part -> { + BlockPos partPos = NbtUtils.readBlockPos((CompoundTag) part); + StructureBlockInfo partInfo = this.blocks.get(partPos); + capturedMultiblocks.put(controllerPos, partInfo); }); + }); storage.read(nbt, spawnData, this); @@ -1026,7 +1027,7 @@ public abstract class Contraption { } private static StructureBlockInfo readStructureBlockInfo(CompoundTag blockListEntry, - HashMapPalette palette) { + HashMapPalette palette) { return new StructureBlockInfo(BlockPos.of(blockListEntry.getLong("Pos")), Objects.requireNonNull(palette.valueFor(blockListEntry.getInt("State"))), blockListEntry.contains("Data") ? blockListEntry.getCompound("Data") : null); @@ -1052,7 +1053,7 @@ public abstract class Contraption { for (boolean brittles : Iterate.trueAndFalse) { for (Iterator iterator = blocks.values() - .iterator(); iterator.hasNext();) { + .iterator(); iterator.hasNext(); ) { StructureBlockInfo block = iterator.next(); if (brittles != BlockMovementChecks.isBrittle(block.state())) continue; @@ -1157,7 +1158,7 @@ public abstract class Contraption { if (blockState.getDestroySpeed(world, targetPos) == -1 || (state.getCollisionShape(world, targetPos) .isEmpty() && !blockState.getCollisionShape(world, targetPos) - .isEmpty())) { + .isEmpty())) { if (targetPos.getY() == world.getMinBuildHeight()) targetPos = targetPos.above(); world.levelEvent(2001, targetPos, Block.getId(state)); @@ -1178,7 +1179,7 @@ public abstract class Contraption { state = state.setValue(SlidingDoorBlock.VISIBLE, !state.getValue(SlidingDoorBlock.OPEN)) .setValue(SlidingDoorBlock.POWERED, false); // Stop Sculk shriekers from getting "stuck" if moved mid-shriek. - if(state.is(Blocks.SCULK_SHRIEKER)){ + if (state.is(Blocks.SCULK_SHRIEKER)) { state = Blocks.SCULK_SHRIEKER.defaultBlockState(); } @@ -1197,7 +1198,7 @@ public abstract class Contraption { CompoundTag tag = block.nbt(); // Temporary fix: Calling load(CompoundTag tag) on a Sculk sensor causes it to not react to vibrations. - if(state.is(Blocks.SCULK_SENSOR) || state.is(Blocks.SCULK_SHRIEKER)) + if (state.is(Blocks.SCULK_SENSOR) || state.is(Blocks.SCULK_SHRIEKER)) tag = null; if (blockEntity != null) @@ -1464,19 +1465,19 @@ public abstract class Contraption { simplifiedEntityColliderProvider.cancel(false); } simplifiedEntityColliderProvider = CompletableFuture.supplyAsync(() -> { - VoxelShape combinedShape = Shapes.empty(); - for (Entry entry : blocks.entrySet()) { - StructureBlockInfo info = entry.getValue(); - BlockPos localPos = entry.getKey(); - VoxelShape collisionShape = info.state().getCollisionShape(world, localPos, CollisionContext.empty()); - if (collisionShape.isEmpty()) - continue; - combinedShape = Shapes.joinUnoptimized(combinedShape, - collisionShape.move(localPos.getX(), localPos.getY(), localPos.getZ()), BooleanOp.OR); - } - return combinedShape.optimize() - .toAabbs(); - }) + VoxelShape combinedShape = Shapes.empty(); + for (Entry entry : blocks.entrySet()) { + StructureBlockInfo info = entry.getValue(); + BlockPos localPos = entry.getKey(); + VoxelShape collisionShape = info.state().getCollisionShape(world, localPos, CollisionContext.empty()); + if (collisionShape.isEmpty()) + continue; + combinedShape = Shapes.joinUnoptimized(combinedShape, + collisionShape.move(localPos.getX(), localPos.getY(), localPos.getZ()), BooleanOp.OR); + } + return combinedShape.optimize() + .toAabbs(); + }) .thenAccept(r -> { simplifiedEntityColliders = Optional.of(r); }); @@ -1484,12 +1485,12 @@ public abstract class Contraption { public static float getRadius(Set blocks, Direction.Axis axis) { switch (axis) { - case X: - return getMaxDistSqr(blocks, BlockPos::getY, BlockPos::getZ); - case Y: - return getMaxDistSqr(blocks, BlockPos::getX, BlockPos::getZ); - case Z: - return getMaxDistSqr(blocks, BlockPos::getX, BlockPos::getY); + case X: + return getMaxDistSqr(blocks, BlockPos::getY, BlockPos::getZ); + case Y: + return getMaxDistSqr(blocks, BlockPos::getX, BlockPos::getZ); + case Z: + return getMaxDistSqr(blocks, BlockPos::getX, BlockPos::getY); } throw new IllegalStateException("Impossible axis"); diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java index 808a444a02..1ac2602b9c 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionCollider.java @@ -145,7 +145,7 @@ public class ContraptionCollider { // Make player 'shorter' to make it less likely to become stuck if (playerType == PlayerType.CLIENT && entityBounds.getYsize() > 1) entityBounds = entityBounds.contract(0, 2 / 16f, 0); - + motion = motion.subtract(contraptionMotion); motion = rotationMatrix.transform(motion); @@ -772,15 +772,12 @@ public class ContraptionCollider { MovementBehaviour movementBehaviour = AllMovementBehaviours.getBehaviour(blockInfo.state()); if (movementBehaviour != null) { - if (movementBehaviour instanceof BlockBreakingMovementBehaviour) { - BlockBreakingMovementBehaviour behaviour = (BlockBreakingMovementBehaviour) movementBehaviour; + if (movementBehaviour instanceof BlockBreakingMovementBehaviour behaviour) { if (!behaviour.canBreak(world, colliderPos, collidedState) && !emptyCollider) return true; continue; } - if (movementBehaviour instanceof HarvesterMovementBehaviour) { - HarvesterMovementBehaviour harvesterMovementBehaviour = - (HarvesterMovementBehaviour) movementBehaviour; + if (movementBehaviour instanceof HarvesterMovementBehaviour harvesterMovementBehaviour) { if (!harvesterMovementBehaviour.isValidCrop(world, colliderPos, collidedState) && !harvesterMovementBehaviour.isValidOther(world, colliderPos, collidedState) && !emptyCollider) diff --git a/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java b/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java index 93a092b467..ec5bb7cabe 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ContraptionHandlerClient.java @@ -49,9 +49,8 @@ public class ContraptionHandlerClient { public static void preventRemotePlayersWalkingAnimations(PlayerTickEvent event) { if (event.phase == Phase.START) return; - if (!(event.player instanceof RemotePlayer)) + if (!(event.player instanceof RemotePlayer remotePlayer)) return; - RemotePlayer remotePlayer = (RemotePlayer) event.player; CompoundTag data = remotePlayer.getPersistentData(); if (!data.contains("LastOverrideLimbSwingUpdate")) return; @@ -92,7 +91,7 @@ public class ContraptionHandlerClient { Collection> contraptions = ContraptionHandler.loadedContraptions.get(mc.level) .values(); - + double bestDistance = Double.MAX_VALUE; BlockHitResult bestResult = null; AbstractContraptionEntity bestEntity = null; @@ -108,23 +107,23 @@ public class ContraptionHandlerClient { BlockHitResult rayTraceResult = rayTraceContraption(origin, target, contraptionEntity); if (rayTraceResult == null) continue; - + double distance = contraptionEntity.toGlobalVector(rayTraceResult.getLocation(), 1).distanceTo(origin); if (distance > bestDistance) continue; - + bestResult = rayTraceResult; bestDistance = distance; bestEntity = contraptionEntity; } - + if (bestResult == null) return; - + InteractionHand hand = event.getHand(); Direction face = bestResult.getDirection(); BlockPos pos = bestResult.getBlockPos(); - + if (bestEntity.handlePlayerInteraction(player, pos, face, hand)) { AllPackets.getChannel() .sendToServer(new ContraptionInteractionPacket(bestEntity, hand, pos, face)); @@ -136,7 +135,7 @@ public class ContraptionHandlerClient { } private static boolean handleSpecialInteractions(AbstractContraptionEntity contraptionEntity, Player player, - BlockPos localPos, Direction side, InteractionHand interactionHand) { + BlockPos localPos, Direction side, InteractionHand interactionHand) { if (AllItems.WRENCH.isIn(player.getItemInHand(interactionHand)) && contraptionEntity instanceof CarriageContraptionEntity car) return TrainRelocator.carriageWrenched(car.toGlobalVector(VecHelper.getCenterOf(localPos), 1), car); @@ -157,7 +156,7 @@ public class ContraptionHandlerClient { @Nullable public static BlockHitResult rayTraceContraption(Vec3 origin, Vec3 target, - AbstractContraptionEntity contraptionEntity) { + AbstractContraptionEntity contraptionEntity) { Vec3 localOrigin = contraptionEntity.toLocalVector(origin, 1); Vec3 localTarget = contraptionEntity.toLocalVector(target, 1); Contraption contraption = contraptionEntity.getContraption(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java index 2eae9b00d4..8c8378b256 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/ControlledContraptionEntity.java @@ -44,7 +44,7 @@ public class ControlledContraptionEntity extends AbstractContraptionEntity { } public static ControlledContraptionEntity create(Level world, IControlContraption controller, - Contraption contraption) { + Contraption contraption) { ControlledContraptionEntity entity = new ControlledContraptionEntity(AllEntityTypes.CONTROLLED_CONTRAPTION.get(), world); entity.controllerPos = controller.getBlockPosition(); @@ -144,11 +144,13 @@ public class ControlledContraptionEntity extends AbstractContraptionEntity { } @Override - public void teleportTo(double p_70634_1_, double p_70634_3_, double p_70634_5_) {} + public void teleportTo(double p_70634_1_, double p_70634_3_, double p_70634_5_) { + } @Override @OnlyIn(Dist.CLIENT) - public void lerpTo(double x, double y, double z, float yw, float pt, int inc, boolean t) {} + public void lerpTo(double x, double y, double z, float yw, float pt, int inc, boolean t) { + } protected void tickContraption() { angleDelta = angle - prevAngle; @@ -173,14 +175,13 @@ public class ControlledContraptionEntity extends AbstractContraptionEntity { @Override protected boolean shouldActorTrigger(MovementContext context, StructureBlockInfo blockInfo, MovementBehaviour actor, - Vec3 actorPosition, BlockPos gridPosition) { + Vec3 actorPosition, BlockPos gridPosition) { if (super.shouldActorTrigger(context, blockInfo, actor, actorPosition, gridPosition)) return true; // Special activation timer for actors in the center of a bearing contraption - if (!(contraption instanceof BearingContraption)) + if (!(contraption instanceof BearingContraption bc)) return false; - BearingContraption bc = (BearingContraption) contraption; Direction facing = bc.getFacing(); Vec3 activeAreaOffset = actor.getActiveAreaOffset(context); if (!activeAreaOffset.multiply(VecHelper.axisAlingedPlaneOf(Vec3.atLowerCornerOf(facing.getNormal()))) @@ -248,10 +249,10 @@ public class ControlledContraptionEntity extends AbstractContraptionEntity { if (axis != null) { TransformStack.of(matrixStack) - .nudge(getId()) - .center() - .rotateDegrees(angle, axis) - .uncenter(); + .nudge(getId()) + .center() + .rotateDegrees(angle, axis) + .uncenter(); } } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java index d94ded193d..e98f98ea49 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/OrientedContraptionEntity.java @@ -98,7 +98,7 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { } public static OrientedContraptionEntity createAtYaw(Level world, Contraption contraption, - Direction initialOrientation, float initialYaw) { + Direction initialOrientation, float initialYaw) { OrientedContraptionEntity entity = create(world, contraption, initialOrientation); entity.startAtYaw(initialYaw); entity.manuallyPlaced = true; @@ -258,8 +258,7 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { boolean rotationLock = false; boolean pauseWhileRotating = false; boolean wasStalled = isStalled(); - if (contraption instanceof MountedContraption) { - MountedContraption mountedContraption = (MountedContraption) contraption; + if (contraption instanceof MountedContraption mountedContraption) { rotationLock = mountedContraption.rotationMode == CartMovementMode.ROTATION_LOCKED; pauseWhileRotating = mountedContraption.rotationMode == CartMovementMode.ROTATE_PAUSED; } @@ -345,15 +344,13 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { return false; } - if (contraption instanceof StabilizedContraption) { - if (!(riding instanceof OrientedContraptionEntity)) + if (contraption instanceof StabilizedContraption stabilized) { + if (!(riding instanceof OrientedContraptionEntity parent)) return false; - StabilizedContraption stabilized = (StabilizedContraption) contraption; Direction facing = stabilized.getFacing(); if (facing.getAxis() .isVertical()) return false; - OrientedContraptionEntity parent = (OrientedContraptionEntity) riding; prevYaw = yaw; yaw = AngleHelper.wrapAngle180(getInitialYaw() - parent.getInitialYaw()) - parent.getViewYRot(1); return false; @@ -372,12 +369,10 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { Vec3 motion = movementVector.normalize(); if (!rotationLock) { - if (riding instanceof AbstractMinecart) { - AbstractMinecart minecartEntity = (AbstractMinecart) riding; + if (riding instanceof AbstractMinecart minecartEntity) { BlockPos railPosition = minecartEntity.getCurrentRailPosition(); BlockState blockState = level().getBlockState(railPosition); - if (blockState.getBlock() instanceof BaseRailBlock) { - BaseRailBlock abstractRailBlock = (BaseRailBlock) blockState.getBlock(); + if (blockState.getBlock() instanceof BaseRailBlock abstractRailBlock) { RailShape railDirection = abstractRailBlock.getRailDirection(blockState, level(), railPosition, minecartEntity); motion = VecHelper.project(motion, MinecartSim2020.getRailVec(railDirection)); @@ -407,9 +402,8 @@ public class OrientedContraptionEntity extends AbstractContraptionEntity { } protected void powerFurnaceCartWithFuelFromStorage(Entity riding) { - if (!(riding instanceof MinecartFurnace)) + if (!(riding instanceof MinecartFurnace furnaceCart)) return; - MinecartFurnace furnaceCart = (MinecartFurnace) riding; // Notify to not trigger serialization side-effects isSerializingFurnaceCart = true; diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java index 8a81f33d72..41b3d06928 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/harvester/HarvesterMovementBehaviour.java @@ -44,13 +44,13 @@ public class HarvesterMovementBehaviour implements MovementBehaviour { public boolean isActive(MovementContext context) { return MovementBehaviour.super.isActive(context) && !VecHelper.isVecPointingTowards(context.relativeMotion, context.state.getValue(HarvesterBlock.FACING) - .getOpposite()); + .getOpposite()); } @Override public Vec3 getActiveAreaOffset(MovementContext context) { return Vec3.atLowerCornerOf(context.state.getValue(HarvesterBlock.FACING) - .getNormal()) + .getNormal()) .scale(.45); } @@ -97,8 +97,7 @@ public class HarvesterMovementBehaviour implements MovementBehaviour { boolean harvestPartial = AllConfigs.server().kinetics.harvestPartiallyGrown.get(); boolean replant = AllConfigs.server().kinetics.harvesterReplants.get(); - if (state.getBlock() instanceof CropBlock) { - CropBlock crop = (CropBlock) state.getBlock(); + if (state.getBlock() instanceof CropBlock crop) { if (harvestPartial) return state != crop.getStateForAge(0) || !replant; return crop.isMaxAge(state); @@ -107,9 +106,8 @@ public class HarvesterMovementBehaviour implements MovementBehaviour { if (state.getCollisionShape(world, pos) .isEmpty() || state.getBlock() instanceof CocoaBlock) { for (Property property : state.getProperties()) { - if (!(property instanceof IntegerProperty)) + if (!(property instanceof IntegerProperty ageProperty)) continue; - IntegerProperty ageProperty = (IntegerProperty) property; if (!property.getName() .equals(BlockStateProperties.AGE_1.getName())) continue; @@ -168,8 +166,7 @@ public class HarvesterMovementBehaviour implements MovementBehaviour { } Block block = state.getBlock(); - if (block instanceof CropBlock) { - CropBlock crop = (CropBlock) block; + if (block instanceof CropBlock crop) { return crop.getStateForAge(0); } if (block == Blocks.SWEET_BERRY_BUSH) { @@ -208,15 +205,15 @@ public class HarvesterMovementBehaviour implements MovementBehaviour { @Override public void renderInContraption(MovementContext context, VirtualRenderWorld renderWorld, - ContraptionMatrices matrices, MultiBufferSource buffers) { - if (!VisualizationManager.supportsVisualization(context.world)) + ContraptionMatrices matrices, MultiBufferSource buffers) { + if (!VisualizationManager.supportsVisualization(context.world)) HarvesterRenderer.renderInContraption(context, renderWorld, matrices, buffers); } @Nullable @Override public ActorVisual createVisual(VisualizationContext visualizationContext, VirtualRenderWorld simulationWorld, - MovementContext movementContext) { + MovementContext movementContext) { return new HarvesterActorVisual(visualizationContext, simulationWorld, movementContext); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughMovementBehaviour.java index 01db954a90..7448ea6c5a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/plough/PloughMovementBehaviour.java @@ -41,7 +41,7 @@ public class PloughMovementBehaviour extends BlockBreakingMovementBehaviour { public boolean isActive(MovementContext context) { return super.isActive(context) && !VecHelper.isVecPointingTowards(context.relativeMotion, context.state.getValue(PloughBlock.FACING) - .getOpposite()); + .getOpposite()); } @Override @@ -86,7 +86,7 @@ public class PloughMovementBehaviour extends BlockBreakingMovementBehaviour { @Override public Vec3 getActiveAreaOffset(MovementContext context) { return Vec3.atLowerCornerOf(context.state.getValue(PloughBlock.FACING) - .getNormal()) + .getNormal()) .scale(.45); } @@ -120,12 +120,11 @@ public class PloughMovementBehaviour extends BlockBreakingMovementBehaviour { protected void onBlockBroken(MovementContext context, BlockPos pos, BlockState brokenState) { super.onBlockBroken(context, pos, brokenState); - if (brokenState.getBlock() == Blocks.SNOW && context.world instanceof ServerLevel) { - ServerLevel world = (ServerLevel) context.world; + if (brokenState.getBlock() == Blocks.SNOW && context.world instanceof ServerLevel world) { brokenState.getDrops(new LootParams.Builder(world).withParameter(LootContextParams.BLOCK_STATE, brokenState) - .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos)) - .withParameter(LootContextParams.THIS_ENTITY, getPlayer(context)) - .withParameter(LootContextParams.TOOL, new ItemStack(Items.IRON_SHOVEL))) + .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos)) + .withParameter(LootContextParams.THIS_ENTITY, getPlayer(context)) + .withParameter(LootContextParams.TOOL, new ItemStack(Items.IRON_SHOVEL))) .forEach(s -> dropItem(context, s)); } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerBlockEntity.java index b7bca082cb..0493ef5702 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/roller/RollerBlockEntity.java @@ -49,7 +49,7 @@ public class RollerBlockEntity extends SmartBlockEntity { @Override public void addBehaviours(List behaviours) { behaviours.add(filtering = new FilteringBehaviour(this, new RollerValueBox(3))); - behaviours.add(mode = new ScrollOptionBehaviour(RollingMode.class, + behaviours.add(mode = new ScrollOptionBehaviour<>(RollingMode.class, CreateLang.translateDirect("contraptions.roller_mode"), this, new RollerValueBox(-3))); filtering.setLabel(CreateLang.translateDirect("contraptions.mechanical_roller.pave_material")); diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java index 2667c87e27..d445205627 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsHandler.java @@ -37,7 +37,7 @@ public class ControlsHandler { } public static void startControlling(AbstractContraptionEntity entity, BlockPos controllerLocalPos) { - entityRef = new WeakReference(entity); + entityRef = new WeakReference<>(entity); controlsPos = controllerLocalPos; Minecraft.getInstance().player.displayClientMessage( @@ -108,9 +108,9 @@ public class ControlsHandler { // Keepalive Pressed Keys if (packetCooldown == 0) { // if (!pressedKeys.isEmpty()) { - AllPackets.getChannel() - .sendToServer(new ControlsInputPacket(pressedKeys, true, entity.getId(), controlsPos, false)); - packetCooldown = PACKET_RATE; + AllPackets.getChannel() + .sendToServer(new ControlsInputPacket(pressedKeys, true, entity.getId(), controlsPos, false)); + packetCooldown = PACKET_RATE; // } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsServerHandler.java b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsServerHandler.java index 2f5ef0af3f..580ad57dbb 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsServerHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/actors/trainControls/ControlsServerHandler.java @@ -24,7 +24,7 @@ public class ControlsServerHandler { public static void tick(LevelAccessor world) { Map map = receivedInputs.get(world); for (Iterator> iterator = map.entrySet() - .iterator(); iterator.hasNext();) { + .iterator(); iterator.hasNext(); ) { Entry entry = iterator.next(); ControlsContext ctx = entry.getValue(); @@ -35,7 +35,7 @@ public class ControlsServerHandler { continue; } - for (Iterator entryIterator = list.iterator(); entryIterator.hasNext();) { + for (Iterator entryIterator = list.iterator(); entryIterator.hasNext(); ) { ManuallyPressedKey pressedKey = entryIterator.next(); pressedKey.decrement(); if (!pressedKey.isAlive()) @@ -61,7 +61,7 @@ public class ControlsServerHandler { } public static void receivePressed(LevelAccessor world, AbstractContraptionEntity entity, BlockPos controlsPos, - UUID uniqueID, Collection collect, boolean pressed) { + UUID uniqueID, Collection collect, boolean pressed) { Map map = receivedInputs.get(world); if (map.containsKey(uniqueID) && map.get(uniqueID).entity != entity) @@ -70,9 +70,9 @@ public class ControlsServerHandler { ControlsContext ctx = map.computeIfAbsent(uniqueID, $ -> new ControlsContext(entity, controlsPos)); Collection list = ctx.keys; - WithNext: for (Integer activated : collect) { - for (Iterator iterator = list.iterator(); iterator.hasNext();) { - ManuallyPressedKey entry = iterator.next(); + WithNext: + for (Integer activated : collect) { + for (ManuallyPressedKey entry : list) { Integer inputType = entry.getSecond(); if (inputType.equals(activated)) { if (!pressed) diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlockEntity.java index 86566349bd..30250093e4 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/ClockworkBearingBlockEntity.java @@ -291,10 +291,9 @@ public class ClockworkBearingBlockEntity extends KineticBlockEntity @Override public void attach(ControlledContraptionEntity contraption) { - if (!(contraption.getContraption() instanceof ClockworkContraption)) + if (!(contraption.getContraption() instanceof ClockworkContraption cc)) return; - ClockworkContraption cc = (ClockworkContraption) contraption.getContraption(); setChanged(); Direction facing = getBlockState().getValue(BlockStateProperties.FACING); BlockPos anchor = worldPosition.relative(facing, cc.offset + 1); @@ -380,9 +379,8 @@ public class ClockworkBearingBlockEntity extends KineticBlockEntity @Override public boolean isAttachedTo(AbstractContraptionEntity contraption) { - if (!(contraption.getContraption() instanceof ClockworkContraption)) + if (!(contraption.getContraption() instanceof ClockworkContraption cc)) return false; - ClockworkContraption cc = (ClockworkContraption) contraption.getContraption(); if (cc.handType == HandType.HOUR) return this.hourHand == contraption; else diff --git a/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java b/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java index 947b3dc54b..9a3b9b1891 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java +++ b/src/main/java/com/simibubi/create/content/contraptions/bearing/StabilizedBearingMovementBehaviour.java @@ -37,14 +37,16 @@ public class StabilizedBearingMovementBehaviour implements MovementBehaviour { public ItemStack canBeDisabledVia(MovementContext context) { return null; } -@Override + + @Override public boolean disableBlockEntityRendering() { return true; } + @Override @OnlyIn(Dist.CLIENT) public void renderInContraption(MovementContext context, VirtualRenderWorld renderWorld, - ContraptionMatrices matrices, MultiBufferSource buffer) { + ContraptionMatrices matrices, MultiBufferSource buffer) { if (VisualizationManager.supportsVisualization(context.world)) return; @@ -79,7 +81,7 @@ public class StabilizedBearingMovementBehaviour implements MovementBehaviour { @Nullable @Override public ActorVisual createVisual(VisualizationContext visualizationContext, VirtualRenderWorld simulationWorld, - MovementContext movementContext) { + MovementContext movementContext) { return new StabilizedBearingVisual(visualizationContext, simulationWorld, movementContext); } @@ -91,13 +93,11 @@ public class StabilizedBearingMovementBehaviour implements MovementBehaviour { Direction.Axis axis = facing.getAxis(); AbstractContraptionEntity entity = context.contraption.entity; - if (entity instanceof ControlledContraptionEntity) { - ControlledContraptionEntity controlledCE = (ControlledContraptionEntity) entity; + if (entity instanceof ControlledContraptionEntity controlledCE) { if (context.contraption.canBeStabilized(facing, context.localPos)) offset = -controlledCE.getAngle(renderPartialTicks); - } else if (entity instanceof OrientedContraptionEntity) { - OrientedContraptionEntity orientedCE = (OrientedContraptionEntity) entity; + } else if (entity instanceof OrientedContraptionEntity orientedCE) { if (axis.isVertical()) offset = -orientedCE.getViewYRot(renderPartialTicks); else { diff --git a/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java index 2105489ee4..351957fd09 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisBlockEntity.java @@ -108,8 +108,7 @@ public class ChassisBlockEntity extends SmartBlockEntity { continue; visited.add(current); BlockEntity blockEntity = level.getBlockEntity(current); - if (blockEntity instanceof ChassisBlockEntity) { - ChassisBlockEntity chassis = (ChassisBlockEntity) blockEntity; + if (blockEntity instanceof ChassisBlockEntity chassis) { collected.add(chassis); visited.add(current); chassis.addAttachedChasses(frontier, visited); @@ -126,7 +125,7 @@ public class ChassisBlockEntity extends SmartBlockEntity { if (isRadial()) { // Collect chain of radial chassis - for (int offset : new int[] { -1, 1 }) { + for (int offset : new int[]{-1, 1}) { Direction direction = Direction.get(AxisDirection.POSITIVE, axis); BlockPos currentPos = worldPosition.relative(direction, offset); if (!level.isLoaded(currentPos)) @@ -174,7 +173,7 @@ public class ChassisBlockEntity extends SmartBlockEntity { Direction facing = Direction.get(AxisDirection.POSITIVE, axis); int chassisRange = visualize ? currentlySelectedRange : getRange(); - for (int offset : new int[] { 1, -1 }) { + for (int offset : new int[]{1, -1}) { if (offset == -1) facing = facing.getOpposite(); boolean sticky = state.getValue(block.getGlueableSide(state, facing)); @@ -255,7 +254,7 @@ public class ChassisBlockEntity extends SmartBlockEntity { class ChassisScrollValueBehaviour extends BulkScrollValueBehaviour { public ChassisScrollValueBehaviour(Component label, SmartBlockEntity be, ValueBoxTransform slot, - Function> groupGetter) { + Function> groupGetter) { super(label, be, slot, groupGetter); } diff --git a/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisRangeDisplay.java b/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisRangeDisplay.java index ed18a0a3b7..d76edfcb61 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisRangeDisplay.java +++ b/src/main/java/com/simibubi/create/content/contraptions/chassis/ChassisRangeDisplay.java @@ -92,7 +92,7 @@ public class ChassisRangeDisplay { boolean hasWrench = AllItems.WRENCH.isIn(player.getMainHandItem()); for (Iterator iterator = entries.keySet() - .iterator(); iterator.hasNext();) { + .iterator(); iterator.hasNext(); ) { BlockPos pos = iterator.next(); Entry entry = entries.get(pos); if (tickEntry(entry, hasWrench)) @@ -100,7 +100,7 @@ public class ChassisRangeDisplay { Outliner.getInstance().keep(entry.getOutlineKey()); } - for (Iterator iterator = groupEntries.iterator(); iterator.hasNext();) { + for (Iterator iterator = groupEntries.iterator(); iterator.hasNext(); ) { GroupEntry group = iterator.next(); if (tickEntry(group, hasWrench)) { iterator.remove(); @@ -114,18 +114,16 @@ public class ChassisRangeDisplay { return; HitResult over = Minecraft.getInstance().hitResult; - if (!(over instanceof BlockHitResult)) + if (!(over instanceof BlockHitResult ray)) return; - BlockHitResult ray = (BlockHitResult) over; BlockPos pos = ray.getBlockPos(); BlockEntity blockEntity = world.getBlockEntity(pos); if (blockEntity == null || blockEntity.isRemoved()) return; - if (!(blockEntity instanceof ChassisBlockEntity)) + if (!(blockEntity instanceof ChassisBlockEntity chassisBlockEntity)) return; boolean ctrl = AllKeys.ctrlDown(); - ChassisBlockEntity chassisBlockEntity = (ChassisBlockEntity) blockEntity; if (ctrl) { GroupEntry existingGroupForPos = getExistingGroupForPos(pos); diff --git a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java index 94cd3edea1..f8748e8091 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryCarriageBlock.java @@ -3,7 +3,6 @@ package com.simibubi.create.content.contraptions.gantry; import com.simibubi.create.AllBlockEntityTypes; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.kinetics.base.DirectionalAxisKineticBlock; -import com.simibubi.create.content.kinetics.base.IRotate; import com.simibubi.create.content.kinetics.gantry.GantryShaftBlock; import com.simibubi.create.foundation.block.IBE; @@ -54,7 +53,7 @@ public class GantryCarriageBlock extends DirectionalAxisKineticBlock implements } public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, - BlockHitResult hit) { + BlockHitResult hit) { if (!player.mayBuild() || player.isShiftKeyDown()) return InteractionResult.PASS; if (player.getItemInHand(handIn) @@ -77,7 +76,7 @@ public class GantryCarriageBlock extends DirectionalAxisKineticBlock implements @Override public void neighborChanged(BlockState state, Level world, BlockPos pos, Block p_220069_4_, BlockPos updatePos, - boolean p_220069_6_) { + boolean p_220069_6_) { if (updatePos.equals(pos.relative(state.getValue(FACING) .getOpposite())) && !canSurvive(state, world, pos)) world.destroyBlock(pos, true); @@ -85,7 +84,7 @@ public class GantryCarriageBlock extends DirectionalAxisKineticBlock implements @Override public BlockState updateShape(BlockState state, Direction direction, BlockState otherState, LevelAccessor world, - BlockPos pos, BlockPos p_196271_6_) { + BlockPos pos, BlockPos p_196271_6_) { if (state.getValue(FACING) != direction.getOpposite()) return state; return cycleAxisIfNecessary(state, direction, otherState); @@ -108,9 +107,8 @@ public class GantryCarriageBlock extends DirectionalAxisKineticBlock implements } public static Axis getValidGantryShaftAxis(BlockState state) { - if (!(state.getBlock() instanceof GantryCarriageBlock)) + if (!(state.getBlock() instanceof GantryCarriageBlock block)) return Axis.Y; - IRotate block = (IRotate) state.getBlock(); Axis rotationAxis = block.getRotationAxis(state); Axis facingAxis = state.getValue(FACING) .getAxis(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java index edc359b6d6..72fcd45194 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/gantry/GantryContraptionEntity.java @@ -102,7 +102,7 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { BlockPos gantryShaftPos = BlockPos.containing(currentPosition).relative(facing.getOpposite()); BlockEntity be = level().getBlockEntity(gantryShaftPos); - if (!(be instanceof GantryShaftBlockEntity) || !AllBlocks.GANTRY_SHAFT.has(be.getBlockState())) { + if (!(be instanceof GantryShaftBlockEntity gantryShaftBlockEntity) || !AllBlocks.GANTRY_SHAFT.has(be.getBlockState())) { if (!level().isClientSide) { setContraptionMotion(Vec3.ZERO); disassemble(); @@ -112,7 +112,6 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { BlockState blockState = be.getBlockState(); Direction direction = blockState.getValue(GantryShaftBlock.FACING); - GantryShaftBlockEntity gantryShaftBlockEntity = (GantryShaftBlockEntity) be; float pinionMovementSpeed = gantryShaftBlockEntity.getPinionMovementSpeed(); if (blockState.getValue(GantryShaftBlock.POWERED) || pinionMovementSpeed == 0) { @@ -185,11 +184,13 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { } @Override - public void teleportTo(double p_70634_1_, double p_70634_3_, double p_70634_5_) {} + public void teleportTo(double p_70634_1_, double p_70634_3_, double p_70634_5_) { + } @Override @OnlyIn(Dist.CLIENT) - public void lerpTo(double x, double y, double z, float yw, float pt, int inc, boolean t) {} + public void lerpTo(double x, double y, double z, float yw, float pt, int inc, boolean t) { + } @Override protected void handleStallInformation(double x, double y, double z, float angle) { @@ -204,7 +205,8 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { @Override @OnlyIn(Dist.CLIENT) - public void applyLocalTransforms(PoseStack matrixStack, float partialTicks) {} + public void applyLocalTransforms(PoseStack matrixStack, float partialTicks) { + } public void updateClientMotion() { float modifier = movementAxis.getAxisDirection() @@ -231,9 +233,8 @@ public class GantryContraptionEntity extends AbstractContraptionEntity { @OnlyIn(Dist.CLIENT) public static void handlePacket(GantryContraptionUpdatePacket packet) { Entity entity = Minecraft.getInstance().level.getEntity(packet.entityID); - if (!(entity instanceof GantryContraptionEntity)) + if (!(entity instanceof GantryContraptionEntity ce)) return; - GantryContraptionEntity ce = (GantryContraptionEntity) entity; ce.axisMotion = packet.motion; ce.clientOffsetDiff = packet.coord - ce.getAxisCoord(); ce.sequencedOffsetLimit = packet.sequenceLimit; diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java index 6973b8b2b6..a6ffadb570 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingHandler.java @@ -72,9 +72,9 @@ public class CouplingHandler { Entity entity1 = world.getEntity(cartId1); Entity entity2 = world.getEntity(cartId2); - if (!(entity1 instanceof AbstractMinecart)) + if (!(entity1 instanceof AbstractMinecart cart1)) return false; - if (!(entity2 instanceof AbstractMinecart)) + if (!(entity2 instanceof AbstractMinecart cart2)) return false; String tooMany = "two_couplings_max"; @@ -97,8 +97,6 @@ public class CouplingHandler { return false; } - AbstractMinecart cart1 = (AbstractMinecart) entity1; - AbstractMinecart cart2 = (AbstractMinecart) entity2; UUID mainID = cart1.getUUID(); UUID connectedID = cart2.getUUID(); MinecartController mainController = CapabilityMinecartController.getIfPresent(world, mainID); diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingPhysics.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingPhysics.java index 1b82db1f88..3f4620646a 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingPhysics.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/CouplingPhysics.java @@ -40,7 +40,7 @@ public class CouplingPhysics { Couple corrections = Couple.create(null, null); Couple maxSpeed = carts.map(AbstractMinecart::getMaxCartSpeedOnRail); boolean firstLoop = true; - for (boolean current : new boolean[] { true, false, true }) { + for (boolean current : new boolean[]{true, false, true}) { AbstractMinecart cart = carts.get(current); AbstractMinecart otherCart = carts.get(!current); @@ -54,8 +54,7 @@ public class CouplingPhysics { BlockPos railPosition = cart.getCurrentRailPosition(); BlockState railState = world.getBlockState(railPosition.above()); - if (railState.getBlock() instanceof BaseRailBlock) { - BaseRailBlock block = (BaseRailBlock) railState.getBlock(); + if (railState.getBlock() instanceof BaseRailBlock block) { shape = block.getRailDirection(railState, world, railPosition, cart); } @@ -71,7 +70,7 @@ public class CouplingPhysics { correction = shape != null ? followLinkOnRail(link, pos, correctionMagnitude, MinecartSim2020.getRailVec(shape)).subtract(pos) : link.normalize() - .scale(correctionMagnitude); + .scale(correctionMagnitude); float maxResolveSpeed = 1.75f; correction = VecHelper.clamp(correction, Math.min(maxResolveSpeed, maxSpeed.get(current))); @@ -102,15 +101,14 @@ public class CouplingPhysics { Couple shapes = carts.mapWithContext((minecart, current) -> { Vec3 vec = nextPositions.get(current); int x = Mth.floor(vec.x()); - int y = Mth.floor(vec.y()); - int z = Mth.floor(vec.z()); - BlockPos pos = new BlockPos(x, y - 1, z); - if (minecart.level().getBlockState(pos).is(BlockTags.RAILS)) pos = pos.below(); + int y = Mth.floor(vec.y()); + int z = Mth.floor(vec.z()); + BlockPos pos = new BlockPos(x, y - 1, z); + if (minecart.level().getBlockState(pos).is(BlockTags.RAILS)) pos = pos.below(); BlockPos railPosition = pos; BlockState railState = world.getBlockState(railPosition.above()); - if (!(railState.getBlock() instanceof BaseRailBlock)) + if (!(railState.getBlock() instanceof BaseRailBlock block)) return null; - BaseRailBlock block = (BaseRailBlock) railState.getBlock(); return block.getRailDirection(railState, world, railPosition, minecart); }); diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java index 0137a02c81..cbc88121f2 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/MinecartCouplingItem.java @@ -33,9 +33,8 @@ public class MinecartCouplingItem extends Item { @SubscribeEvent(priority = EventPriority.HIGH) public static void handleInteractionWithMinecart(PlayerInteractEvent.EntityInteract event) { Entity interacted = event.getTarget(); - if (!(interacted instanceof AbstractMinecart)) + if (!(interacted instanceof AbstractMinecart minecart)) return; - AbstractMinecart minecart = (AbstractMinecart) interacted; Player player = event.getEntity(); if (player == null) return; @@ -60,7 +59,7 @@ public class MinecartCouplingItem extends Item { } protected static boolean onCouplingInteractOnMinecart(PlayerInteractEvent.EntityInteract event, - AbstractMinecart minecart, Player player, MinecartController controller) { + AbstractMinecart minecart, Player player, MinecartController controller) { Level world = event.getLevel(); if (controller.isFullyCoupled()) { if (!world.isClientSide) @@ -73,7 +72,7 @@ public class MinecartCouplingItem extends Item { } private static boolean onWrenchInteractOnMinecart(EntityInteract event, AbstractMinecart minecart, Player player, - MinecartController controller) { + MinecartController controller) { int couplings = (controller.isConnectedToCoupling() ? 1 : 0) + (controller.isLeadingCoupling() ? 1 : 0); if (couplings == 0) return false; diff --git a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java index 42b0bc6603..d51250a723 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java +++ b/src/main/java/com/simibubi/create/content/contraptions/minecart/capability/MinecartController.java @@ -105,15 +105,15 @@ public class MinecartController implements INBTSerializable { int j = Mth.floor(cart.getY()); int k = Mth.floor(cart.getZ()); if (world.getBlockState(new BlockPos(i, j - 1, k)) - .is(BlockTags.RAILS)) { + .is(BlockTags.RAILS)) { --j; } BlockPos blockpos = new BlockPos(i, j, k); BlockState blockstate = world.getBlockState(blockpos); if (cart.canUseRail() && blockstate.is(BlockTags.RAILS) - && blockstate.getBlock() instanceof PoweredRailBlock - && ((PoweredRailBlock) blockstate.getBlock()) - .isActivatorRail()) { + && blockstate.getBlock() instanceof PoweredRailBlock + && ((PoweredRailBlock) blockstate.getBlock()) + .isActivatorRail()) { if (cart.isVehicle()) { cart.ejectPassengers(); } @@ -218,9 +218,8 @@ public class MinecartController implements INBTSerializable { if (passengers.isEmpty()) return; Entity entity = passengers.get(0); - if (!(entity instanceof OrientedContraptionEntity)) + if (!(entity instanceof OrientedContraptionEntity contraption)) return; - OrientedContraptionEntity contraption = (OrientedContraptionEntity) entity; UUID couplingId = contraption.getCouplingId(); if (couplingId == cd.mainCartID) { contraption.setCouplingId(cd.connectedCartID); @@ -394,7 +393,8 @@ public class MinecartController implements INBTSerializable { Vec3 motion; float yaw, pitch; - private StallData() {} + private StallData() { + } StallData(AbstractMinecart entity) { position = entity.position(); diff --git a/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java index 8e2c2b0fe7..3aa85fb96b 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/mounted/CartAssemblerBlockEntity.java @@ -186,9 +186,8 @@ public class CartAssemblerBlockEntity extends SmartBlockEntity implements IDispl return; Entity entity = cart.getPassengers() .get(0); - if (!(entity instanceof OrientedContraptionEntity)) + if (!(entity instanceof OrientedContraptionEntity contraption)) return; - OrientedContraptionEntity contraption = (OrientedContraptionEntity) entity; UUID couplingId = contraption.getCouplingId(); if (couplingId == null) { diff --git a/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java b/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java index 94839ce8e1..e0d963db13 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java +++ b/src/main/java/com/simibubi/create/content/contraptions/mounted/MinecartContraptionItem.java @@ -111,7 +111,7 @@ public class MinecartContraptionItem extends Item { BlockState blockstate1 = world.getBlockState(blockpos.below()); RailShape railshape1 = blockstate1.getBlock() instanceof BaseRailBlock ? ((BaseRailBlock) blockstate1.getBlock()).getRailDirection(blockstate1, world, blockpos.below(), - null) + null) : RailShape.NORTH_SOUTH; if (direction != Direction.DOWN && railshape1.isAscending()) { d3 = -0.4D; @@ -174,7 +174,7 @@ public class MinecartContraptionItem extends Item { } public static void addContraptionToMinecart(Level world, ItemStack itemstack, AbstractMinecart cart, - @Nullable Direction newFacing) { + @Nullable Direction newFacing) { CompoundTag tag = itemstack.getOrCreateTag(); if (tag.contains("Contraption")) { CompoundTag contraptionTag = tag.getCompound("Contraption"); @@ -185,7 +185,7 @@ public class MinecartContraptionItem extends Item { OrientedContraptionEntity contraptionEntity = newFacing == null ? OrientedContraptionEntity.create(world, mountedContraption, intialOrientation) : OrientedContraptionEntity.createAtYaw(world, mountedContraption, intialOrientation, - newFacing.toYRot()); + newFacing.toYRot()); contraptionEntity.startRiding(cart); contraptionEntity.setPos(cart.getX(), cart.getY(), cart.getZ()); @@ -212,20 +212,18 @@ public class MinecartContraptionItem extends Item { return; if (entity instanceof AbstractContraptionEntity) entity = entity.getVehicle(); - if (!(entity instanceof AbstractMinecart)) + if (!(entity instanceof AbstractMinecart cart)) return; if (!entity.isAlive()) return; if (player instanceof DeployerFakePlayer dfp && dfp.onMinecartContraption) return; - AbstractMinecart cart = (AbstractMinecart) entity; Type type = cart.getMinecartType(); if (type != Type.RIDEABLE && type != Type.FURNACE && type != Type.CHEST) return; List passengers = cart.getPassengers(); - if (passengers.isEmpty() || !(passengers.get(0) instanceof OrientedContraptionEntity)) + if (passengers.isEmpty() || !(passengers.get(0) instanceof OrientedContraptionEntity oce)) return; - OrientedContraptionEntity oce = (OrientedContraptionEntity) passengers.get(0); Contraption contraption = oce.getContraption(); if (ContraptionMovementSetting.isNoPickup(contraption.getBlocks() @@ -244,14 +242,14 @@ public class MinecartContraptionItem extends Item { contraption.stop(event.getLevel()); for (MutablePair pair : contraption.getActors()) - if (AllMovementBehaviours.getBehaviour(pair.left.state())instanceof PortableStorageInterfaceMovement psim) + if (AllMovementBehaviours.getBehaviour(pair.left.state()) instanceof PortableStorageInterfaceMovement psim) psim.reset(pair.right); ItemStack generatedStack = create(type, oce).setHoverName(entity.getCustomName()); if (ContraptionPickupLimiting.isTooLargeForPickup(generatedStack.serializeNBT())) { MutableComponent message = CreateLang.translateDirect("contraption.minecart_contraption_too_big") - .withStyle(ChatFormatting.RED); + .withStyle(ChatFormatting.RED); player.displayClientMessage(message, true); return; } @@ -272,17 +270,17 @@ public class MinecartContraptionItem extends Item { ItemStack stack = ItemStack.EMPTY; switch (type) { - case RIDEABLE: - stack = AllItems.MINECART_CONTRAPTION.asStack(); - break; - case FURNACE: - stack = AllItems.FURNACE_MINECART_CONTRAPTION.asStack(); - break; - case CHEST: - stack = AllItems.CHEST_MINECART_CONTRAPTION.asStack(); - break; - default: - break; + case RIDEABLE: + stack = AllItems.MINECART_CONTRAPTION.asStack(); + break; + case FURNACE: + stack = AllItems.FURNACE_MINECART_CONTRAPTION.asStack(); + break; + case CHEST: + stack = AllItems.CHEST_MINECART_CONTRAPTION.asStack(); + break; + default: + break; } if (stack.isEmpty()) diff --git a/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java b/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java index 66586a728d..4148c3f8bc 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/piston/PistonExtensionPoleBlock.java @@ -45,12 +45,12 @@ import net.minecraft.world.phys.shapes.VoxelShape; public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock implements IWrenchable, SimpleWaterloggedBlock { - private static final int placementHelperId = PlacementHelpers.register(PlacementHelper.get()); + private static final int placementHelperId = PlacementHelpers.register(PlacementHelper.get()); - public PistonExtensionPoleBlock(Properties properties) { - super(properties); - registerDefaultState(defaultBlockState().setValue(FACING, Direction.UP).setValue(BlockStateProperties.WATERLOGGED, false)); - } + public PistonExtensionPoleBlock(Properties properties) { + super(properties); + registerDefaultState(defaultBlockState().setValue(FACING, Direction.UP).setValue(BlockStateProperties.WATERLOGGED, false)); + } @Override public PushReaction getPistonPushReaction(BlockState state) { @@ -65,7 +65,7 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme BlockPos pistonHead = null; BlockPos pistonBase = null; - for (int modifier : new int[] { 1, -1 }) { + for (int modifier : new int[]{1, -1}) { for (int offset = modifier; modifier * offset < MechanicalPistonBlock.maxAllowedPistonPoles(); offset += modifier) { BlockPos currentPos = pos.relative(direction, offset); @@ -89,18 +89,17 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme if (pistonHead != null && pistonBase != null && worldIn.getBlockState(pistonHead) .getValue(BlockStateProperties.FACING) == worldIn.getBlockState(pistonBase) - .getValue(BlockStateProperties.FACING)) { + .getValue(BlockStateProperties.FACING)) { final BlockPos basePos = pistonBase; BlockPos.betweenClosedStream(pistonBase, pistonHead) - .filter(p -> !p.equals(pos) && !p.equals(basePos)) - .forEach(p -> worldIn.destroyBlock(p, !player.isCreative())); + .filter(p -> !p.equals(pos) && !p.equals(basePos)) + .forEach(p -> worldIn.destroyBlock(p, !player.isCreative())); worldIn.setBlockAndUpdate(basePos, worldIn.getBlockState(basePos) - .setValue(MechanicalPistonBlock.STATE, PistonState.RETRACTED)); + .setValue(MechanicalPistonBlock.STATE, PistonState.RETRACTED)); BlockEntity be = worldIn.getBlockEntity(basePos); - if (be instanceof MechanicalPistonBlockEntity) { - MechanicalPistonBlockEntity baseBE = (MechanicalPistonBlockEntity) be; + if (be instanceof MechanicalPistonBlockEntity baseBE) { baseBE.offset = 0; baseBE.onLengthBroken(); } @@ -120,18 +119,18 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme FluidState FluidState = context.getLevel() .getFluidState(context.getClickedPos()); return defaultBlockState().setValue(FACING, context.getClickedFace() - .getOpposite()) + .getOpposite()) .setValue(BlockStateProperties.WATERLOGGED, Boolean.valueOf(FluidState.getType() == Fluids.WATER)); } @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { + BlockHitResult ray) { ItemStack heldItem = player.getItemInHand(hand); - IPlacementHelper placementHelper = PlacementHelpers.get(placementHelperId); - if (placementHelper.matchesItem(heldItem) && !player.isShiftKeyDown()) - return placementHelper.getOffset(player, world, state, pos, ray).placeInWorld(world, (BlockItem) heldItem.getItem(), player, hand, ray); + IPlacementHelper placementHelper = PlacementHelpers.get(placementHelperId); + if (placementHelper.matchesItem(heldItem) && !player.isShiftKeyDown()) + return placementHelper.getOffset(player, world, state, pos, ray).placeInWorld(world, (BlockItem) heldItem.getItem(), player, hand, ray); return InteractionResult.PASS; } @@ -148,38 +147,38 @@ public class PistonExtensionPoleBlock extends WrenchableDirectionalBlock impleme super.createBlockStateDefinition(builder); } - @Override - public BlockState updateShape(BlockState state, Direction direction, BlockState neighbourState, LevelAccessor world, BlockPos pos, BlockPos neighbourPos) { - if (state.getValue(BlockStateProperties.WATERLOGGED)) - world.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); - return state; - } + @Override + public BlockState updateShape(BlockState state, Direction direction, BlockState neighbourState, LevelAccessor world, BlockPos pos, BlockPos neighbourPos) { + if (state.getValue(BlockStateProperties.WATERLOGGED)) + world.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); + return state; + } @Override public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { return false; } - @MethodsReturnNonnullByDefault - public static class PlacementHelper extends PoleHelper { + @MethodsReturnNonnullByDefault + public static class PlacementHelper extends PoleHelper { - private static final PlacementHelper instance = new PlacementHelper(); + private static final PlacementHelper instance = new PlacementHelper(); - public static PlacementHelper get() { - return instance; - } + public static PlacementHelper get() { + return instance; + } - private PlacementHelper(){ - super( - AllBlocks.PISTON_EXTENSION_POLE::has, - state -> state.getValue(FACING).getAxis(), - FACING - ); - } + private PlacementHelper() { + super( + AllBlocks.PISTON_EXTENSION_POLE::has, + state -> state.getValue(FACING).getAxis(), + FACING + ); + } - @Override - public Predicate getItemPredicate() { - return AllBlocks.PISTON_EXTENSION_POLE::isIn; - } - } + @Override + public Predicate getItemPredicate() { + return AllBlocks.PISTON_EXTENSION_POLE::isIn; + } + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java index b770e2050b..2765aa0979 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java +++ b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlock.java @@ -34,14 +34,13 @@ import net.minecraft.world.phys.shapes.VoxelShape; public class PulleyBlock extends HorizontalAxisKineticBlock implements IBE { - public PulleyBlock(Properties properties) { - super(properties); - } + public PulleyBlock(Properties properties) { + super(properties); + } - private static void onRopeBroken(Level world, BlockPos pulleyPos) { + private static void onRopeBroken(Level world, BlockPos pulleyPos) { BlockEntity be = world.getBlockEntity(pulleyPos); - if (be instanceof PulleyBlockEntity) { - PulleyBlockEntity pulley = (PulleyBlockEntity) be; + if (be instanceof PulleyBlockEntity pulley) { pulley.initialOffset = 0; pulley.onLengthBroken(); } @@ -59,122 +58,122 @@ public class PulleyBlock extends HorizontalAxisKineticBlock implements IBE be.assembleNextTick = true); - return InteractionResult.SUCCESS; - } - return InteractionResult.PASS; - } + public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, + BlockHitResult hit) { + if (!player.mayBuild()) + return InteractionResult.PASS; + if (player.isShiftKeyDown()) + return InteractionResult.PASS; + if (player.getItemInHand(handIn) + .isEmpty()) { + withBlockEntityDo(worldIn, pos, be -> be.assembleNextTick = true); + return InteractionResult.SUCCESS; + } + return InteractionResult.PASS; + } - @Override - public Class getBlockEntityClass() { - return PulleyBlockEntity.class; - } - - @Override - public BlockEntityType getBlockEntityType() { - return AllBlockEntityTypes.ROPE_PULLEY.get(); - } + @Override + public Class getBlockEntityClass() { + return PulleyBlockEntity.class; + } - private static class RopeBlockBase extends Block implements SimpleWaterloggedBlock { + @Override + public BlockEntityType getBlockEntityType() { + return AllBlockEntityTypes.ROPE_PULLEY.get(); + } - public RopeBlockBase(Properties properties) { - super(properties); - registerDefaultState(super.defaultBlockState().setValue(BlockStateProperties.WATERLOGGED, false)); - } + private static class RopeBlockBase extends Block implements SimpleWaterloggedBlock { + + public RopeBlockBase(Properties properties) { + super(properties); + registerDefaultState(super.defaultBlockState().setValue(BlockStateProperties.WATERLOGGED, false)); + } @Override - public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { - return false; - } + public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { + return false; + } - @Override - public PushReaction getPistonPushReaction(BlockState state) { - return PushReaction.BLOCK; - } + @Override + public PushReaction getPistonPushReaction(BlockState state) { + return PushReaction.BLOCK; + } - @Override - public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, - Player player) { - return AllBlocks.ROPE_PULLEY.asStack(); - } + @Override + public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, + Player player) { + return AllBlocks.ROPE_PULLEY.asStack(); + } - @Override - public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) { - if (!isMoving && (!state.hasProperty(BlockStateProperties.WATERLOGGED) || !newState.hasProperty(BlockStateProperties.WATERLOGGED) || state.getValue(BlockStateProperties.WATERLOGGED) == newState.getValue(BlockStateProperties.WATERLOGGED))) { - onRopeBroken(worldIn, pos.above()); - if (!worldIn.isClientSide) { - BlockState above = worldIn.getBlockState(pos.above()); - BlockState below = worldIn.getBlockState(pos.below()); - if (above.getBlock() instanceof RopeBlockBase) - worldIn.destroyBlock(pos.above(), true); - if (below.getBlock() instanceof RopeBlockBase) - worldIn.destroyBlock(pos.below(), true); - } - } - if (state.hasBlockEntity() && state.getBlock() != newState.getBlock()) { - worldIn.removeBlockEntity(pos); - } - } + @Override + public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) { + if (!isMoving && (!state.hasProperty(BlockStateProperties.WATERLOGGED) || !newState.hasProperty(BlockStateProperties.WATERLOGGED) || state.getValue(BlockStateProperties.WATERLOGGED) == newState.getValue(BlockStateProperties.WATERLOGGED))) { + onRopeBroken(worldIn, pos.above()); + if (!worldIn.isClientSide) { + BlockState above = worldIn.getBlockState(pos.above()); + BlockState below = worldIn.getBlockState(pos.below()); + if (above.getBlock() instanceof RopeBlockBase) + worldIn.destroyBlock(pos.above(), true); + if (below.getBlock() instanceof RopeBlockBase) + worldIn.destroyBlock(pos.below(), true); + } + } + if (state.hasBlockEntity() && state.getBlock() != newState.getBlock()) { + worldIn.removeBlockEntity(pos); + } + } - @Override - public FluidState getFluidState(BlockState state) { - return state.getValue(BlockStateProperties.WATERLOGGED) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState(); - } + @Override + public FluidState getFluidState(BlockState state) { + return state.getValue(BlockStateProperties.WATERLOGGED) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState(); + } - @Override - protected void createBlockStateDefinition(Builder builder) { - builder.add(BlockStateProperties.WATERLOGGED); - super.createBlockStateDefinition(builder); - } + @Override + protected void createBlockStateDefinition(Builder builder) { + builder.add(BlockStateProperties.WATERLOGGED); + super.createBlockStateDefinition(builder); + } - @Override - public BlockState updateShape(BlockState state, Direction direction, BlockState neighbourState, - LevelAccessor world, BlockPos pos, BlockPos neighbourPos) { - if (state.getValue(BlockStateProperties.WATERLOGGED)) - world.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); - return state; - } + @Override + public BlockState updateShape(BlockState state, Direction direction, BlockState neighbourState, + LevelAccessor world, BlockPos pos, BlockPos neighbourPos) { + if (state.getValue(BlockStateProperties.WATERLOGGED)) + world.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); + return state; + } - @Override - public BlockState getStateForPlacement(BlockPlaceContext context) { - FluidState FluidState = context.getLevel().getFluidState(context.getClickedPos()); - return super.getStateForPlacement(context).setValue(BlockStateProperties.WATERLOGGED, Boolean.valueOf(FluidState.getType() == Fluids.WATER)); - } + @Override + public BlockState getStateForPlacement(BlockPlaceContext context) { + FluidState FluidState = context.getLevel().getFluidState(context.getClickedPos()); + return super.getStateForPlacement(context).setValue(BlockStateProperties.WATERLOGGED, Boolean.valueOf(FluidState.getType() == Fluids.WATER)); + } - } + } - public static class MagnetBlock extends RopeBlockBase { + public static class MagnetBlock extends RopeBlockBase { - public MagnetBlock(Properties properties) { - super(properties); - } + public MagnetBlock(Properties properties) { + super(properties); + } - @Override - public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { - return AllShapes.PULLEY_MAGNET; - } + @Override + public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { + return AllShapes.PULLEY_MAGNET; + } - } + } - public static class RopeBlock extends RopeBlockBase { + public static class RopeBlock extends RopeBlockBase { - public RopeBlock(Properties properties) { - super(properties); - } + public RopeBlock(Properties properties) { + super(properties); + } - @Override - public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { - return AllShapes.FOUR_VOXEL_POLE.get(Direction.UP); - } - } + @Override + public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { + return AllShapes.FOUR_VOXEL_POLE.get(Direction.UP); + } + } } diff --git a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlockEntity.java b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlockEntity.java index 1c16c974ce..b667cb5c48 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/contraptions/pulley/PulleyBlockEntity.java @@ -76,9 +76,9 @@ public class PulleyBlockEntity extends LinearActuatorBlockEntity implements Thre if (level.isClientSide() && mirrorParent != null) if (sharedMirrorContraption == null || sharedMirrorContraption.get() == null || !sharedMirrorContraption.get() - .isAlive()) { + .isAlive()) { sharedMirrorContraption = null; - if (level.getBlockEntity(mirrorParent)instanceof PulleyBlockEntity pte && pte.movedContraption != null) + if (level.getBlockEntity(mirrorParent) instanceof PulleyBlockEntity pte && pte.movedContraption != null) sharedMirrorContraption = new WeakReference<>(pte.movedContraption); } @@ -204,8 +204,8 @@ public class PulleyBlockEntity extends LinearActuatorBlockEntity implements Thre .getCollisionShape(level, magnetPos) .isEmpty()); level.setBlock(magnetPos, AllBlocks.PULLEY_MAGNET.getDefaultState() - .setValue(BlockStateProperties.WATERLOGGED, - Boolean.valueOf(ifluidstate.getType() == Fluids.WATER)), + .setValue(BlockStateProperties.WATERLOGGED, + Boolean.valueOf(ifluidstate.getType() == Fluids.WATER)), 66); } } @@ -255,8 +255,7 @@ public class PulleyBlockEntity extends LinearActuatorBlockEntity implements Thre @Override protected Vec3 toPosition(float offset) { - if (movedContraption.getContraption() instanceof PulleyContraption) { - PulleyContraption contraption = (PulleyContraption) movedContraption.getContraption(); + if (movedContraption.getContraption() instanceof PulleyContraption contraption) { return Vec3.atLowerCornerOf(contraption.anchor) .add(0, contraption.getInitialOffset() - offset, 0); diff --git a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java index 12deecf630..5e958d6292 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionInteractionPacket.java @@ -2,6 +2,7 @@ package com.simibubi.create.content.contraptions.sync; import com.simibubi.create.content.contraptions.AbstractContraptionEntity; import com.simibubi.create.foundation.networking.SimplePacketBase; + import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.FriendlyByteBuf; @@ -9,6 +10,7 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.AABB; + import net.minecraftforge.common.ForgeMod; import net.minecraftforge.network.NetworkEvent.Context; @@ -49,9 +51,8 @@ public class ContraptionInteractionPacket extends SimplePacketBase { if (sender == null) return; Entity entityByID = sender.level().getEntity(target); - if (!(entityByID instanceof AbstractContraptionEntity)) + if (!(entityByID instanceof AbstractContraptionEntity contraptionEntity)) return; - AbstractContraptionEntity contraptionEntity = (AbstractContraptionEntity) entityByID; AABB bb = contraptionEntity.getBoundingBox(); double boundsExtra = Math.max(bb.getXsize(), bb.getYsize()); double d = sender.getAttribute(ForgeMod.BLOCK_REACH.get()).getValue() + 10 + boundsExtra; diff --git a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java index da69ee740d..70be71d3c5 100644 --- a/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java +++ b/src/main/java/com/simibubi/create/content/contraptions/sync/ContraptionSeatMappingPacket.java @@ -55,9 +55,8 @@ public class ContraptionSeatMappingPacket extends SimplePacketBase { public boolean handle(Context context) { context.enqueueWork(() -> { Entity entityByID = Minecraft.getInstance().level.getEntity(entityID); - if (!(entityByID instanceof AbstractContraptionEntity)) + if (!(entityByID instanceof AbstractContraptionEntity contraptionEntity)) return; - AbstractContraptionEntity contraptionEntity = (AbstractContraptionEntity) entityByID; if (dismountedID != -1) { Entity dismountedByID = Minecraft.getInstance().level.getEntity(dismountedID); diff --git a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java index 263bce99ed..54a93e0edb 100644 --- a/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java +++ b/src/main/java/com/simibubi/create/content/decoration/copycat/CopycatBarsModel.java @@ -14,6 +14,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; + import net.minecraftforge.client.model.data.ModelData; public class CopycatBarsModel extends CopycatModel { @@ -29,7 +30,7 @@ public class CopycatBarsModel extends CopycatModel { @Override protected List getCroppedQuads(BlockState state, Direction side, RandomSource rand, BlockState material, - ModelData wrappedData, RenderType renderType) { + ModelData wrappedData, RenderType renderType) { BakedModel model = getModelOf(material); List superQuads = originalModel.getQuads(state, side, rand, wrappedData, renderType); TextureAtlasSprite targetSprite = model.getParticleIcon(wrappedData); @@ -39,8 +40,7 @@ public class CopycatBarsModel extends CopycatModel { if (side != null && (vertical || side.getAxis() == Axis.Y)) { List templateQuads = model.getQuads(material, null, rand, wrappedData, renderType); - for (int i = 0; i < templateQuads.size(); i++) { - BakedQuad quad = templateQuads.get(i); + for (BakedQuad quad : templateQuads) { if (quad.getDirection() != Direction.UP) continue; targetSprite = quad.getSprite(); @@ -53,8 +53,7 @@ public class CopycatBarsModel extends CopycatModel { List quads = new ArrayList<>(); - for (int i = 0; i < superQuads.size(); i++) { - BakedQuad quad = superQuads.get(i); + for (BakedQuad quad : superQuads) { TextureAtlasSprite original = quad.getSprite(); BakedQuad newQuad = BakedQuadHelper.clone(quad); int[] vertexData = newQuad.getVertices(); diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java index b604794999..b5a8a447c5 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/BacktankArmorLayer.java @@ -30,7 +30,7 @@ public class BacktankArmorLayer @Override public void render(PoseStack ms, MultiBufferSource buffer, int light, LivingEntity entity, float yaw, float pitch, - float pt, float p_225628_8_, float p_225628_9_, float p_225628_10_) { + float pt, float p_225628_8_, float p_225628_9_, float p_225628_10_) { if (entity.getPose() == Pose.SLEEPING) return; @@ -39,13 +39,12 @@ public class BacktankArmorLayer return; M entityModel = getParentModel(); - if (!(entityModel instanceof HumanoidModel)) + if (!(entityModel instanceof HumanoidModel model)) return; - HumanoidModel model = (HumanoidModel) entityModel; VertexConsumer vc = buffer.getBuffer(Sheets.cutoutBlockSheet()); BlockState renderedState = item.getBlock().defaultBlockState() - .setValue(BacktankBlock.HORIZONTAL_FACING, Direction.SOUTH); + .setValue(BacktankBlock.HORIZONTAL_FACING, Direction.SOUTH); SuperByteBuffer backtank = CachedBuffers.block(renderedState); SuperByteBuffer cogs = CachedBuffers.partial(BacktankRenderer.getCogsModel(renderedState), renderedState); SuperByteBuffer nob = CachedBuffers.partial(BacktankRenderer.getShaftModel(renderedState), renderedState); @@ -86,11 +85,10 @@ public class BacktankArmorLayer registerOn(renderer); } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) public static void registerOn(EntityRenderer entityRenderer) { - if (!(entityRenderer instanceof LivingEntityRenderer)) + if (!(entityRenderer instanceof LivingEntityRenderer livingRenderer)) return; - LivingEntityRenderer livingRenderer = (LivingEntityRenderer) entityRenderer; if (!(livingRenderer.getModel() instanceof HumanoidModel)) return; BacktankArmorLayer layer = new BacktankArmorLayer<>(livingRenderer); diff --git a/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java b/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java index dfc0296158..b231c0f69d 100644 --- a/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/armor/DivingBootsItem.java @@ -77,8 +77,7 @@ public class DivingBootsItem extends BaseArmorItem { return false; if (entity.getPose() == Pose.SWIMMING) return false; - if (entity instanceof Player) { - Player playerEntity = (Player) entity; + if (entity instanceof Player playerEntity) { if (playerEntity.getAbilities().flying) return false; } diff --git a/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java b/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java index 7fa1115e72..283a36f6c9 100644 --- a/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java +++ b/src/main/java/com/simibubi/create/content/equipment/bell/BasicParticleData.java @@ -15,6 +15,7 @@ import net.minecraft.client.particle.SpriteSet; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; import net.minecraft.network.FriendlyByteBuf; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -22,12 +23,13 @@ import net.minecraftforge.api.distmarker.OnlyIn; @MethodsReturnNonnullByDefault public abstract class BasicParticleData implements ParticleOptions, ICustomParticleDataWithSprite> { - public BasicParticleData() { } + public BasicParticleData() { + } @Override public Deserializer> getDeserializer() { BasicParticleData data = this; - return new ParticleOptions.Deserializer>() { + return new ParticleOptions.Deserializer<>() { @Override public BasicParticleData fromCommand(ParticleType> arg0, StringReader reader) { return data; @@ -56,7 +58,7 @@ public abstract class BasicParticleData implements ParticleO @OnlyIn(Dist.CLIENT) public ParticleEngine.SpriteParticleRegistration> getMetaFactory() { return animatedSprite -> (data, worldIn, x, y, z, vx, vy, vz) -> - getBasicFactory().makeParticle(worldIn, x, y, z, vx, vy, vz, animatedSprite); + getBasicFactory().makeParticle(worldIn, x, y, z, vx, vy, vz, animatedSprite); } @Override @@ -65,5 +67,6 @@ public abstract class BasicParticleData implements ParticleO } @Override - public void writeToNetwork(FriendlyByteBuf buffer) { } + public void writeToNetwork(FriendlyByteBuf buffer) { + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java index d54451e648..0eb0defad3 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintAssignCompleteRecipePacket.java @@ -1,9 +1,11 @@ package com.simibubi.create.content.equipment.blueprint; import com.simibubi.create.foundation.networking.SimplePacketBase; + import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; + import net.minecraftforge.network.NetworkEvent.Context; public class BlueprintAssignCompleteRecipePacket extends SimplePacketBase { @@ -29,12 +31,11 @@ public class BlueprintAssignCompleteRecipePacket extends SimplePacketBase { ServerPlayer player = context.getSender(); if (player == null) return; - if (player.containerMenu instanceof BlueprintMenu) { - BlueprintMenu c = (BlueprintMenu) player.containerMenu; + if (player.containerMenu instanceof BlueprintMenu c) { player.level() - .getRecipeManager() - .byKey(recipeID) - .ifPresent(r -> BlueprintItem.assignCompleteRecipe(c.player.level(), c.ghostInventory, r)); + .getRecipeManager() + .byKey(recipeID) + .ifPresent(r -> BlueprintItem.assignCompleteRecipe(c.player.level(), c.ghostInventory, r)); } }); return true; diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java index 25ea995073..9b2dadd4c7 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintEntity.java @@ -173,15 +173,15 @@ public class BlueprintEntity extends HangingEntity Axis axis = direction.getAxis(); if (size == 2) pos = pos.add(Vec3.atLowerCornerOf(axis.isHorizontal() ? direction.getCounterClockWise() - .getNormal() - : verticalOrientation.getClockWise() - .getNormal()) - .scale(0.5)) + .getNormal() + : verticalOrientation.getClockWise() + .getNormal()) + .scale(0.5)) .add(Vec3 .atLowerCornerOf(axis.isHorizontal() ? Direction.UP.getNormal() : direction == Direction.UP ? verticalOrientation.getNormal() - : verticalOrientation.getOpposite() - .getNormal()) + : verticalOrientation.getOpposite() + .getNormal()) .scale(0.5)); d1 = pos.x; @@ -193,14 +193,14 @@ public class BlueprintEntity extends HangingEntity double d6 = (double) this.getWidth(); Direction.Axis direction$axis = this.direction.getAxis(); switch (direction$axis) { - case X: - d4 = 1.0D; - break; - case Y: - d5 = 1.0D; - break; - case Z: - d6 = 1.0D; + case X: + d4 = 1.0D; + break; + case Y: + d5 = 1.0D; + break; + case Z: + d6 = 1.0D; } d4 = d4 / 32.0D; @@ -225,7 +225,7 @@ public class BlueprintEntity extends HangingEntity BlockPos blockpos = this.pos.relative(this.direction.getOpposite()); Direction upDirection = direction.getAxis() .isHorizontal() ? Direction.UP - : direction == Direction.UP ? verticalOrientation : verticalOrientation.getOpposite(); + : direction == Direction.UP ? verticalOrientation : verticalOrientation.getOpposite(); Direction newDirection = direction.getAxis() .isVertical() ? verticalOrientation.getClockWise() : direction.getCounterClockWise(); BlockPos.MutableBlockPos blockpos$mutable = new BlockPos.MutableBlockPos(); @@ -262,10 +262,9 @@ public class BlueprintEntity extends HangingEntity @Override public boolean skipAttackInteraction(Entity source) { - if (!(source instanceof Player) || level().isClientSide) + if (!(source instanceof Player player) || level().isClientSide) return super.skipAttackInteraction(source); - Player player = (Player) source; double attrib = player.getAttribute(ForgeMod.BLOCK_REACH.get()) .getValue() + (player.isCreative() ? 0 : -0.5F); @@ -297,8 +296,7 @@ public class BlueprintEntity extends HangingEntity return; playSound(SoundEvents.PAINTING_BREAK, 1.0F, 1.0F); - if (p_110128_1_ instanceof Player) { - Player playerentity = (Player) p_110128_1_; + if (p_110128_1_ instanceof Player playerentity) { if (playerentity.getAbilities().instabuild) return; } @@ -329,7 +327,7 @@ public class BlueprintEntity extends HangingEntity @Override @OnlyIn(Dist.CLIENT) public void lerpTo(double p_180426_1_, double p_180426_3_, double p_180426_5_, float p_180426_7_, float p_180426_8_, - int p_180426_9_, boolean p_180426_10_) { + int p_180426_9_, boolean p_180426_10_) { BlockPos blockpos = this.pos.offset(BlockPos.containing(p_180426_1_ - this.getX(), p_180426_3_ - this.getY(), p_180426_5_ - this.getZ())); this.setPos((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()); @@ -372,7 +370,8 @@ public class BlueprintEntity extends HangingEntity Map craftingGrid = new HashMap<>(); boolean success = true; - Search: for (int i = 0; i < 9; i++) { + Search: + for (int i = 0; i < 9; i++) { FilterItemStack requestedItem = FilterItemStack.of(items.getStackInSlot(i)); if (requestedItem.isEmpty()) { craftingGrid.put(i, ItemStack.EMPTY); diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java index c87e275a60..f6c6eb7abe 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintItem.java @@ -1,10 +1,13 @@ package com.simibubi.create.content.equipment.blueprint; +import java.util.Collection; + import com.simibubi.create.AllItems; import com.simibubi.create.content.logistics.filter.AttributeFilterMenu.WhitelistMode; import com.simibubi.create.content.logistics.filter.FilterItem; +import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute; +import com.simibubi.create.content.logistics.item.filter.attribute.attributes.InTagAttribute; -import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute;import com.simibubi.create.content.logistics.item.filter.attribute.attributes.InTagAttribute; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; @@ -26,12 +29,11 @@ import net.minecraft.world.item.crafting.Ingredient.TagValue; import net.minecraft.world.item.crafting.Ingredient.Value; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.Level; + import net.minecraftforge.common.crafting.IShapedRecipe; import net.minecraftforge.common.crafting.MultiItemValue; import net.minecraftforge.items.ItemStackHandler; -import java.util.Collection; - public class BlueprintItem extends Item { public BlueprintItem(Properties p_i48487_1_) { @@ -44,14 +46,14 @@ public class BlueprintItem extends Item { Player player = ctx.getPlayer(); ItemStack stack = ctx.getItemInHand(); BlockPos pos = ctx.getClickedPos() - .relative(face); + .relative(face); if (player != null && !player.mayUseItemAt(pos, face, stack)) return InteractionResult.FAIL; Level world = ctx.getLevel(); HangingEntity hangingentity = new BlueprintEntity(world, pos, face, face.getAxis() - .isHorizontal() ? Direction.DOWN : ctx.getHorizontalDirection()); + .isHorizontal() ? Direction.DOWN : ctx.getHorizontalDirection()); CompoundTag compoundnbt = stack.getTag(); if (compoundnbt != null) @@ -79,12 +81,11 @@ public class BlueprintItem extends Item { inv.setStackInSlot(i, ItemStack.EMPTY); inv.setStackInSlot(9, recipe.getResultItem(level.registryAccess())); - if (recipe instanceof IShapedRecipe) { - IShapedRecipe shapedRecipe = (IShapedRecipe) recipe; + if (recipe instanceof IShapedRecipe shapedRecipe) { for (int row = 0; row < shapedRecipe.getRecipeHeight(); row++) for (int col = 0; col < shapedRecipe.getRecipeWidth(); col++) inv.setStackInSlot(row * 3 + col, - convertIngredientToFilter(ingredients.get(row * shapedRecipe.getRecipeWidth() + col))); + convertIngredientToFilter(ingredients.get(row * shapedRecipe.getRecipeWidth() + col))); } else { for (int i = 0; i < ingredients.size(); i++) inv.setStackInSlot(i, convertIngredientToFilter(ingredients.get(i))); @@ -105,7 +106,7 @@ public class BlueprintItem extends Item { for (int i = 0; i < acceptedItems.length; i++) filterItems.setStackInSlot(i, convertIItemListToFilter(acceptedItems[i])); result.getOrCreateTag() - .put("Items", filterItems.serializeNBT()); + .put("Items", filterItems.serializeNBT()); return result; } @@ -120,13 +121,13 @@ public class BlueprintItem extends Item { ResourceLocation resourcelocation = new ResourceLocation(GsonHelper.getAsString(itemList.serialize(), "tag")); ItemStack filterItem = AllItems.ATTRIBUTE_FILTER.asStack(); filterItem.getOrCreateTag() - .putInt("WhitelistMode", WhitelistMode.WHITELIST_DISJ.ordinal()); + .putInt("WhitelistMode", WhitelistMode.WHITELIST_DISJ.ordinal()); ListTag attributes = new ListTag(); CompoundTag compoundNBT = ItemAttribute.saveStatic(new InTagAttribute(ItemTags.create(resourcelocation))); compoundNBT.putBoolean("Inverted", false); attributes.add(compoundNBT); filterItem.getOrCreateTag() - .put("MatchedAttributes", attributes); + .put("MatchedAttributes", attributes); return filterItem; } diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java index ac4fa01e62..197ef51a05 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintMenu.java @@ -1,8 +1,11 @@ package com.simibubi.create.content.equipment.blueprint; +import java.util.Optional; + import com.simibubi.create.AllMenuTypes; import com.simibubi.create.content.equipment.blueprint.BlueprintEntity.BlueprintSection; import com.simibubi.create.foundation.gui.menu.GhostItemMenu; + import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; @@ -18,14 +21,13 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.Level; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; import net.minecraftforge.items.SlotItemHandler; -import java.util.Optional; - public class BlueprintMenu extends GhostItemMenu { public BlueprintMenu(MenuType type, int id, Inventory inv, FriendlyByteBuf extraData) { @@ -68,12 +70,12 @@ public class BlueprintMenu extends GhostItemMenu { ServerPlayer serverplayerentity = (ServerPlayer) player; CraftingContainer craftingInventory = new BlueprintCraftingInventory(this, ghostInventory); Optional optional = player.getServer() - .getRecipeManager() - .getRecipeFor(RecipeType.CRAFTING, craftingInventory, player.getCommandSenderWorld()); + .getRecipeManager() + .getRecipeFor(RecipeType.CRAFTING, craftingInventory, player.getCommandSenderWorld()); if (!optional.isPresent()) { if (ghostInventory.getStackInSlot(9) - .isEmpty()) + .isEmpty()) return; if (!contentHolder.inferredIcon) return; @@ -90,7 +92,7 @@ public class BlueprintMenu extends GhostItemMenu { contentHolder.inferredIcon = true; ItemStack toSend = itemstack.copy(); toSend.getOrCreateTag() - .putBoolean("InferredFromRecipe", true); + .putBoolean("InferredFromRecipe", true); serverplayerentity.connection.send(new ClientboundContainerSetSlotPacket(containerId, incrementStateId(), 36 + 9, toSend)); } @@ -99,9 +101,9 @@ public class BlueprintMenu extends GhostItemMenu { if (slotId == 36 + 9) { if (stack.hasTag()) { contentHolder.inferredIcon = stack.getTag() - .getBoolean("InferredFromRecipe"); + .getBoolean("InferredFromRecipe"); stack.getTag() - .remove("InferredFromRecipe"); + .remove("InferredFromRecipe"); } else contentHolder.inferredIcon = false; } @@ -129,9 +131,8 @@ public class BlueprintMenu extends GhostItemMenu { int entityID = extraData.readVarInt(); int section = extraData.readVarInt(); Entity entityByID = Minecraft.getInstance().level.getEntity(entityID); - if (!(entityByID instanceof BlueprintEntity)) + if (!(entityByID instanceof BlueprintEntity blueprintEntity)) return null; - BlueprintEntity blueprintEntity = (BlueprintEntity) entityByID; BlueprintSection blueprintSection = blueprintEntity.getSection(section); return blueprintSection; } diff --git a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java index 02a0a9c813..c5cc0c7021 100644 --- a/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java +++ b/src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintOverlayRenderer.java @@ -19,16 +19,16 @@ import com.simibubi.create.content.logistics.item.filter.attribute.ItemAttribute import com.simibubi.create.content.logistics.item.filter.attribute.attributes.InTagAttribute; import com.simibubi.create.content.logistics.packager.InventorySummary; import com.simibubi.create.content.logistics.tableCloth.BlueprintOverlayShopContext; -import com.simibubi.create.content.logistics.tableCloth.TableClothBlockEntity; import com.simibubi.create.content.logistics.tableCloth.ShoppingListItem.ShoppingList; +import com.simibubi.create.content.logistics.tableCloth.TableClothBlockEntity; import com.simibubi.create.content.trains.track.TrackPlacement.PlacementInfo; import com.simibubi.create.foundation.gui.AllGuiTextures; -import net.createmod.catnip.gui.element.GuiGameElement; import net.createmod.catnip.animation.AnimationTickHolder; import net.createmod.catnip.data.Couple; import net.createmod.catnip.data.Iterate; import net.createmod.catnip.data.Pair; +import net.createmod.catnip.gui.element.GuiGameElement; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; @@ -36,7 +36,6 @@ import net.minecraft.client.gui.screens.inventory.tooltip.TooltipRenderUtil; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.Item; @@ -49,6 +48,7 @@ import net.minecraft.world.level.GameType; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult.Type; + import net.minecraftforge.client.gui.overlay.ForgeGui; import net.minecraftforge.client.gui.overlay.IGuiOverlay; import net.minecraftforge.items.ItemHandlerHelper; @@ -92,10 +92,9 @@ public class BlueprintOverlayRenderer { return; EntityHitResult entityRay = (EntityHitResult) mouseOver; - if (!(entityRay.getEntity() instanceof BlueprintEntity)) + if (!(entityRay.getEntity() instanceof BlueprintEntity blueprintEntity)) return; - BlueprintEntity blueprintEntity = (BlueprintEntity) entityRay.getEntity(); BlueprintSection sectionAt = blueprintEntity.getSectionAt(entityRay.getLocation() .subtract(blueprintEntity.position())); @@ -151,7 +150,7 @@ public class BlueprintOverlayRenderer { shopContext = new BlueprintOverlayShopContext(false, dce.getStockLevelForTrade(list), alreadyPurchased); ingredients.add(Pair.of(dce.getPaymentItem() - .copyWithCount(dce.getPaymentAmount()), + .copyWithCount(dce.getPaymentAmount()), !dce.getPaymentItem() .isEmpty() && shopContext.stockLevel() > shopContext.purchases())); for (BigItemStack entry : dce.requestData.encodedRequest.stacks()) @@ -241,7 +240,8 @@ public class BlueprintOverlayRenderer { newlyAdded.clear(); newlyMissing.clear(); - Search: for (int i = 0; i < 9; i++) { + Search: + for (int i = 0; i < 9; i++) { FilterItemStack requestedItem = FilterItemStack.of(items.getStackInSlot(i)); if (requestedItem.isEmpty()) { craftingGrid.put(i, ItemStack.EMPTY); @@ -351,7 +351,7 @@ public class BlueprintOverlayRenderer { AllGuiTextures.TRADE_OVERLAY.render(graphics, width / 2 - 48, y - 19); if (shopContext.purchases() > 0) { graphics.renderItem(AllItems.SHOPPING_LIST.asStack(), width / 2 + 20, y - 20); - graphics.drawString(mc.font, Component.literal("x" + shopContext.purchases()), width / 2 + 20 + 16, + graphics.drawString(mc.font, Component.literal("x" + shopContext.purchases()), width / 2 + 20 + 16, y - 20 + 4, 0xff_eeeeee, true); } } @@ -411,7 +411,7 @@ public class BlueprintOverlayRenderer { if ((gui.getGuiTicks() / 40) % cycle != i) continue; graphics.renderComponentTooltip(gui.getFont(), tooltipLines, mc.getWindow() - .getGuiScaledWidth(), + .getGuiScaledWidth(), mc.getWindow() .getGuiScaledHeight()); } @@ -421,7 +421,7 @@ public class BlueprintOverlayRenderer { } public static void drawItemStack(GuiGraphics graphics, Minecraft mc, int x, int y, ItemStack itemStack, - String count) { + String count) { if (itemStack.getItem() instanceof FilterItem) { int step = AnimationTickHolder.getTicks(mc.level) / 10; ItemStack[] itemsMatchingFilter = getItemsMatchingFilter(itemStack); diff --git a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java index 35223f7e7e..4873ba0976 100644 --- a/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/extendoGrip/ExtendoGripItem.java @@ -1,5 +1,9 @@ package com.simibubi.create.content.equipment.extendoGrip; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Supplier; + import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; @@ -9,6 +13,7 @@ import com.simibubi.create.content.equipment.armor.BacktankUtil; import com.simibubi.create.foundation.advancement.AllAdvancements; import com.simibubi.create.foundation.item.render.SimpleCustomRenderer; import com.simibubi.create.infrastructure.config.AllConfigs; + import net.createmod.catnip.animation.AnimationTickHolder; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; @@ -29,6 +34,7 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult.Type; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.InputEvent; @@ -46,10 +52,6 @@ import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import java.util.UUID; -import java.util.function.Consumer; -import java.util.function.Supplier; - @EventBusSubscriber public class ExtendoGripItem extends Item { public static final int MAX_DAMAGE = 200; @@ -62,11 +64,11 @@ public class ExtendoGripItem extends Item { AttributeModifier.Operation.ADDITION); private static final Supplier> rangeModifier = Suppliers.memoize(() -> - // Holding an ExtendoGrip - ImmutableMultimap.of(ForgeMod.BLOCK_REACH.get(), singleRangeAttributeModifier)); + // Holding an ExtendoGrip + ImmutableMultimap.of(ForgeMod.BLOCK_REACH.get(), singleRangeAttributeModifier)); private static final Supplier> doubleRangeModifier = Suppliers.memoize(() -> - // Holding two ExtendoGrips o.O - ImmutableMultimap.of(ForgeMod.BLOCK_REACH.get(), doubleRangeAttributeModifier)); + // Holding two ExtendoGrips o.O + ImmutableMultimap.of(ForgeMod.BLOCK_REACH.get(), doubleRangeAttributeModifier)); private static DamageSource lastActiveDamageSource; @@ -79,11 +81,9 @@ public class ExtendoGripItem extends Item { @SubscribeEvent public static void holdingExtendoGripIncreasesRange(LivingTickEvent event) { - if (!(event.getEntity() instanceof Player)) + if (!(event.getEntity() instanceof Player player)) return; - Player player = (Player) event.getEntity(); - CompoundTag persistentData = player.getPersistentData(); boolean inOff = AllItems.EXTENDO_GRIP.isIn(player.getOffhandItem()); boolean inMain = AllItems.EXTENDO_GRIP.isIn(player.getMainHandItem()); @@ -245,9 +245,8 @@ public class ExtendoGripItem extends Item { if (lastActiveDamageSource == null) return; Entity entity = lastActiveDamageSource.getDirectEntity(); - if (!(entity instanceof Player)) + if (!(entity instanceof Player player)) return; - Player player = (Player) entity; if (!isHoldingExtendoGrip(player)) return; event.setStrength(event.getStrength() + 2); diff --git a/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java b/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java index fa2a4fe138..ec744ad2de 100644 --- a/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java +++ b/src/main/java/com/simibubi/create/content/equipment/goggles/GoggleOverlayRenderer.java @@ -68,7 +68,7 @@ public class GoggleOverlayRenderer { return; HitResult objectMouseOver = mc.hitResult; - if (!(objectMouseOver instanceof BlockHitResult)) { + if (!(objectMouseOver instanceof BlockHitResult result)) { lastHovered = null; hoverTicks = 0; return; @@ -82,7 +82,6 @@ public class GoggleOverlayRenderer { return; } - BlockHitResult result = (BlockHitResult) objectMouseOver; ClientLevel world = mc.level; BlockPos pos = result.getBlockPos(); diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java index e684674e81..eb5b87af7b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/BuiltinPotatoProjectileTypes.java @@ -1,10 +1,16 @@ package com.simibubi.create.content.equipment.potatoCannon; +import java.util.UUID; +import java.util.function.BiPredicate; +import java.util.function.Predicate; +import java.util.function.Supplier; + import com.mojang.authlib.GameProfile; import com.mojang.datafixers.util.Pair; import com.simibubi.create.AllItems; import com.simibubi.create.Create; import com.simibubi.create.foundation.mixin.accessor.FallingBlockEntityAccessor; + import net.createmod.catnip.data.WorldAttached; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -34,17 +40,13 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.EntityTeleportEvent; import net.minecraftforge.registries.ForgeRegistries; -import java.util.UUID; -import java.util.function.BiPredicate; -import java.util.function.Predicate; -import java.util.function.Supplier; - public class BuiltinPotatoProjectileTypes { private static final GameProfile ZOMBIE_CONVERTER_NAME = @@ -54,206 +56,204 @@ public class BuiltinPotatoProjectileTypes { public static final PotatoCannonProjectileType - FALLBACK = create("fallback").damage(0) + FALLBACK = create("fallback").damage(0) .register(), - POTATO = create("potato").damage(5) - .reloadTicks(15) - .velocity(1.25f) - .knockback(1.5f) - .renderTumbling() - .onBlockHit(plantCrop(Blocks.POTATOES)) - .registerAndAssign(Items.POTATO), + POTATO = create("potato").damage(5) + .reloadTicks(15) + .velocity(1.25f) + .knockback(1.5f) + .renderTumbling() + .onBlockHit(plantCrop(Blocks.POTATOES)) + .registerAndAssign(Items.POTATO), - BAKED_POTATO = create("baked_potato").damage(5) - .reloadTicks(15) - .velocity(1.25f) - .knockback(0.5f) - .renderTumbling() - .preEntityHit(setFire(3)) - .registerAndAssign(Items.BAKED_POTATO), + BAKED_POTATO = create("baked_potato").damage(5) + .reloadTicks(15) + .velocity(1.25f) + .knockback(0.5f) + .renderTumbling() + .preEntityHit(setFire(3)) + .registerAndAssign(Items.BAKED_POTATO), - CARROT = create("carrot").damage(4) - .reloadTicks(12) - .velocity(1.45f) - .knockback(0.3f) - .renderTowardMotion(140, 1) - .soundPitch(1.5f) - .onBlockHit(plantCrop(Blocks.CARROTS)) - .registerAndAssign(Items.CARROT), + CARROT = create("carrot").damage(4) + .reloadTicks(12) + .velocity(1.45f) + .knockback(0.3f) + .renderTowardMotion(140, 1) + .soundPitch(1.5f) + .onBlockHit(plantCrop(Blocks.CARROTS)) + .registerAndAssign(Items.CARROT), - GOLDEN_CARROT = create("golden_carrot").damage(12) - .reloadTicks(15) - .velocity(1.45f) - .knockback(0.5f) - .renderTowardMotion(140, 2) - .soundPitch(1.5f) - .registerAndAssign(Items.GOLDEN_CARROT), + GOLDEN_CARROT = create("golden_carrot").damage(12) + .reloadTicks(15) + .velocity(1.45f) + .knockback(0.5f) + .renderTowardMotion(140, 2) + .soundPitch(1.5f) + .registerAndAssign(Items.GOLDEN_CARROT), - SWEET_BERRIES = create("sweet_berry").damage(3) - .reloadTicks(10) - .knockback(0.1f) - .velocity(1.05f) - .renderTumbling() - .splitInto(3) - .soundPitch(1.25f) - .registerAndAssign(Items.SWEET_BERRIES), + SWEET_BERRIES = create("sweet_berry").damage(3) + .reloadTicks(10) + .knockback(0.1f) + .velocity(1.05f) + .renderTumbling() + .splitInto(3) + .soundPitch(1.25f) + .registerAndAssign(Items.SWEET_BERRIES), - GLOW_BERRIES = create("glow_berry").damage(2) - .reloadTicks(10) - .knockback(0.05f) - .velocity(1.05f) - .renderTumbling() - .splitInto(2) - .soundPitch(1.2f) - .onEntityHit(potion(MobEffects.GLOWING, 1, 200, false)) - .registerAndAssign(Items.GLOW_BERRIES), + GLOW_BERRIES = create("glow_berry").damage(2) + .reloadTicks(10) + .knockback(0.05f) + .velocity(1.05f) + .renderTumbling() + .splitInto(2) + .soundPitch(1.2f) + .onEntityHit(potion(MobEffects.GLOWING, 1, 200, false)) + .registerAndAssign(Items.GLOW_BERRIES), - CHOCOLATE_BERRIES = create("chocolate_berry").damage(4) - .reloadTicks(10) - .knockback(0.2f) - .velocity(1.05f) - .renderTumbling() - .splitInto(3) - .soundPitch(1.25f) - .registerAndAssign(AllItems.CHOCOLATE_BERRIES.get()), + CHOCOLATE_BERRIES = create("chocolate_berry").damage(4) + .reloadTicks(10) + .knockback(0.2f) + .velocity(1.05f) + .renderTumbling() + .splitInto(3) + .soundPitch(1.25f) + .registerAndAssign(AllItems.CHOCOLATE_BERRIES.get()), - POISON_POTATO = create("poison_potato").damage(5) - .reloadTicks(15) - .knockback(0.05f) - .velocity(1.25f) - .renderTumbling() - .onEntityHit(potion(MobEffects.POISON, 1, 160, true)) - .registerAndAssign(Items.POISONOUS_POTATO), + POISON_POTATO = create("poison_potato").damage(5) + .reloadTicks(15) + .knockback(0.05f) + .velocity(1.25f) + .renderTumbling() + .onEntityHit(potion(MobEffects.POISON, 1, 160, true)) + .registerAndAssign(Items.POISONOUS_POTATO), - CHORUS_FRUIT = create("chorus_fruit").damage(3) - .reloadTicks(15) - .velocity(1.20f) - .knockback(0.05f) - .renderTumbling() - .onEntityHit(chorusTeleport(20)) - .registerAndAssign(Items.CHORUS_FRUIT), + CHORUS_FRUIT = create("chorus_fruit").damage(3) + .reloadTicks(15) + .velocity(1.20f) + .knockback(0.05f) + .renderTumbling() + .onEntityHit(chorusTeleport(20)) + .registerAndAssign(Items.CHORUS_FRUIT), - APPLE = create("apple").damage(5) - .reloadTicks(10) - .velocity(1.45f) - .knockback(0.5f) - .renderTumbling() - .soundPitch(1.1f) - .registerAndAssign(Items.APPLE), + APPLE = create("apple").damage(5) + .reloadTicks(10) + .velocity(1.45f) + .knockback(0.5f) + .renderTumbling() + .soundPitch(1.1f) + .registerAndAssign(Items.APPLE), - HONEYED_APPLE = create("honeyed_apple").damage(6) - .reloadTicks(15) - .velocity(1.35f) - .knockback(0.1f) - .renderTumbling() - .soundPitch(1.1f) - .onEntityHit(potion(MobEffects.MOVEMENT_SLOWDOWN, 2, 160, true)) - .registerAndAssign(AllItems.HONEYED_APPLE.get()), + HONEYED_APPLE = create("honeyed_apple").damage(6) + .reloadTicks(15) + .velocity(1.35f) + .knockback(0.1f) + .renderTumbling() + .soundPitch(1.1f) + .onEntityHit(potion(MobEffects.MOVEMENT_SLOWDOWN, 2, 160, true)) + .registerAndAssign(AllItems.HONEYED_APPLE.get()), - GOLDEN_APPLE = create("golden_apple").damage(1) - .reloadTicks(100) - .velocity(1.45f) - .knockback(0.05f) - .renderTumbling() - .soundPitch(1.1f) - .onEntityHit(ray -> { - Entity entity = ray.getEntity(); - Level world = entity.level(); + GOLDEN_APPLE = create("golden_apple").damage(1) + .reloadTicks(100) + .velocity(1.45f) + .knockback(0.05f) + .renderTumbling() + .soundPitch(1.1f) + .onEntityHit(ray -> { + Entity entity = ray.getEntity(); + Level world = entity.level(); - if (!(entity instanceof ZombieVillager) || !((ZombieVillager) entity).hasEffect(MobEffects.WEAKNESS)) - return foodEffects(Foods.GOLDEN_APPLE, false).test(ray); - if (world.isClientSide) - return false; + if (!(entity instanceof ZombieVillager) || !((ZombieVillager) entity).hasEffect(MobEffects.WEAKNESS)) + return foodEffects(Foods.GOLDEN_APPLE, false).test(ray); + if (world.isClientSide) + return false; - FakePlayer dummy = ZOMBIE_CONVERTERS.get(world); - dummy.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.GOLDEN_APPLE, 1)); - ((ZombieVillager) entity).mobInteract(dummy, InteractionHand.MAIN_HAND); - return true; - }) - .registerAndAssign(Items.GOLDEN_APPLE), + FakePlayer dummy = ZOMBIE_CONVERTERS.get(world); + dummy.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.GOLDEN_APPLE, 1)); + ((ZombieVillager) entity).mobInteract(dummy, InteractionHand.MAIN_HAND); + return true; + }) + .registerAndAssign(Items.GOLDEN_APPLE), - ENCHANTED_GOLDEN_APPLE = create("enchanted_golden_apple").damage(1) - .reloadTicks(100) - .velocity(1.45f) - .knockback(0.05f) - .renderTumbling() - .soundPitch(1.1f) - .onEntityHit(foodEffects(Foods.ENCHANTED_GOLDEN_APPLE, false)) - .registerAndAssign(Items.ENCHANTED_GOLDEN_APPLE), + ENCHANTED_GOLDEN_APPLE = create("enchanted_golden_apple").damage(1) + .reloadTicks(100) + .velocity(1.45f) + .knockback(0.05f) + .renderTumbling() + .soundPitch(1.1f) + .onEntityHit(foodEffects(Foods.ENCHANTED_GOLDEN_APPLE, false)) + .registerAndAssign(Items.ENCHANTED_GOLDEN_APPLE), - BEETROOT = create("beetroot").damage(2) - .reloadTicks(5) - .velocity(1.6f) - .knockback(0.1f) - .renderTowardMotion(140, 2) - .soundPitch(1.6f) - .registerAndAssign(Items.BEETROOT), + BEETROOT = create("beetroot").damage(2) + .reloadTicks(5) + .velocity(1.6f) + .knockback(0.1f) + .renderTowardMotion(140, 2) + .soundPitch(1.6f) + .registerAndAssign(Items.BEETROOT), - MELON_SLICE = create("melon_slice").damage(3) - .reloadTicks(8) - .knockback(0.1f) - .velocity(1.45f) - .renderTumbling() - .soundPitch(1.5f) - .registerAndAssign(Items.MELON_SLICE), + MELON_SLICE = create("melon_slice").damage(3) + .reloadTicks(8) + .knockback(0.1f) + .velocity(1.45f) + .renderTumbling() + .soundPitch(1.5f) + .registerAndAssign(Items.MELON_SLICE), - GLISTERING_MELON = create("glistering_melon").damage(5) - .reloadTicks(8) - .knockback(0.1f) - .velocity(1.45f) - .renderTumbling() - .soundPitch(1.5f) - .onEntityHit(potion(MobEffects.GLOWING, 1, 100, true)) - .registerAndAssign(Items.GLISTERING_MELON_SLICE), + GLISTERING_MELON = create("glistering_melon").damage(5) + .reloadTicks(8) + .knockback(0.1f) + .velocity(1.45f) + .renderTumbling() + .soundPitch(1.5f) + .onEntityHit(potion(MobEffects.GLOWING, 1, 100, true)) + .registerAndAssign(Items.GLISTERING_MELON_SLICE), - MELON_BLOCK = create("melon_block").damage(8) - .reloadTicks(20) - .knockback(2.0f) - .velocity(0.95f) - .renderTumbling() - .soundPitch(0.9f) - .onBlockHit(placeBlockOnGround(Blocks.MELON)) - .registerAndAssign(Blocks.MELON), + MELON_BLOCK = create("melon_block").damage(8) + .reloadTicks(20) + .knockback(2.0f) + .velocity(0.95f) + .renderTumbling() + .soundPitch(0.9f) + .onBlockHit(placeBlockOnGround(Blocks.MELON)) + .registerAndAssign(Blocks.MELON), - PUMPKIN_BLOCK = create("pumpkin_block").damage(6) - .reloadTicks(15) - .knockback(2.0f) - .velocity(0.95f) - .renderTumbling() - .soundPitch(0.9f) - .onBlockHit(placeBlockOnGround(Blocks.PUMPKIN)) - .registerAndAssign(Blocks.PUMPKIN), + PUMPKIN_BLOCK = create("pumpkin_block").damage(6) + .reloadTicks(15) + .knockback(2.0f) + .velocity(0.95f) + .renderTumbling() + .soundPitch(0.9f) + .onBlockHit(placeBlockOnGround(Blocks.PUMPKIN)) + .registerAndAssign(Blocks.PUMPKIN), - PUMPKIN_PIE = create("pumpkin_pie").damage(7) - .reloadTicks(15) - .knockback(0.05f) - .velocity(1.1f) - .renderTumbling() - .sticky() - .soundPitch(1.1f) - .registerAndAssign(Items.PUMPKIN_PIE), + PUMPKIN_PIE = create("pumpkin_pie").damage(7) + .reloadTicks(15) + .knockback(0.05f) + .velocity(1.1f) + .renderTumbling() + .sticky() + .soundPitch(1.1f) + .registerAndAssign(Items.PUMPKIN_PIE), - CAKE = create("cake").damage(8) - .reloadTicks(15) - .knockback(0.1f) - .velocity(1.1f) - .renderTumbling() - .sticky() - .soundPitch(1.0f) - .registerAndAssign(Items.CAKE), + CAKE = create("cake").damage(8) + .reloadTicks(15) + .knockback(0.1f) + .velocity(1.1f) + .renderTumbling() + .sticky() + .soundPitch(1.0f) + .registerAndAssign(Items.CAKE), - BLAZE_CAKE = create("blaze_cake").damage(15) - .reloadTicks(20) - .knockback(0.3f) - .velocity(1.1f) - .renderTumbling() - .sticky() - .preEntityHit(setFire(12)) - .soundPitch(1.0f) - .registerAndAssign(AllItems.BLAZE_CAKE.get()) - - ; + BLAZE_CAKE = create("blaze_cake").damage(15) + .reloadTicks(20) + .knockback(0.3f) + .velocity(1.1f) + .renderTumbling() + .sticky() + .preEntityHit(setFire(12)) + .soundPitch(1.0f) + .registerAndAssign(AllItems.BLAZE_CAKE.get()); private static PotatoCannonProjectileType.Builder create(String name) { return new PotatoCannonProjectileType.Builder(Create.asResource(name)); @@ -378,9 +378,8 @@ public class BuiltinPotatoProjectileTypes { Level world = entity.getCommandSenderWorld(); if (world.isClientSide) return true; - if (!(entity instanceof LivingEntity)) + if (!(entity instanceof LivingEntity livingEntity)) return false; - LivingEntity livingEntity = (LivingEntity) entity; double entityX = livingEntity.getX(); double entityY = livingEntity.getY(); @@ -415,6 +414,7 @@ public class BuiltinPotatoProjectileTypes { }; } - public static void register() {} + public static void register() { + } } diff --git a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java index 379cc79043..38e784ebfa 100644 --- a/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/potatoCannon/PotatoProjectileEntity.java @@ -35,6 +35,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.entity.IEntityAdditionalSpawnData; import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.network.NetworkHooks; @@ -223,14 +224,12 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements if (random.nextDouble() <= recoveryChance) recoverItem(); - if (!(target instanceof LivingEntity)) { + if (!(target instanceof LivingEntity livingentity)) { playHitSound(level(), position()); kill(); return; } - LivingEntity livingentity = (LivingEntity) target; - if (type.getReloadTicks() < 10) livingentity.invulnerableTime = type.getReloadTicks() + 10; @@ -254,8 +253,7 @@ public class PotatoProjectileEntity extends AbstractHurtingProjectile implements .send(new ClientboundGameEventPacket(ClientboundGameEventPacket.ARROW_HIT_PLAYER, 0.0F)); } - if (onServer && owner instanceof ServerPlayer) { - ServerPlayer serverplayerentity = (ServerPlayer) owner; + if (onServer && owner instanceof ServerPlayer serverplayerentity) { if (!target.isAlive() && target.getType() .getCategory() == MobCategory.MONSTER || (target instanceof Player && target != owner)) AllAdvancements.POTATO_CANNON.awardTo(serverplayerentity); diff --git a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java index 06f97c6c0f..8b7c13f7be 100644 --- a/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/sandPaper/SandPaperItem.java @@ -34,6 +34,7 @@ import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.extensions.common.IClientItemExtensions; @@ -74,9 +75,8 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { } HitResult raytraceresult = getPlayerPOVHitResult(worldIn, playerIn, ClipContext.Fluid.NONE); - if (!(raytraceresult instanceof BlockHitResult)) + if (!(raytraceresult instanceof BlockHitResult ray)) return FAIL; - BlockHitResult ray = (BlockHitResult) raytraceresult; Vec3 hitVec = ray.getLocation(); AABB bb = new AABB(hitVec, hitVec).inflate(1f); @@ -117,9 +117,8 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { @Override public ItemStack finishUsingItem(ItemStack stack, Level worldIn, LivingEntity entityLiving) { - if (!(entityLiving instanceof Player)) + if (!(entityLiving instanceof Player player)) return stack; - Player player = (Player) entityLiving; CompoundTag tag = stack.getOrCreateTag(); if (tag.contains("Polishing")) { ItemStack toPolish = ItemStack.of(tag.getCompound("Polishing")); @@ -128,8 +127,8 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { if (worldIn.isClientSide) { spawnParticles(entityLiving.getEyePosition(1) - .add(entityLiving.getLookAngle() - .scale(.5f)), + .add(entityLiving.getLookAngle() + .scale(.5f)), toPolish, worldIn); return stack; } @@ -159,9 +158,8 @@ public class SandPaperItem extends Item implements CustomUseEffectsItem { @Override public void releaseUsing(ItemStack stack, Level worldIn, LivingEntity entityLiving, int timeLeft) { - if (!(entityLiving instanceof Player)) + if (!(entityLiving instanceof Player player)) return; - Player player = (Player) entityLiving; CompoundTag tag = stack.getOrCreateTag(); if (tag.contains("Polishing")) { ItemStack toPolish = ItemStack.of(tag.getCompound("Polishing")); diff --git a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java index 1870725522..0d22ed7c6a 100644 --- a/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/symmetryWand/SymmetryWandItem.java @@ -20,8 +20,8 @@ import com.simibubi.create.foundation.item.render.SimpleCustomRenderer; import com.simibubi.create.foundation.utility.BlockHelper; import com.simibubi.create.infrastructure.config.AllConfigs; -import net.createmod.catnip.gui.ScreenOpener; import net.createmod.catnip.data.Iterate; +import net.createmod.catnip.gui.ScreenOpener; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; @@ -42,6 +42,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.extensions.common.IClientItemExtensions; @@ -149,13 +150,13 @@ public class SymmetryWandItem extends Item { playerIn.getCooldowns() .addCooldown(this, 5); } - return new InteractionResultHolder(InteractionResult.SUCCESS, wand); + return new InteractionResultHolder<>(InteractionResult.SUCCESS, wand); } // No Shift -> Clear Mirror wand.getTag() .putBoolean(ENABLE, false); - return new InteractionResultHolder(InteractionResult.SUCCESS, wand); + return new InteractionResultHolder<>(InteractionResult.SUCCESS, wand); } @OnlyIn(Dist.CLIENT) diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java index 3fb2141113..f82dc087ac 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxBlockEntity.java @@ -16,9 +16,9 @@ import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour import com.simibubi.create.foundation.blockEntity.behaviour.animatedContainer.AnimatedContainerBehaviour; import com.simibubi.create.foundation.utility.ResetableLazy; -import net.createmod.catnip.math.VecHelper; import net.createmod.catnip.animation.LerpedFloat; import net.createmod.catnip.animation.LerpedFloat.Chaser; +import net.createmod.catnip.math.VecHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; @@ -36,6 +36,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.IItemHandler; @@ -114,7 +115,7 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider boolean update = false; for (Iterator>> toolboxSlots = connectedPlayers.entrySet() - .iterator(); toolboxSlots.hasNext();) { + .iterator(); toolboxSlots.hasNext(); ) { Entry> toolboxSlotEntry = toolboxSlots.next(); WeakHashMap set = toolboxSlotEntry.getValue(); @@ -124,7 +125,7 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider boolean clear = referenceItem.isEmpty(); for (Iterator> playerEntries = set.entrySet() - .iterator(); playerEntries.hasNext();) { + .iterator(); playerEntries.hasNext(); ) { Entry playerEntry = playerEntries.next(); Player player = playerEntry.getKey(); @@ -216,16 +217,11 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider Set affected = new HashSet<>(); - for (Iterator>> toolboxSlots = connectedPlayers.entrySet() - .iterator(); toolboxSlots.hasNext();) { + for (Entry> toolboxSlotEntry : connectedPlayers.entrySet()) { - Entry> toolboxSlotEntry = toolboxSlots.next(); WeakHashMap set = toolboxSlotEntry.getValue(); - for (Iterator> playerEntries = set.entrySet() - .iterator(); playerEntries.hasNext();) { - Entry playerEntry = playerEntries.next(); - + for (Entry playerEntry : set.entrySet()) { Player player = playerEntry.getKey(); int hotbarSlot = playerEntry.getValue(); @@ -356,8 +352,8 @@ public class ToolboxBlockEntity extends SmartBlockEntity implements MenuProvider public Component getDisplayName() { return customName != null ? customName : AllBlocks.TOOLBOXES.get(getColor()) - .get() - .getName(); + .get() + .getName(); } @Override diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java index 1890dadb04..924a61054b 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxDisposeAllPacket.java @@ -12,6 +12,7 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; + import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.network.NetworkEvent.Context; @@ -43,9 +44,8 @@ public class ToolboxDisposeAllPacket extends SimplePacketBase { if (player.distanceToSqr(toolboxPos.getX() + 0.5, toolboxPos.getY(), toolboxPos.getZ() + 0.5) > maxRange * maxRange) return; - if (!(blockEntity instanceof ToolboxBlockEntity)) + if (!(blockEntity instanceof ToolboxBlockEntity toolbox)) return; - ToolboxBlockEntity toolbox = (ToolboxBlockEntity) blockEntity; CompoundTag compound = player.getPersistentData() .getCompound("CreateToolboxData"); @@ -55,19 +55,19 @@ public class ToolboxDisposeAllPacket extends SimplePacketBase { for (int i = 0; i < 36; i++) { String key = String.valueOf(i); if (compound.contains(key) && NbtUtils.readBlockPos(compound.getCompound(key) - .getCompound("Pos")) + .getCompound("Pos")) .equals(toolboxPos)) { ToolboxHandler.unequip(player, i, true); sendData.setTrue(); } - + ItemStack itemStack = player.getInventory().getItem(i); ItemStack remainder = ItemHandlerHelper.insertItemStacked(toolbox.inventory, itemStack, false); if (remainder.getCount() != itemStack.getCount()) player.getInventory().setItem(i, remainder); } }); - + if (sendData.booleanValue()) ToolboxHandler.syncData(player); }); diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java index a63c4befaf..4352c4c567 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxEquipPacket.java @@ -10,6 +10,7 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; + import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.network.NetworkEvent.Context; @@ -59,7 +60,7 @@ public class ToolboxEquipPacket extends SimplePacketBase { if (player.distanceToSqr(toolboxPos.getX() + 0.5, toolboxPos.getY(), toolboxPos.getZ() + 0.5) > maxRange * maxRange) return; - if (!(blockEntity instanceof ToolboxBlockEntity)) + if (!(blockEntity instanceof ToolboxBlockEntity toolboxBlockEntity)) return; ToolboxHandler.unequip(player, hotbarSlot, false); @@ -69,8 +70,6 @@ public class ToolboxEquipPacket extends SimplePacketBase { return; } - ToolboxBlockEntity toolboxBlockEntity = (ToolboxBlockEntity) blockEntity; - ItemStack playerStack = player.getInventory().getItem(hotbarSlot); if (!playerStack.isEmpty() && !ToolboxInventory.canItemsShareCompartment(playerStack, toolboxBlockEntity.inventory.filters.get(slot))) { diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java index 232c85cad7..f2718a0458 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxHandler.java @@ -20,6 +20,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.network.PacketDistributor; public class ToolboxHandler { @@ -44,12 +45,11 @@ public class ToolboxHandler { return; if (!(world instanceof ServerLevel)) return; - if (!(entity instanceof ServerPlayer)) + if (!(entity instanceof ServerPlayer player)) return; if (entity.tickCount % validationTimer != 0) return; - ServerPlayer player = (ServerPlayer) entity; if (!player.getPersistentData() .contains("CreateToolboxData")) return; @@ -90,8 +90,8 @@ public class ToolboxHandler { if (player.getPersistentData() .contains("CreateToolboxData") && !player.getPersistentData() - .getCompound("CreateToolboxData") - .isEmpty()) { + .getCompound("CreateToolboxData") + .isEmpty()) { syncData(player); } } @@ -128,8 +128,7 @@ public class ToolboxHandler { int prevSlot = prevData.getInt("Slot"); BlockEntity prevBlockEntity = world.getBlockEntity(prevPos); - if (prevBlockEntity instanceof ToolboxBlockEntity) { - ToolboxBlockEntity toolbox = (ToolboxBlockEntity) prevBlockEntity; + if (prevBlockEntity instanceof ToolboxBlockEntity toolbox) { toolbox.unequip(prevSlot, player, hotbarSlot, keepItems || !ToolboxHandler.withinRange(player, toolbox)); } compound.remove(key); diff --git a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java index f7db862c84..d7ca5fd995 100644 --- a/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java +++ b/src/main/java/com/simibubi/create/content/equipment/toolbox/ToolboxMenu.java @@ -19,6 +19,7 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; + import net.minecraftforge.items.SlotItemHandler; public class ToolboxMenu extends MenuBase { @@ -44,8 +45,7 @@ public class ToolboxMenu extends MenuBase { ClientLevel world = Minecraft.getInstance().level; BlockEntity blockEntity = world.getBlockEntity(readBlockPos); - if (blockEntity instanceof ToolboxBlockEntity) { - ToolboxBlockEntity toolbox = (ToolboxBlockEntity) blockEntity; + if (blockEntity instanceof ToolboxBlockEntity toolbox) { toolbox.readClient(readNbt); return toolbox; } @@ -130,8 +130,8 @@ public class ToolboxMenu extends MenuBase { int x = 79; int y = 37; - int[] xOffsets = { x, x + 33, x + 66, x + 66 + 6, x + 66, x + 33, x, x - 6 }; - int[] yOffsets = { y, y - 6, y, y + 33, y + 66, y + 66 + 6, y + 66, y + 33 }; + int[] xOffsets = {x, x + 33, x + 66, x + 66 + 6, x + 66, x + 33, x, x - 6}; + int[] yOffsets = {y, y - 6, y, y + 33, y + 66, y + 66 + 6, y + 66, y + 33}; for (int compartment = 0; compartment < 8; compartment++) { int baseIndex = compartment * STACKS_PER_COMPARTMENT; diff --git a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java index b9d6bb3bbe..72f66f9ca4 100644 --- a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java +++ b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchEventHandler.java @@ -10,6 +10,7 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; + import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; @@ -40,12 +41,11 @@ public class WrenchEventHandler { .getBlockState(event.getPos()); Block block = state.getBlock(); - if (!(block instanceof IWrenchable)) + if (!(block instanceof IWrenchable actor)) return; BlockHitResult hitVec = event.getHitVec(); UseOnContext context = new UseOnContext(player, event.getHand(), hitVec); - IWrenchable actor = (IWrenchable) block; InteractionResult result = player.isShiftKeyDown() ? actor.onSneakWrenched(state, context) : actor.onWrenched(state, context); diff --git a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java index cfdf6b45c4..9dfc92e907 100644 --- a/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java +++ b/src/main/java/com/simibubi/create/content/equipment/wrench/WrenchItem.java @@ -22,6 +22,7 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.extensions.common.IClientItemExtensions; @@ -44,13 +45,12 @@ public class WrenchItem extends Item { .getBlockState(context.getClickedPos()); Block block = state.getBlock(); - if (!(block instanceof IWrenchable)) { + if (!(block instanceof IWrenchable actor)) { if (player.isShiftKeyDown() && canWrenchPickup(state)) return onItemUseOnOther(context); return super.useOn(context); } - IWrenchable actor = (IWrenchable) block; if (player.isShiftKeyDown()) return actor.onSneakWrenched(state, context); return actor.onWrenched(state, context); @@ -78,7 +78,7 @@ public class WrenchItem extends Item { public static void wrenchInstaKillsMinecarts(AttackEntityEvent event) { Entity target = event.getTarget(); - if (!(target instanceof AbstractMinecart)) + if (!(target instanceof AbstractMinecart minecart)) return; Player player = event.getEntity(); ItemStack heldItem = player.getMainHandItem(); @@ -86,7 +86,6 @@ public class WrenchItem extends Item { return; if (player.isCreative()) return; - AbstractMinecart minecart = (AbstractMinecart) target; minecart.hurt(minecart.damageSources().playerAttack(player), 100); } diff --git a/src/main/java/com/simibubi/create/content/fluids/drain/ItemDrainBlock.java b/src/main/java/com/simibubi/create/content/fluids/drain/ItemDrainBlock.java index 5cd049aa30..e45de5ed8d 100644 --- a/src/main/java/com/simibubi/create/content/fluids/drain/ItemDrainBlock.java +++ b/src/main/java/com/simibubi/create/content/fluids/drain/ItemDrainBlock.java @@ -32,6 +32,7 @@ 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.minecraftforge.common.capabilities.ForgeCapabilities; public class ItemDrainBlock extends Block implements IWrenchable, IBE { @@ -42,12 +43,12 @@ public class ItemDrainBlock extends Block implements IWrenchable, IBE { @@ -73,14 +74,13 @@ public class ItemDrainBlock extends Block implements IWrenchable, IBE type; private FluidStack fluid; - public FluidParticleData() {} + public FluidParticleData() { + } @SuppressWarnings("unchecked") public FluidParticleData(ParticleType type, FluidStack fluid) { @@ -68,7 +70,7 @@ public class FluidParticleData implements ParticleOptions, ICustomParticleData new FluidParticleData(AllParticleTypes.FLUID_DRIP.get(), fs))); public static final ParticleOptions.Deserializer DESERIALIZER = - new ParticleOptions.Deserializer() { + new ParticleOptions.Deserializer<>() { // TODO Fluid particles on command public FluidParticleData fromCommand(ParticleType particleTypeIn, StringReader reader) diff --git a/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlock.java b/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlock.java index a0b0fae2c2..aa42298841 100644 --- a/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlock.java +++ b/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlock.java @@ -58,13 +58,13 @@ public class PumpBlock extends DirectionalKineticBlock @Override public VoxelShape getShape(BlockState state, BlockGetter p_220053_2_, BlockPos p_220053_3_, - CollisionContext p_220053_4_) { + CollisionContext p_220053_4_) { return AllShapes.PUMP.get(state.getValue(FACING)); } @Override public void neighborChanged(BlockState state, Level world, BlockPos pos, Block otherBlock, BlockPos neighborPos, - boolean isMoving) { + boolean isMoving) { DebugPackets.sendNeighborsUpdatePacket(world, pos); Direction d = FluidPropagator.validateNeighbourChange(state, world, pos, otherBlock, neighborPos, isMoving); if (d == null) @@ -88,7 +88,7 @@ public class PumpBlock extends DirectionalKineticBlock @Override public BlockState updateShape(BlockState state, Direction direction, BlockState neighbourState, LevelAccessor world, - BlockPos pos, BlockPos neighbourPos) { + BlockPos pos, BlockPos neighbourPos) { if (state.getValue(BlockStateProperties.WATERLOGGED)) world.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); return state; @@ -146,9 +146,8 @@ public class PumpBlock extends DirectionalKineticBlock if (isPump(state) && isPump(oldState) && state.getValue(FACING) == oldState.getValue(FACING) .getOpposite()) { BlockEntity blockEntity = world.getBlockEntity(pos); - if (!(blockEntity instanceof PumpBlockEntity)) + if (!(blockEntity instanceof PumpBlockEntity pump)) return; - PumpBlockEntity pump = (PumpBlockEntity) blockEntity; pump.pressureUpdate = true; } } diff --git a/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlockEntity.java b/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlockEntity.java index 0a2bb05d3d..a8b3f9a9f9 100644 --- a/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/fluids/pump/PumpBlockEntity.java @@ -21,10 +21,10 @@ import com.simibubi.create.foundation.advancement.AllAdvancements; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; -import net.createmod.catnip.math.BlockFace; import net.createmod.catnip.data.Couple; import net.createmod.catnip.data.Iterate; import net.createmod.catnip.data.Pair; +import net.createmod.catnip.math.BlockFace; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; @@ -33,6 +33,7 @@ import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; + import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.fluids.capability.IFluidHandler; @@ -226,7 +227,7 @@ public class PumpBlockEntity extends KineticBlockEntity { } protected boolean searchForEndpointRecursively(Map>> pipeGraph, - Set targets, Map> validFaces, BlockFace currentFace, boolean pull) { + Set targets, Map> validFaces, BlockFace currentFace, boolean pull) { BlockPos currentPos = currentFace.getPos(); if (!pipeGraph.containsKey(currentPos)) return false; @@ -275,8 +276,7 @@ public class PumpBlockEntity extends KineticBlockEntity { // facing a pump if (PumpBlock.isPump(connectedState) && connectedState.getValue(PumpBlock.FACING) - .getAxis() == face.getAxis() && blockEntity instanceof PumpBlockEntity) { - PumpBlockEntity pumpBE = (PumpBlockEntity) blockEntity; + .getAxis() == face.getAxis() && blockEntity instanceof PumpBlockEntity pumpBE) { return pumpBE.isPullingOnSide(pumpBE.isFront(blockFace.getOppositeFace())) != pull; } @@ -362,7 +362,7 @@ public class PumpBlockEntity extends KineticBlockEntity { @Override public AttachmentTypes getRenderedRimAttachment(BlockAndTintGetter world, BlockPos pos, BlockState state, - Direction direction) { + Direction direction) { AttachmentTypes attachment = super.getRenderedRimAttachment(world, pos, state, direction); if (attachment == AttachmentTypes.RIM) return AttachmentTypes.NONE; diff --git a/src/main/java/com/simibubi/create/content/fluids/tank/FluidTankBlock.java b/src/main/java/com/simibubi/create/content/fluids/tank/FluidTankBlock.java index ebd07cb36a..5c3e237520 100644 --- a/src/main/java/com/simibubi/create/content/fluids/tank/FluidTankBlock.java +++ b/src/main/java/com/simibubi/create/content/fluids/tank/FluidTankBlock.java @@ -49,6 +49,7 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; + import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.ForgeSoundType; import net.minecraftforge.common.util.LazyOptional; @@ -124,7 +125,7 @@ public class FluidTankBlock extends Block implements IWrenchable, IBE pendingFluidTicks = world.getFluidTicks(); - if (pendingFluidTicks instanceof LevelTicks) { - LevelTicks serverTickList = (LevelTicks) pendingFluidTicks; + if (pendingFluidTicks instanceof LevelTicks serverTickList) { serverTickList.clearArea(new BoundingBox(currentPos)); } @@ -268,7 +267,7 @@ public class FluidFillingBehaviour extends FluidManipulationBehaviour { if (fluidState.getType() != Fluids.EMPTY && blockState.getCollisionShape(getWorld(), pos, CollisionContext.empty()) - .isEmpty()) + .isEmpty()) return toFill.isSame(fluidState.getType()) ? SpaceType.FILLED : SpaceType.BLOCKING; return canBeReplacedByFluid(world, pos, blockState) ? SpaceType.FILLABLE : SpaceType.BLOCKING; diff --git a/src/main/java/com/simibubi/create/content/kinetics/KineticDebugger.java b/src/main/java/com/simibubi/create/content/kinetics/KineticDebugger.java index 42bc5c6625..b8716230f7 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/KineticDebugger.java +++ b/src/main/java/com/simibubi/create/content/kinetics/KineticDebugger.java @@ -5,9 +5,9 @@ import com.simibubi.create.content.kinetics.base.KineticBlockEntity; import com.simibubi.create.content.kinetics.base.KineticBlockEntityRenderer; import com.simibubi.create.infrastructure.config.AllConfigs; -import net.createmod.catnip.render.SuperByteBufferCache; import net.createmod.catnip.math.VecHelper; import net.createmod.catnip.outliner.Outliner; +import net.createmod.catnip.render.SuperByteBufferCache; import net.createmod.catnip.theme.Color; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; @@ -47,16 +47,16 @@ public class KineticDebugger { if (be.getTheoreticalSpeed() != 0 && !shape.isEmpty()) Outliner.getInstance().chaseAABB("kineticSource", shape.bounds() .move(toOutline)) - .lineWidth(1 / 16f) - .colored(be.hasSource() ? Color.generateFromLong(be.network).getRGB() : 0xffcc00); + .lineWidth(1 / 16f) + .colored(be.hasSource() ? Color.generateFromLong(be.network).getRGB() : 0xffcc00); if (state.getBlock() instanceof IRotate) { Axis axis = ((IRotate) state.getBlock()).getRotationAxis(state); Vec3 vec = Vec3.atLowerCornerOf(Direction.get(AxisDirection.POSITIVE, axis) - .getNormal()); + .getNormal()); Vec3 center = VecHelper.getCenterOf(be.getBlockPos()); Outliner.getInstance().showLine("rotationAxis", center.add(vec), center.subtract(vec)) - .lineWidth(1 / 16f); + .lineWidth(1 / 16f); } } @@ -76,10 +76,9 @@ public class KineticDebugger { return null; if (world == null) return null; - if (!(obj instanceof BlockHitResult)) + if (!(obj instanceof BlockHitResult ray)) return null; - BlockHitResult ray = (BlockHitResult) obj; BlockEntity be = world.getBlockEntity(ray.getBlockPos()); if (!(be instanceof KineticBlockEntity)) return null; diff --git a/src/main/java/com/simibubi/create/content/kinetics/RotationPropagator.java b/src/main/java/com/simibubi/create/content/kinetics/RotationPropagator.java index 848b579748..0b2ad4f2f7 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/RotationPropagator.java +++ b/src/main/java/com/simibubi/create/content/kinetics/RotationPropagator.java @@ -47,11 +47,9 @@ public class RotationPropagator { Block fromBlock = stateFrom.getBlock(); Block toBlock = stateTo.getBlock(); - if (!(fromBlock instanceof IRotate && toBlock instanceof IRotate)) + if (!(fromBlock instanceof IRotate definitionFrom && toBlock instanceof IRotate definitionTo)) return 0; - final IRotate definitionFrom = (IRotate) fromBlock; - final IRotate definitionTo = (IRotate) toBlock; final BlockPos diff = to.getBlockPos() .subtract(from.getBlockPos()); final Direction direction = Direction.getNearest(diff.getX(), diff.getY(), diff.getZ()); @@ -157,7 +155,7 @@ public class RotationPropagator { } private static float getAxisModifier(KineticBlockEntity be, Direction direction) { - if (!(be.hasSource()||be.isSource()) || !(be instanceof DirectionalShaftHalvesBlockEntity)) + if (!(be.hasSource() || be.isSource()) || !(be instanceof DirectionalShaftHalvesBlockEntity)) return 1; Direction source = ((DirectionalShaftHalvesBlockEntity) be).getSourceFacing(); @@ -235,7 +233,7 @@ public class RotationPropagator { Math.signum(newSpeed) != Math.signum(speedOfNeighbour) && (newSpeed != 0 && speedOfNeighbour != 0); boolean tooFast = Math.abs(newSpeed) > AllConfigs.server().kinetics.maxRotationSpeed.get() - || Math.abs(oppositeSpeed) > AllConfigs.server().kinetics.maxRotationSpeed.get(); + || Math.abs(oppositeSpeed) > AllConfigs.server().kinetics.maxRotationSpeed.get(); // Check for both the new speed and the opposite speed, just in case boolean speedChangedTooOften = currentTE.getFlickerScore() > MAX_FLICKER_SCORE; @@ -321,10 +319,9 @@ public class RotationPropagator { if (!(neighbourState.getBlock() instanceof IRotate)) continue; BlockEntity blockEntity = worldIn.getBlockEntity(neighbourPos); - if (!(blockEntity instanceof KineticBlockEntity)) + if (!(blockEntity instanceof KineticBlockEntity neighbourBE)) continue; - final KineticBlockEntity neighbourBE = (KineticBlockEntity) blockEntity; if (!neighbourBE.hasSource() || !neighbourBE.source.equals(pos)) continue; @@ -350,9 +347,8 @@ public class RotationPropagator { while (!frontier.isEmpty()) { final BlockPos pos = frontier.remove(0); BlockEntity blockEntity = world.getBlockEntity(pos); - if (!(blockEntity instanceof KineticBlockEntity)) + if (!(blockEntity instanceof KineticBlockEntity currentBE)) continue; - final KineticBlockEntity currentBE = (KineticBlockEntity) blockEntity; currentBE.removeSource(); currentBE.sendData(); @@ -393,9 +389,8 @@ public class RotationPropagator { return null; BlockEntity neighbourBE = currentTE.getLevel() .getBlockEntity(neighbourPos); - if (!(neighbourBE instanceof KineticBlockEntity)) + if (!(neighbourBE instanceof KineticBlockEntity neighbourKBE)) return null; - KineticBlockEntity neighbourKBE = (KineticBlockEntity) neighbourBE; if (!(neighbourKBE.getBlockState() .getBlock() instanceof IRotate)) return null; @@ -439,9 +434,8 @@ public class RotationPropagator { } BlockState blockState = be.getBlockState(); - if (!(blockState.getBlock() instanceof IRotate)) + if (!(blockState.getBlock() instanceof IRotate block)) return neighbours; - IRotate block = (IRotate) blockState.getBlock(); return be.addPropagationLocations(block, blockState, neighbours); } diff --git a/src/main/java/com/simibubi/create/content/kinetics/base/GeneratingKineticBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/base/GeneratingKineticBlockEntity.java index 6aa907f995..e3c5e67db3 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/base/GeneratingKineticBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/base/GeneratingKineticBlockEntity.java @@ -38,9 +38,8 @@ public abstract class GeneratingKineticBlockEntity extends KineticBlockEntity { public void setSource(BlockPos source) { super.setSource(source); BlockEntity blockEntity = level.getBlockEntity(source); - if (!(blockEntity instanceof KineticBlockEntity)) + if (!(blockEntity instanceof KineticBlockEntity sourceBE)) return; - KineticBlockEntity sourceBE = (KineticBlockEntity) blockEntity; if (reActivateSource && Math.abs(sourceBE.getSpeed()) >= Math.abs(getGeneratedSpeed())) reActivateSource = false; } diff --git a/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlock.java b/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlock.java index 40882f34f5..d92c48f1db 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlock.java +++ b/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlock.java @@ -28,8 +28,7 @@ public abstract class KineticBlock extends Block implements IRotate { // we can prevent a major re-propagation here BlockEntity blockEntity = worldIn.getBlockEntity(pos); - if (blockEntity instanceof KineticBlockEntity) { - KineticBlockEntity kineticBlockEntity = (KineticBlockEntity) blockEntity; + if (blockEntity instanceof KineticBlockEntity kineticBlockEntity) { kineticBlockEntity.preventSpeedUpdate = 0; if (oldState.getBlock() != state.getBlock()) @@ -42,7 +41,7 @@ public abstract class KineticBlock extends Block implements IRotate { kineticBlockEntity.preventSpeedUpdate = 2; } } - + @Override public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) { IBE.onRemove(pState, pLevel, pPos, pNewState); @@ -61,14 +60,13 @@ public abstract class KineticBlock extends Block implements IRotate { @Override public void updateIndirectNeighbourShapes(BlockState stateIn, LevelAccessor worldIn, BlockPos pos, int flags, - int count) { + int count) { if (worldIn.isClientSide()) return; BlockEntity blockEntity = worldIn.getBlockEntity(pos); - if (!(blockEntity instanceof KineticBlockEntity)) + if (!(blockEntity instanceof KineticBlockEntity kbe)) return; - KineticBlockEntity kbe = (KineticBlockEntity) blockEntity; if (kbe.preventSpeedUpdate > 0) return; @@ -86,10 +84,9 @@ public abstract class KineticBlock extends Block implements IRotate { return; BlockEntity blockEntity = worldIn.getBlockEntity(pos); - if (!(blockEntity instanceof KineticBlockEntity)) + if (!(blockEntity instanceof KineticBlockEntity kbe)) return; - KineticBlockEntity kbe = (KineticBlockEntity) blockEntity; kbe.effects.queueRotationIndicators(); } diff --git a/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlockEntity.java index aa408210db..9f0ac2d03c 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/base/KineticBlockEntity.java @@ -415,9 +415,9 @@ public class KineticBlockEntity extends SmartBlockEntity implements IHaveGoggleI .forGoggles(tooltip); Component hint = CreateLang.translateDirect("gui.contraptions.network_overstressed"); List cutString = TooltipHelper.cutTextComponent(hint, Palette.GRAY_AND_WHITE); - for (int i = 0; i < cutString.size(); i++) + for (Component component : cutString) CreateLang.builder() - .add(cutString.get(i) + .add(component .copy()) .forGoggles(tooltip); return true; @@ -431,9 +431,9 @@ public class KineticBlockEntity extends SmartBlockEntity implements IHaveGoggleI CreateLang.translateDirect("gui.contraptions.not_fast_enough", I18n.get(getBlockState().getBlock() .getDescriptionId())); List cutString = TooltipHelper.cutTextComponent(hint, Palette.GRAY_AND_WHITE); - for (int i = 0; i < cutString.size(); i++) + for (Component component : cutString) CreateLang.builder() - .add(cutString.get(i) + .add(component .copy()) .forGoggles(tooltip); return true; diff --git a/src/main/java/com/simibubi/create/content/kinetics/base/KineticEffectHandler.java b/src/main/java/com/simibubi/create/content/kinetics/base/KineticEffectHandler.java index ef97f7638d..0a49c8a449 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/base/KineticEffectHandler.java +++ b/src/main/java/com/simibubi/create/content/kinetics/base/KineticEffectHandler.java @@ -76,10 +76,9 @@ public class KineticEffectHandler { BlockState state = kte.getBlockState(); Block block = state.getBlock(); - if (!(block instanceof KineticBlock)) + if (!(block instanceof KineticBlock kb)) return; - KineticBlock kb = (KineticBlock) block; float radius1 = kb.getParticleInitialRadius(); float radius2 = kb.getParticleTargetRadius(); diff --git a/src/main/java/com/simibubi/create/content/kinetics/base/RotationIndicatorParticleData.java b/src/main/java/com/simibubi/create/content/kinetics/base/RotationIndicatorParticleData.java index 7a249f6989..5cc799074d 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/base/RotationIndicatorParticleData.java +++ b/src/main/java/com/simibubi/create/content/kinetics/base/RotationIndicatorParticleData.java @@ -17,6 +17,7 @@ import net.minecraft.core.Direction.Axis; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; import net.minecraft.network.FriendlyByteBuf; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -24,7 +25,7 @@ public class RotationIndicatorParticleData implements ParticleOptions, ICustomParticleDataWithSprite { // TODO 1.16 make this unnecessary - public static final PrimitiveCodec CHAR = new PrimitiveCodec() { + public static final PrimitiveCodec CHAR = new PrimitiveCodec<>() { @Override public DataResult read(final DynamicOps ops, final T input) { return ops.getNumberValue(input) @@ -44,7 +45,7 @@ public class RotationIndicatorParticleData public static final Codec CODEC = RecordCodecBuilder.create(i -> i .group(Codec.INT.fieldOf("color") - .forGetter(p -> p.color), + .forGetter(p -> p.color), Codec.FLOAT.fieldOf("speed") .forGetter(p -> p.speed), Codec.FLOAT.fieldOf("radius1") @@ -58,9 +59,9 @@ public class RotationIndicatorParticleData .apply(i, RotationIndicatorParticleData::new)); public static final ParticleOptions.Deserializer DESERIALIZER = - new ParticleOptions.Deserializer() { + new ParticleOptions.Deserializer<>() { public RotationIndicatorParticleData fromCommand(ParticleType particleTypeIn, - StringReader reader) throws CommandSyntaxException { + StringReader reader) throws CommandSyntaxException { reader.expect(' '); int color = reader.readInt(); reader.expect(' '); @@ -77,7 +78,7 @@ public class RotationIndicatorParticleData } public RotationIndicatorParticleData fromNetwork(ParticleType particleTypeIn, - FriendlyByteBuf buffer) { + FriendlyByteBuf buffer) { return new RotationIndicatorParticleData(buffer.readInt(), buffer.readFloat(), buffer.readFloat(), buffer.readFloat(), buffer.readInt(), buffer.readChar()); } @@ -91,7 +92,7 @@ public class RotationIndicatorParticleData final char axis; public RotationIndicatorParticleData(int color, float speed, float radius1, float radius2, int lifeSpan, - char axis) { + char axis) { this.color = color; this.speed = speed; this.radius1 = radius1; @@ -145,4 +146,4 @@ public class RotationIndicatorParticleData return RotationIndicatorParticle.Factory::new; } -} \ No newline at end of file +} diff --git a/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlock.java b/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlock.java index eb1f8ad539..c0e31bb0d3 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlock.java +++ b/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlock.java @@ -141,7 +141,7 @@ public class BeltBlock extends HorizontalKineticBlock @Override public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, - Player player) { + Player player) { return AllItems.BELT_CONNECTOR.asStack(); } @@ -191,8 +191,7 @@ public class BeltBlock extends HorizontalKineticBlock public void entityInside(BlockState state, Level worldIn, BlockPos pos, Entity entityIn) { if (!canTransportObjects(state)) return; - if (entityIn instanceof Player) { - Player player = (Player) entityIn; + if (entityIn instanceof Player player) { if (player.isShiftKeyDown() && !AllItems.CARDBOARD_BOOTS.isIn(player.getItemBySlot(EquipmentSlot.FEET))) return; if (player.getAbilities().flying) @@ -253,7 +252,7 @@ public class BeltBlock extends HorizontalKineticBlock @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand handIn, - BlockHitResult hit) { + BlockHitResult hit) { if (player.isShiftKeyDown() || !player.mayBuild()) return InteractionResult.PASS; ItemStack heldItem = player.getItemInHand(handIn); @@ -403,18 +402,18 @@ public class BeltBlock extends HorizontalKineticBlock return shape; return getBlockEntityOptional(worldIn, pos).map(be -> { - Entity entity = ((EntityCollisionContext) context).getEntity(); - if (entity == null) + Entity entity = ((EntityCollisionContext) context).getEntity(); + if (entity == null) + return shape; + + BeltBlockEntity controller = be.getControllerBE(); + if (controller == null) + return shape; + if (controller.passengers == null || !controller.passengers.containsKey(entity)) + return BeltShapes.getCollisionShape(state); return shape; - BeltBlockEntity controller = be.getControllerBE(); - if (controller == null) - return shape; - if (controller.passengers == null || !controller.passengers.containsKey(entity)) - return BeltShapes.getCollisionShape(state); - return shape; - - }) + }) .orElse(shape); } @@ -462,8 +461,7 @@ public class BeltBlock extends HorizontalKineticBlock BlockEntity blockEntity = world.getBlockEntity(beltPos); BlockState currentState = world.getBlockState(beltPos); - if (blockEntity instanceof BeltBlockEntity && AllBlocks.BELT.has(currentState)) { - BeltBlockEntity be = (BeltBlockEntity) blockEntity; + if (blockEntity instanceof BeltBlockEntity be && AllBlocks.BELT.has(currentState)) { be.setController(currentPos); be.beltLength = beltChain.size(); be.index = index; @@ -505,8 +503,7 @@ public class BeltBlock extends HorizontalKineticBlock boolean hasPulley = false; BlockEntity blockEntity = world.getBlockEntity(currentPos); - if (blockEntity instanceof BeltBlockEntity) { - BeltBlockEntity belt = (BeltBlockEntity) blockEntity; + if (blockEntity instanceof BeltBlockEntity belt) { if (belt.isController()) belt.getInventory() .ejectAll(); @@ -525,7 +522,7 @@ public class BeltBlock extends HorizontalKineticBlock @Override public BlockState updateShape(BlockState state, Direction side, BlockState p_196271_3_, LevelAccessor world, - BlockPos pos, BlockPos p_196271_6_) { + BlockPos pos, BlockPos p_196271_6_) { updateWater(world, state, pos); if (side.getAxis() .isHorizontal()) @@ -635,7 +632,7 @@ public class BeltBlock extends HorizontalKineticBlock return rotate; if (state.getValue(HORIZONTAL_FACING) .getAxisDirection() != rotate.getValue(HORIZONTAL_FACING) - .getAxisDirection()) { + .getAxisDirection()) { if (state.getValue(PART) == BeltPart.START) return rotate.setValue(PART, BeltPart.END); if (state.getValue(PART) == BeltPart.END) diff --git a/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlockEntity.java index 9d25aaacf8..bc1bd8d013 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/belt/BeltBlockEntity.java @@ -45,6 +45,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; @@ -389,7 +390,7 @@ public class BeltBlockEntity extends KineticBlockEntity { } private void applyToAllItems(float maxDistanceFromCenter, - Function processFunction) { + Function processFunction) { BeltBlockEntity controller = getControllerBE(); if (controller == null) return; @@ -472,8 +473,7 @@ public class BeltBlockEntity extends KineticBlockEntity { return inserted; BlockEntity teAbove = level.getBlockEntity(worldPosition.above()); - if (teAbove instanceof BrassTunnelBlockEntity) { - BrassTunnelBlockEntity tunnelBE = (BrassTunnelBlockEntity) teAbove; + if (teAbove instanceof BrassTunnelBlockEntity tunnelBE) { if (tunnelBE.hasDistributionBehaviour()) { if (!tunnelBE.getStackToDistribute() .isEmpty()) @@ -542,7 +542,7 @@ public class BeltBlockEntity extends KineticBlockEntity { @Override public float propagateRotationTo(KineticBlockEntity target, BlockState stateFrom, BlockState stateTo, BlockPos diff, - boolean connectedViaAxes, boolean connectedViaCogs) { + boolean connectedViaAxes, boolean connectedViaCogs) { if (target instanceof BeltBlockEntity && !connectedViaAxes) return getController().equals(((BeltBlockEntity) target).getController()) ? 1 : 0; return 0; diff --git a/src/main/java/com/simibubi/create/content/kinetics/belt/BeltSlicer.java b/src/main/java/com/simibubi/create/content/kinetics/belt/BeltSlicer.java index e29744cf34..e4885c66a1 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/belt/BeltSlicer.java +++ b/src/main/java/com/simibubi/create/content/kinetics/belt/BeltSlicer.java @@ -449,10 +449,9 @@ public class BeltSlicer { public static void tickHoveringInformation() { Minecraft mc = Minecraft.getInstance(); HitResult target = mc.hitResult; - if (target == null || !(target instanceof BlockHitResult)) + if (target == null || !(target instanceof BlockHitResult result)) return; - BlockHitResult result = (BlockHitResult) target; ClientLevel world = mc.level; BlockPos pos = result.getBlockPos(); BlockState state = world.getBlockState(pos); diff --git a/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltCrusherInteractionHandler.java b/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltCrusherInteractionHandler.java index a710973de6..acfe8ec622 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltCrusherInteractionHandler.java +++ b/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltCrusherInteractionHandler.java @@ -11,66 +11,65 @@ 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.state.BlockState; + import net.minecraftforge.items.ItemHandlerHelper; public class BeltCrusherInteractionHandler { - public static boolean checkForCrushers(BeltInventory beltInventory, TransportedItemStack currentItem, - float nextOffset) { + public static boolean checkForCrushers(BeltInventory beltInventory, TransportedItemStack currentItem, + float nextOffset) { - boolean beltMovementPositive = beltInventory.beltMovementPositive; - int firstUpcomingSegment = (int) Math.floor(currentItem.beltPosition); - int step = beltMovementPositive ? 1 : -1; - firstUpcomingSegment = Mth.clamp(firstUpcomingSegment, 0, beltInventory.belt.beltLength - 1); + boolean beltMovementPositive = beltInventory.beltMovementPositive; + int firstUpcomingSegment = (int) Math.floor(currentItem.beltPosition); + int step = beltMovementPositive ? 1 : -1; + firstUpcomingSegment = Mth.clamp(firstUpcomingSegment, 0, beltInventory.belt.beltLength - 1); - for (int segment = firstUpcomingSegment; beltMovementPositive ? segment <= nextOffset - : segment + 1 >= nextOffset; segment += step) { - BlockPos crusherPos = BeltHelper.getPositionForOffset(beltInventory.belt, segment) - .above(); - Level world = beltInventory.belt.getLevel(); - BlockState crusherState = world.getBlockState(crusherPos); - if (!(crusherState.getBlock() instanceof CrushingWheelControllerBlock)) - continue; - Direction crusherFacing = crusherState.getValue(CrushingWheelControllerBlock.FACING); - Direction movementFacing = beltInventory.belt.getMovementFacing(); - if (crusherFacing != movementFacing) - continue; + for (int segment = firstUpcomingSegment; beltMovementPositive ? segment <= nextOffset + : segment + 1 >= nextOffset; segment += step) { + BlockPos crusherPos = BeltHelper.getPositionForOffset(beltInventory.belt, segment) + .above(); + Level world = beltInventory.belt.getLevel(); + BlockState crusherState = world.getBlockState(crusherPos); + if (!(crusherState.getBlock() instanceof CrushingWheelControllerBlock)) + continue; + Direction crusherFacing = crusherState.getValue(CrushingWheelControllerBlock.FACING); + Direction movementFacing = beltInventory.belt.getMovementFacing(); + if (crusherFacing != movementFacing) + continue; - float crusherEntry = segment + .5f; - crusherEntry += .399f * (beltMovementPositive ? -1 : 1); - float postCrusherEntry = crusherEntry + .799f * (!beltMovementPositive ? -1 : 1); + float crusherEntry = segment + .5f; + crusherEntry += .399f * (beltMovementPositive ? -1 : 1); + float postCrusherEntry = crusherEntry + .799f * (!beltMovementPositive ? -1 : 1); - boolean hasCrossed = nextOffset > crusherEntry && nextOffset < postCrusherEntry && beltMovementPositive - || nextOffset < crusherEntry && nextOffset > postCrusherEntry && !beltMovementPositive; - if (!hasCrossed) - return false; - currentItem.beltPosition = crusherEntry; + boolean hasCrossed = nextOffset > crusherEntry && nextOffset < postCrusherEntry && beltMovementPositive + || nextOffset < crusherEntry && nextOffset > postCrusherEntry && !beltMovementPositive; + if (!hasCrossed) + return false; + currentItem.beltPosition = crusherEntry; - BlockEntity be = world.getBlockEntity(crusherPos); - if (!(be instanceof CrushingWheelControllerBlockEntity)) - return true; + BlockEntity be = world.getBlockEntity(crusherPos); + if (!(be instanceof CrushingWheelControllerBlockEntity crusherBE)) + return true; - CrushingWheelControllerBlockEntity crusherBE = (CrushingWheelControllerBlockEntity) be; + ItemStack toInsert = currentItem.stack.copy(); - ItemStack toInsert = currentItem.stack.copy(); + ItemStack remainder = ItemHandlerHelper.insertItemStacked(crusherBE.inventory, toInsert, false); + if (toInsert.equals(remainder, false)) + return true; - ItemStack remainder = ItemHandlerHelper.insertItemStacked(crusherBE.inventory, toInsert, false); - if (toInsert.equals(remainder, false)) - return true; + int notFilled = currentItem.stack.getCount() - toInsert.getCount(); + if (!remainder.isEmpty()) { + remainder.grow(notFilled); + } else if (notFilled > 0) + remainder = ItemHandlerHelper.copyStackWithSize(currentItem.stack, notFilled); - int notFilled = currentItem.stack.getCount() - toInsert.getCount(); - if (!remainder.isEmpty()) { - remainder.grow(notFilled); - } else if (notFilled > 0) - remainder = ItemHandlerHelper.copyStackWithSize(currentItem.stack, notFilled); + currentItem.stack = remainder; + beltInventory.belt.sendData(); + return true; + } - currentItem.stack = remainder; - beltInventory.belt.sendData(); - return true; - } - - return false; - } + return false; + } } diff --git a/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltFunnelInteractionHandler.java b/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltFunnelInteractionHandler.java index 3b214e46e1..3b8267193e 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltFunnelInteractionHandler.java +++ b/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltFunnelInteractionHandler.java @@ -15,12 +15,13 @@ 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.state.BlockState; + import net.minecraftforge.items.ItemHandlerHelper; public class BeltFunnelInteractionHandler { public static boolean checkForFunnels(BeltInventory beltInventory, TransportedItemStack currentItem, - float nextOffset) { + float nextOffset) { boolean beltMovementPositive = beltInventory.beltMovementPositive; int firstUpcomingSegment = (int) Math.floor(currentItem.beltPosition); int step = beltMovementPositive ? 1 : -1; @@ -59,10 +60,9 @@ public class BeltFunnelInteractionHandler { continue; BlockEntity be = world.getBlockEntity(funnelPos); - if (!(be instanceof FunnelBlockEntity)) + if (!(be instanceof FunnelBlockEntity funnelBE)) return true; - FunnelBlockEntity funnelBE = (FunnelBlockEntity) be; InvManipulationBehaviour inserting = funnelBE.getBehaviour(InvManipulationBehaviour.TYPE); FilteringBehaviour filtering = funnelBE.getBehaviour(FilteringBehaviour.TYPE); @@ -72,7 +72,7 @@ public class BeltFunnelInteractionHandler { else continue; - if(beltInventory.belt.invVersionTracker.stillWaiting(inserting)) + if (beltInventory.belt.invVersionTracker.stillWaiting(inserting)) continue; int amountToExtract = funnelBE.getAmountToExtract(); diff --git a/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltTunnelInteractionHandler.java b/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltTunnelInteractionHandler.java index ce5a8b5db0..4bd951beb0 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltTunnelInteractionHandler.java +++ b/src/main/java/com/simibubi/create/content/kinetics/belt/transport/BeltTunnelInteractionHandler.java @@ -21,12 +21,13 @@ 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.state.BlockState; + import net.minecraftforge.items.ItemHandlerHelper; public class BeltTunnelInteractionHandler { public static boolean flapTunnelsAndCheckIfStuck(BeltInventory beltInventory, TransportedItemStack current, - float nextOffset) { + float nextOffset) { int currentSegment = (int) current.beltPosition; int upcomingSegment = (int) nextOffset; @@ -48,8 +49,7 @@ public class BeltTunnelInteractionHandler { BeltTunnelBlockEntity nextTunnel = getTunnelOnSegment(beltInventory, upcomingSegment); int transferred = current.stack.getCount(); - if (nextTunnel instanceof BrassTunnelBlockEntity) { - BrassTunnelBlockEntity brassTunnel = (BrassTunnelBlockEntity) nextTunnel; + if (nextTunnel instanceof BrassTunnelBlockEntity brassTunnel) { if (brassTunnel.hasDistributionBehaviour()) { if (!brassTunnel.canTakeItems()) return true; @@ -115,7 +115,7 @@ public class BeltTunnelInteractionHandler { } public static boolean stuckAtTunnel(BeltInventory beltInventory, int offset, ItemStack stack, - Direction movementDirection) { + Direction movementDirection) { BeltBlockEntity belt = beltInventory.belt; BlockPos pos = BeltHelper.getPositionForOffset(belt, offset) .above(); @@ -125,9 +125,8 @@ public class BeltTunnelInteractionHandler { return false; BlockEntity be = belt.getLevel() .getBlockEntity(pos); - if (be == null || !(be instanceof BrassTunnelBlockEntity)) + if (be == null || !(be instanceof BrassTunnelBlockEntity tunnel)) return false; - BrassTunnelBlockEntity tunnel = (BrassTunnelBlockEntity) be; return !tunnel.canInsert(movementDirection.getOpposite(), stack); } diff --git a/src/main/java/com/simibubi/create/content/kinetics/chainConveyor/ChainConveyorPackage.java b/src/main/java/com/simibubi/create/content/kinetics/chainConveyor/ChainConveyorPackage.java index 040b2b52f2..f08c45a06d 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/chainConveyor/ChainConveyorPackage.java +++ b/src/main/java/com/simibubi/create/content/kinetics/chainConveyor/ChainConveyorPackage.java @@ -59,7 +59,7 @@ public class ChainConveyorPackage { public void setBE(ChainConveyorBlockEntity ccbe) { if (beReference == null || beReference.get() != ccbe) - beReference = new WeakReference(ccbe); + beReference = new WeakReference<>(ccbe); } } diff --git a/src/main/java/com/simibubi/create/content/kinetics/crafter/ConnectedInputHandler.java b/src/main/java/com/simibubi/create/content/kinetics/crafter/ConnectedInputHandler.java index cf02a8766d..457312ce84 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/crafter/ConnectedInputHandler.java +++ b/src/main/java/com/simibubi/create/content/kinetics/crafter/ConnectedInputHandler.java @@ -28,6 +28,7 @@ import net.minecraft.nbt.Tag; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; + import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemStackHandler; @@ -125,7 +126,7 @@ public class ConnectedInputHandler { } public static void connectControllers(Level world, MechanicalCrafterBlockEntity crafter1, - MechanicalCrafterBlockEntity crafter2) { + MechanicalCrafterBlockEntity crafter2) { crafter1.input.data.forEach(offset -> { BlockPos connectedPos = crafter1.getBlockPos() @@ -151,10 +152,9 @@ public class ConnectedInputHandler { private static void modifyAndUpdate(Level world, BlockPos pos, Consumer callback) { BlockEntity blockEntity = world.getBlockEntity(pos); - if (!(blockEntity instanceof MechanicalCrafterBlockEntity)) + if (!(blockEntity instanceof MechanicalCrafterBlockEntity crafter)) return; - MechanicalCrafterBlockEntity crafter = (MechanicalCrafterBlockEntity) blockEntity; callback.accept(crafter.input); crafter.setChanged(); crafter.connectivityChanged(); diff --git a/src/main/java/com/simibubi/create/content/kinetics/crank/HandCrankBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/crank/HandCrankBlockEntity.java index c21da8a357..7dd9927f9b 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/crank/HandCrankBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/crank/HandCrankBlockEntity.java @@ -5,17 +5,16 @@ import com.simibubi.create.AllPartialModels; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.content.kinetics.base.GeneratingKineticBlockEntity; -import dev.engine_room.flywheel.api.model.Model; -import dev.engine_room.flywheel.lib.model.Models; +import net.createmod.catnip.animation.AnimationTickHolder; import net.createmod.catnip.render.CachedBuffers; import net.createmod.catnip.render.SuperByteBuffer; -import net.createmod.catnip.animation.AnimationTickHolder; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @@ -49,9 +48,8 @@ public class HandCrankBlockEntity extends GeneratingKineticBlockEntity { @Override public float getGeneratedSpeed() { Block block = getBlockState().getBlock(); - if (!(block instanceof HandCrankBlock)) + if (!(block instanceof HandCrankBlock crank)) return 0; - HandCrankBlock crank = (HandCrankBlock) block; int speed = (inUse == 0 ? 0 : clockwise() ? -1 : 1) * crank.getRotationSpeed(); return convertToDirection(speed, getBlockState().getValue(HandCrankBlock.FACING)); } diff --git a/src/main/java/com/simibubi/create/content/kinetics/crusher/CrushingWheelControllerBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/crusher/CrushingWheelControllerBlockEntity.java index c87117142c..cb20f6d2f0 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/crusher/CrushingWheelControllerBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/crusher/CrushingWheelControllerBlockEntity.java @@ -17,8 +17,8 @@ import com.simibubi.create.foundation.sound.SoundScapes; import com.simibubi.create.foundation.sound.SoundScapes.AmbienceGroup; import com.simibubi.create.infrastructure.config.AllConfigs; -import net.createmod.catnip.nbt.NBTHelper; import net.createmod.catnip.math.VecHelper; +import net.createmod.catnip.nbt.NBTHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; @@ -39,6 +39,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; @@ -114,10 +115,10 @@ public class CrushingWheelControllerBlockEntity extends SmartBlockEntity { .getStep(); Vec3 outSpeed = new Vec3((facing.getAxis() == Axis.X ? 0.25D : 0.0D) * offset, offset == 1 ? (facing.getAxis() == Axis.Y ? 0.5D : 0.0D) : 0.0D // Increased upwards speed so upwards - // crushing wheels shoot out the item - // properly. + // crushing wheels shoot out the item + // properly. , (facing.getAxis() == Axis.Z ? 0.25D : 0.0D) * offset); // No downwards speed, so downwards crushing wheels - // drop the items as before. + // drop the items as before. Vec3 outPos = centerPos.add((facing.getAxis() == Axis.X ? .55f * offset : 0f), (facing.getAxis() == Axis.Y ? .55f * offset : 0f), (facing.getAxis() == Axis.Z ? .55f * offset : 0f)); @@ -202,32 +203,32 @@ public class CrushingWheelControllerBlockEntity extends SmartBlockEntity { double movement = Math.max(-speed / 4f, -.5f) * -offset; processingEntity.setDeltaMovement( new Vec3(facing.getAxis() == Axis.X ? movement : xMotion, facing.getAxis() == Axis.Y ? movement : 0f // Do - // not - // move - // entities - // upwards - // or - // downwards - // for - // horizontal - // crushers, + // not + // move + // entities + // upwards + // or + // downwards + // for + // horizontal + // crushers, , facing.getAxis() == Axis.Z ? movement : zMotion)); // Or they'll only get their feet crushed. if (level.isClientSide) return; - if (!(processingEntity instanceof ItemEntity)) { + if (!(processingEntity instanceof ItemEntity itemEntity)) { Vec3 entityOutPos = outPos.add(facing.getAxis() == Axis.X ? .5f * offset : 0f, facing.getAxis() == Axis.Y ? .5f * offset : 0f, facing.getAxis() == Axis.Z ? .5f * offset : 0f); int crusherDamage = AllConfigs.server().kinetics.crushingDamage.get(); if (processingEntity instanceof LivingEntity) { if ((((LivingEntity) processingEntity).getHealth() - crusherDamage <= 0) // Takes LivingEntity instances - // as exception, so it can - // move them before it would - // kill them. + // as exception, so it can + // move them before it would + // kill them. && (((LivingEntity) processingEntity).hurtTime <= 0)) { // This way it can actually output the items - // to the right spot. + // to the right spot. processingEntity.setPos(entityOutPos.x, entityOutPos.y, entityOutPos.z); } } @@ -238,7 +239,6 @@ public class CrushingWheelControllerBlockEntity extends SmartBlockEntity { return; } - ItemEntity itemEntity = (ItemEntity) processingEntity; itemEntity.setPickUpDelay(20); if (facing.getAxis() == Axis.Y) { if (processingEntity.getY() * -offset < (centerPos.y - .25f) * -offset) { @@ -301,8 +301,7 @@ public class CrushingWheelControllerBlockEntity extends SmartBlockEntity { for (int roll = 0; roll < rolls; roll++) { List rolledResults = recipe.get() .rollResults(); - for (int i = 0; i < rolledResults.size(); i++) { - ItemStack stack = rolledResults.get(i); + for (ItemStack stack : rolledResults) { ItemHelper.addToList(stack, list); } } diff --git a/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerFakePlayer.java b/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerFakePlayer.java index 94e63e9d09..761842d90b 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerFakePlayer.java +++ b/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerFakePlayer.java @@ -35,6 +35,7 @@ import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.UsernameCache; @@ -121,8 +122,7 @@ public class DeployerFakePlayer extends FakePlayer { public static void deployerCollectsDropsFromKilledEntities(LivingDropsEvent event) { DamageSource source = event.getSource(); Entity trueSource = source.getEntity(); - if (trueSource != null && trueSource instanceof DeployerFakePlayer) { - DeployerFakePlayer fakePlayer = (DeployerFakePlayer) trueSource; + if (trueSource != null && trueSource instanceof DeployerFakePlayer fakePlayer) { event.getDrops() .forEach(stack -> fakePlayer.getInventory() .placeItemBackInInventory(stack.getItem())); @@ -158,7 +158,7 @@ public class DeployerFakePlayer extends FakePlayer { CKinetics.DeployerAggroSetting setting = AllConfigs.server().kinetics.ignoreDeployerAttacks.get(); - switch(setting) { + switch (setting) { case ALL -> event.setCanceled(true); case CREEPERS -> { if (mob instanceof Creeper) @@ -216,10 +216,12 @@ public class DeployerFakePlayer extends FakePlayer { } @Override - public void send(Packet packetIn) {} + public void send(Packet packetIn) { + } @Override - public void send(Packet p_243227_, @Nullable PacketSendListener p_243273_) {} + public void send(Packet p_243227_, @Nullable PacketSendListener p_243273_) { + } } } diff --git a/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerHandler.java b/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerHandler.java index 2e1f3bb4ea..7f6a2eae67 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerHandler.java +++ b/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerHandler.java @@ -9,8 +9,6 @@ import java.util.stream.Collectors; import javax.annotation.Nullable; -import net.minecraft.world.item.MobBucketItem; - import org.apache.commons.lang3.tuple.Pair; import com.google.common.collect.Multimap; @@ -51,6 +49,7 @@ import net.minecraft.world.item.BucketItem; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import net.minecraft.world.item.MobBucketItem; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.ClipContext; @@ -69,6 +68,7 @@ import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.extensions.IForgeBaseRailBlock; import net.minecraftforge.event.entity.player.PlayerInteractEvent.LeftClickBlock; @@ -101,7 +101,7 @@ public class DeployerHandler { if (rayMode && (pos.relative(face.getOpposite(), 3) .equals(position) || pos.relative(face.getOpposite(), 1) - .equals(position))) + .equals(position))) return Blocks.BEDROCK.defaultBlockState(); return level.getBlockState(position); } @@ -113,8 +113,7 @@ public class DeployerHandler { .getBlock() == ((BlockItem) held.getItem()).getBlock()) return false; - if (held.getItem() instanceof BucketItem) { - BucketItem bucketItem = (BucketItem) held.getItem(); + if (held.getItem() instanceof BucketItem bucketItem) { Fluid fluid = bucketItem.getFluid(); if (fluid != Fluids.EMPTY && world.getFluidState(targetPos) .getType() == fluid) @@ -139,7 +138,7 @@ public class DeployerHandler { } private static void activateInner(DeployerFakePlayer player, Vec3 vec, BlockPos clickedPos, Vec3 extensionVector, - Mode mode) { + Mode mode) { Vec3 rayOrigin = vec.add(extensionVector.scale(3 / 2f + 1 / 64f)); Vec3 rayTarget = vec.add(extensionVector.scale(5 / 2f - 1 / 64f)); @@ -171,15 +170,14 @@ public class DeployerHandler { if (cancelResult == null) { if (entity.interact(player, hand) .consumesAction()) { - if (entity instanceof AbstractVillager) { - AbstractVillager villager = ((AbstractVillager) entity); + if (entity instanceof AbstractVillager villager) { if (villager.getTradingPlayer() instanceof DeployerFakePlayer) villager.setTradingPlayer(null); } success = true; } else if (entity instanceof LivingEntity && stack.interactLivingEntity(player, (LivingEntity) entity, hand) - .consumesAction()) + .consumesAction()) success = true; } if (!success && entity instanceof Player playerEntity) { @@ -412,14 +410,14 @@ public class DeployerHandler { } public static InteractionResult safeOnUse(BlockState state, Level world, BlockPos pos, Player player, - InteractionHand hand, BlockHitResult ray) { + InteractionHand hand, BlockHitResult ray) { if (state.getBlock() instanceof BeehiveBlock) return safeOnBeehiveUse(state, world, pos, player, hand); return state.use(world, player, hand, ray); } protected static InteractionResult safeOnBeehiveUse(BlockState state, Level world, BlockPos pos, Player player, - InteractionHand hand) { + InteractionHand hand) { // <> BeehiveBlock#onUse BeehiveBlock block = (BeehiveBlock) state.getBlock(); diff --git a/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerRenderer.java b/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerRenderer.java index 60b165f110..a2d8cf25a7 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerRenderer.java +++ b/src/main/java/com/simibubi/create/content/kinetics/deployer/DeployerRenderer.java @@ -21,12 +21,12 @@ import com.simibubi.create.foundation.virtualWorld.VirtualRenderWorld; import dev.engine_room.flywheel.api.visualization.VisualizationManager; import dev.engine_room.flywheel.lib.model.baked.PartialModel; import dev.engine_room.flywheel.lib.transform.TransformStack; +import net.createmod.catnip.animation.AnimationTickHolder; +import net.createmod.catnip.math.AngleHelper; +import net.createmod.catnip.math.VecHelper; +import net.createmod.catnip.nbt.NBTHelper; import net.createmod.catnip.render.CachedBuffers; import net.createmod.catnip.render.SuperByteBuffer; -import net.createmod.catnip.animation.AnimationTickHolder; -import net.createmod.catnip.nbt.NBTHelper; -import net.createmod.catnip.math.VecHelper; -import net.createmod.catnip.math.AngleHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.MultiBufferSource; @@ -50,7 +50,7 @@ public class DeployerRenderer extends SafeBlockEntityRenderer iterator = caughtEntities.iterator(); iterator.hasNext();) { + for (Iterator iterator = caughtEntities.iterator(); iterator.hasNext(); ) { Entity entity = iterator.next(); if (!entity.isAlive() || !entity.getBoundingBox() .intersects(bounds) || isPlayerCreativeFlying(entity)) { @@ -129,8 +129,7 @@ public class AirCurrent { } public static boolean isPlayerCreativeFlying(Entity entity) { - if (entity instanceof Player) { - Player player = (Player) entity; + if (entity instanceof Player player) { return player.isCreative() && player.getAbilities().flying; } return false; @@ -143,7 +142,7 @@ public class AirCurrent { FanProcessingType processingType = pair.getRight(); if (processingType == AllFanProcessingTypes.NONE) continue; - + handler.handleProcessingOnAllItems(transported -> { if (world.isClientSide) { processingType.spawnProcessingParticles(world, handler.getWorldPositionOf(transported)); @@ -251,18 +250,18 @@ public class AirCurrent { if (shapeDepth == Double.POSITIVE_INFINITY) { continue; } - return Math.min((float) (i + shapeDepth + 1/32d), max); + return Math.min((float) (i + shapeDepth + 1 / 32d), max); } return max; } private static final double[][] DEPTH_TEST_COORDINATES = { - { 0.25, 0.25 }, - { 0.25, 0.75 }, - { 0.5, 0.5 }, - { 0.75, 0.25 }, - { 0.75, 0.75 } + {0.25, 0.25}, + {0.25, 0.75}, + {0.5, 0.5}, + {0.75, 0.25}, + {0.75, 0.75} }; // Finds the maximum depth of the shape when traveling in the given direction. diff --git a/src/main/java/com/simibubi/create/content/kinetics/fan/AirFlowParticleData.java b/src/main/java/com/simibubi/create/content/kinetics/fan/AirFlowParticleData.java index 9655950b93..8c7f28024d 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/fan/AirFlowParticleData.java +++ b/src/main/java/com/simibubi/create/content/kinetics/fan/AirFlowParticleData.java @@ -14,21 +14,22 @@ import net.minecraft.core.Vec3i; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; import net.minecraft.network.FriendlyByteBuf; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public class AirFlowParticleData implements ParticleOptions, ICustomParticleDataWithSprite { - - public static final Codec CODEC = RecordCodecBuilder.create(i -> - i.group( - Codec.INT.fieldOf("x").forGetter(p -> p.posX), - Codec.INT.fieldOf("y").forGetter(p -> p.posY), - Codec.INT.fieldOf("z").forGetter(p -> p.posZ)) - .apply(i, AirFlowParticleData::new)); - public static final ParticleOptions.Deserializer DESERIALIZER = new ParticleOptions.Deserializer() { + public static final Codec CODEC = RecordCodecBuilder.create(i -> + i.group( + Codec.INT.fieldOf("x").forGetter(p -> p.posX), + Codec.INT.fieldOf("y").forGetter(p -> p.posY), + Codec.INT.fieldOf("z").forGetter(p -> p.posZ)) + .apply(i, AirFlowParticleData::new)); + + public static final ParticleOptions.Deserializer DESERIALIZER = new ParticleOptions.Deserializer<>() { public AirFlowParticleData fromCommand(ParticleType particleTypeIn, StringReader reader) - throws CommandSyntaxException { + throws CommandSyntaxException { reader.expect(' '); int x = reader.readInt(); reader.expect(' '); @@ -82,7 +83,7 @@ public class AirFlowParticleData implements ParticleOptions, ICustomParticleData public Deserializer getDeserializer() { return DESERIALIZER; } - + @Override public Codec getCodec(ParticleType type) { return CODEC; @@ -94,4 +95,4 @@ public class AirFlowParticleData implements ParticleOptions, ICustomParticleData return AirFlowParticle.Factory::new; } -} \ No newline at end of file +} diff --git a/src/main/java/com/simibubi/create/content/kinetics/fan/EncasedFanBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/fan/EncasedFanBlockEntity.java index 836b14a156..01750896d2 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/fan/EncasedFanBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/fan/EncasedFanBlockEntity.java @@ -39,7 +39,7 @@ public class EncasedFanBlockEntity extends KineticBlockEntity implements IAirCur super.addBehaviours(behaviours); registerAwardables(behaviours, AllAdvancements.ENCASED_FAN, AllAdvancements.FAN_PROCESSING); } - + @Override protected void read(CompoundTag compound, boolean clientPacket) { super.read(compound, clientPacket); @@ -89,7 +89,7 @@ public class EncasedFanBlockEntity extends KineticBlockEntity implements IAirCur super.remove(); updateChute(); } - + @Override public boolean isSourceRemoved() { return remove; @@ -108,9 +108,8 @@ public class EncasedFanBlockEntity extends KineticBlockEntity implements IAirCur .isVertical()) return; BlockEntity poweredChute = level.getBlockEntity(worldPosition.relative(direction)); - if (!(poweredChute instanceof ChuteBlockEntity)) + if (!(poweredChute instanceof ChuteBlockEntity chuteBE)) return; - ChuteBlockEntity chuteBE = (ChuteBlockEntity) poweredChute; if (direction == Direction.DOWN) chuteBE.updatePull(); else diff --git a/src/main/java/com/simibubi/create/content/kinetics/fan/NozzleBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/fan/NozzleBlockEntity.java index ff51c7679c..3e2cacabd9 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/fan/NozzleBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/fan/NozzleBlockEntity.java @@ -39,7 +39,8 @@ public class NozzleBlockEntity extends SmartBlockEntity { } @Override - public void addBehaviours(List behaviours) {} + public void addBehaviours(List behaviours) { + } @Override protected void write(CompoundTag compound, boolean clientPacket) { @@ -86,10 +87,10 @@ public class NozzleBlockEntity extends SmartBlockEntity { } } - for (Iterator iterator = pushingEntities.iterator(); iterator.hasNext();) { + for (Iterator iterator = pushingEntities.iterator(); iterator.hasNext(); ) { Entity entity = iterator.next(); Vec3 diff = entity.position() - .subtract(center); + .subtract(center); if (!(entity instanceof Player) && level.isClientSide) continue; @@ -105,7 +106,7 @@ public class NozzleBlockEntity extends SmartBlockEntity { float factor = (entity instanceof ItemEntity) ? 1 / 128f : 1 / 32f; Vec3 pushVec = diff.normalize() - .scale((range - distance) * (pushing ? 1 : -1)); + .scale((range - distance) * (pushing ? 1 : -1)); entity.setDeltaMovement(entity.getDeltaMovement() .add(pushVec.scale(factor))); entity.fallDistance = 0; @@ -123,10 +124,9 @@ public class NozzleBlockEntity extends SmartBlockEntity { private float calcRange() { BlockEntity be = level.getBlockEntity(fanPos); - if (!(be instanceof IAirCurrentSource)) + if (!(be instanceof IAirCurrentSource source)) return 0; - IAirCurrentSource source = (IAirCurrentSource) be; if (source.getAirCurrent() == null) return 0; if (source.getSpeed() == 0) @@ -147,7 +147,7 @@ public class NozzleBlockEntity extends SmartBlockEntity { for (Entity entity : level.getEntitiesOfClass(Entity.class, bb)) { Vec3 diff = entity.position() - .subtract(center); + .subtract(center); double distance = diff.length(); if (distance > range || entity.isShiftKeyDown() || AirCurrent.isPlayerCreativeFlying(entity)) @@ -163,7 +163,7 @@ public class NozzleBlockEntity extends SmartBlockEntity { pushingEntities.add(entity); } - for (Iterator iterator = pushingEntities.iterator(); iterator.hasNext();) { + for (Iterator iterator = pushingEntities.iterator(); iterator.hasNext(); ) { Entity entity = iterator.next(); if (entity.isAlive()) continue; @@ -172,7 +172,7 @@ public class NozzleBlockEntity extends SmartBlockEntity { if (!pushing && pushingEntities.size() > 256 && !level.isClientSide) { level.explode(null, center.x, center.y, center.z, 2, ExplosionInteraction.NONE); - for (Iterator iterator = pushingEntities.iterator(); iterator.hasNext();) { + for (Iterator iterator = pushingEntities.iterator(); iterator.hasNext(); ) { Entity entity = iterator.next(); entity.discard(); iterator.remove(); diff --git a/src/main/java/com/simibubi/create/content/kinetics/gauge/GaugeBlock.java b/src/main/java/com/simibubi/create/content/kinetics/gauge/GaugeBlock.java index 292c310315..a781e83818 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/gauge/GaugeBlock.java +++ b/src/main/java/com/simibubi/create/content/kinetics/gauge/GaugeBlock.java @@ -8,9 +8,9 @@ import com.simibubi.create.content.kinetics.base.IRotate; import com.simibubi.create.foundation.block.IBE; import net.createmod.catnip.data.Iterate; -import net.createmod.catnip.math.VecHelper; import net.createmod.catnip.lang.Lang; import net.createmod.catnip.levelWrappers.WrappedLevel; +import net.createmod.catnip.math.VecHelper; import net.createmod.catnip.theme.Color; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -121,9 +121,8 @@ public class GaugeBlock extends DirectionalAxisKineticBlock implements IBE REGISTER = DeferredRegister.create(AllRegistries.Keys.ARM_INTERACTION_POINT_TYPES, Create.ID); @@ -202,7 +200,7 @@ public class AllArmInteractionPointTypes { return state.getBlock() instanceof AbstractFunnelBlock && !(state.hasProperty(FunnelBlock.EXTRACTING) && state.getValue(FunnelBlock.EXTRACTING)) && !(state.hasProperty(BeltFunnelBlock.SHAPE) - && state.getValue(BeltFunnelBlock.SHAPE) == Shape.PUSHING); + && state.getValue(BeltFunnelBlock.SHAPE) == Shape.PUSHING); } @Override @@ -300,12 +298,13 @@ public class AllArmInteractionPointTypes { public static class DepositOnlyArmInteractionPoint extends ArmInteractionPoint { public DepositOnlyArmInteractionPoint(ArmInteractionPointType type, Level level, BlockPos pos, - BlockState state) { + BlockState state) { super(type, level, pos, state); } @Override - public void cycleMode() {} + public void cycleMode() { + } @Override public ItemStack extract(int slot, int amount, boolean simulate) { @@ -406,9 +405,8 @@ public class AllArmInteractionPointTypes { @Override public ItemStack extract(int slot, int amount, boolean simulate) { BlockEntity be = level.getBlockEntity(pos); - if (!(be instanceof MechanicalCrafterBlockEntity)) + if (!(be instanceof MechanicalCrafterBlockEntity crafter)) return ItemStack.EMPTY; - MechanicalCrafterBlockEntity crafter = (MechanicalCrafterBlockEntity) be; SmartInventory inventory = crafter.getInventory(); inventory.allowExtraction(); ItemStack extract = super.extract(slot, amount, simulate); @@ -500,8 +498,7 @@ public class AllArmInteractionPointTypes { ItemStack insert = inserter.insert(stack); if (!simulate && insert.getCount() != stack.getCount()) { BlockEntity blockEntity = level.getBlockEntity(pos); - if (blockEntity instanceof FunnelBlockEntity) { - FunnelBlockEntity funnelBlockEntity = (FunnelBlockEntity) blockEntity; + if (blockEntity instanceof FunnelBlockEntity funnelBlockEntity) { funnelBlockEntity.onTransfer(stack); if (funnelBlockEntity.hasFlap()) funnelBlockEntity.flap(true); @@ -666,7 +663,7 @@ public class AllArmInteractionPointTypes { @Override protected Vec3 getInteractionPositionVector() { return Vec3.atLowerCornerOf(pos) - .add(.5f, 1, .5f); + .add(.5f, 1, .5f); } } } diff --git a/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmBlockEntity.java index 162ae7062d..e71c9c4289 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmBlockEntity.java @@ -115,7 +115,7 @@ public class ArmBlockEntity extends KineticBlockEntity implements TransformableB public void addBehaviours(List behaviours) { super.addBehaviours(behaviours); - selectionMode = new ScrollOptionBehaviour(SelectionMode.class, + selectionMode = new ScrollOptionBehaviour<>(SelectionMode.class, CreateLang.translateDirect("logistics.when_multiple_outputs_available"), this, new SelectionModeValueBox()); behaviours.add(selectionMode); @@ -262,7 +262,8 @@ public class ArmBlockEntity extends KineticBlockEntity implements TransformableB if (scanRange > inputs.size()) scanRange = inputs.size(); - InteractionPoints: for (int i = startIndex; i < scanRange; i++) { + InteractionPoints: + for (int i = startIndex; i < scanRange; i++) { ArmInteractionPoint armInteractionPoint = inputs.get(i); if (!armInteractionPoint.isValid()) continue; diff --git a/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmInteractionPointHandler.java b/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmInteractionPointHandler.java index 19ba5b4da9..36850a4f9c 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmInteractionPointHandler.java +++ b/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmInteractionPointHandler.java @@ -94,7 +94,7 @@ public class ArmInteractionPointHandler { return; int removed = 0; - for (Iterator iterator = currentSelection.iterator(); iterator.hasNext();) { + for (Iterator iterator = currentSelection.iterator(); iterator.hasNext(); ) { ArmInteractionPoint point = iterator.next(); if (point.getPos() .closerThan(pos, ArmBlockEntity.getRange())) @@ -157,11 +157,10 @@ public class ArmInteractionPointHandler { } HitResult objectMouseOver = Minecraft.getInstance().hitResult; - if (!(objectMouseOver instanceof BlockHitResult)) { + if (!(objectMouseOver instanceof BlockHitResult result)) { return; } - BlockHitResult result = (BlockHitResult) objectMouseOver; BlockPos pos = result.getBlockPos(); BlockEntity be = Minecraft.getInstance().level.getBlockEntity(pos); @@ -185,7 +184,7 @@ public class ArmInteractionPointHandler { } private static void drawOutlines(Collection selection) { - for (Iterator iterator = selection.iterator(); iterator.hasNext();) { + for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) { ArmInteractionPoint point = iterator.next(); if (!point.isValid()) { @@ -203,7 +202,7 @@ public class ArmInteractionPointHandler { int color = point.getMode() .getColor(); Outliner.getInstance().showAABB(point, shape.bounds() - .move(pos)) + .move(pos)) .colored(color) .lineWidth(1 / 16f); } diff --git a/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmPlacementPacket.java b/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmPlacementPacket.java index 8e33af2ec8..baf8b6ab76 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmPlacementPacket.java +++ b/src/main/java/com/simibubi/create/content/kinetics/mechanicalArm/ArmPlacementPacket.java @@ -12,6 +12,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.network.NetworkEvent.Context; @@ -55,10 +56,9 @@ public class ArmPlacementPacket extends SimplePacketBase { if (world == null || !world.isLoaded(pos)) return; BlockEntity blockEntity = world.getBlockEntity(pos); - if (!(blockEntity instanceof ArmBlockEntity)) + if (!(blockEntity instanceof ArmBlockEntity arm)) return; - ArmBlockEntity arm = (ArmBlockEntity) blockEntity; arm.interactionPointTag = receivedTag; }); return true; diff --git a/src/main/java/com/simibubi/create/content/kinetics/millstone/MillstoneBlock.java b/src/main/java/com/simibubi/create/content/kinetics/millstone/MillstoneBlock.java index 4a1edbfbf6..99c69568f5 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/millstone/MillstoneBlock.java +++ b/src/main/java/com/simibubi/create/content/kinetics/millstone/MillstoneBlock.java @@ -25,6 +25,7 @@ import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; + import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.IItemHandler; @@ -49,7 +50,7 @@ public class MillstoneBlock extends KineticBlock implements IBE capability = millstone.getCapability(ForgeCapabilities.ITEM_HANDLER); if (!capability.isPresent()) return; diff --git a/src/main/java/com/simibubi/create/content/kinetics/saw/SawBlockEntity.java b/src/main/java/com/simibubi/create/content/kinetics/saw/SawBlockEntity.java index bd1b7628c9..d7dadbc30c 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/saw/SawBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/kinetics/saw/SawBlockEntity.java @@ -62,6 +62,7 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; @@ -355,15 +356,14 @@ public class SawBlockEntity extends BlockBreakingKineticBlockEntity { inventory.clear(); for (int roll = 0; roll < rolls; roll++) { - List results = new LinkedList(); + List results = new LinkedList<>(); if (recipe instanceof CuttingRecipe) results = ((CuttingRecipe) recipe).rollResults(); else if (recipe instanceof StonecutterRecipe || recipe.getType() == woodcuttingRecipeType.get()) results.add(recipe.getResultItem(level.registryAccess()) .copy()); - for (int i = 0; i < results.size(); i++) { - ItemStack stack = results.get(i); + for (ItemStack stack : results) { ItemHelper.addToList(stack, list); } } diff --git a/src/main/java/com/simibubi/create/content/kinetics/simpleRelays/encased/EncasedCogRenderer.java b/src/main/java/com/simibubi/create/content/kinetics/simpleRelays/encased/EncasedCogRenderer.java index 8a0461aac1..a8549c2c37 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/simpleRelays/encased/EncasedCogRenderer.java +++ b/src/main/java/com/simibubi/create/content/kinetics/simpleRelays/encased/EncasedCogRenderer.java @@ -8,9 +8,9 @@ import com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockEn import com.simibubi.create.content.kinetics.simpleRelays.SimpleKineticBlockEntity; import dev.engine_room.flywheel.api.visualization.VisualizationManager; +import net.createmod.catnip.data.Iterate; import net.createmod.catnip.render.CachedBuffers; import net.createmod.catnip.render.SuperByteBuffer; -import net.createmod.catnip.data.Iterate; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; @@ -40,16 +40,15 @@ public class EncasedCogRenderer extends KineticBlockEntityRenderer DESERIALIZER = - new ParticleOptions.Deserializer() { + new ParticleOptions.Deserializer<>() { public SteamJetParticleData fromCommand(ParticleType particleTypeIn, - StringReader reader) throws CommandSyntaxException { + StringReader reader) throws CommandSyntaxException { reader.expect(' '); float speed = reader.readFloat(); return new SteamJetParticleData(speed); } public SteamJetParticleData fromNetwork(ParticleType particleTypeIn, - FriendlyByteBuf buffer) { + FriendlyByteBuf buffer) { return new SteamJetParticleData(buffer.readFloat()); } }; @@ -79,4 +80,4 @@ public class SteamJetParticleData implements ParticleOptions, ICustomParticleDat return SteamJetParticle.Factory::new; } -} \ No newline at end of file +} diff --git a/src/main/java/com/simibubi/create/content/kinetics/transmission/GearshiftBlock.java b/src/main/java/com/simibubi/create/content/kinetics/transmission/GearshiftBlock.java index 5e0e154ecd..307772c282 100644 --- a/src/main/java/com/simibubi/create/content/kinetics/transmission/GearshiftBlock.java +++ b/src/main/java/com/simibubi/create/content/kinetics/transmission/GearshiftBlock.java @@ -38,12 +38,12 @@ public class GearshiftBlock extends AbstractEncasedShaftBlock implements IBE 1/4f) - speed *= Mth.clamp((1/2f - offset.length()) * 2, 0, 1); + if (offset.length() > 1 / 4f) + speed *= Mth.clamp((1 / 2f - offset.length()) * 2, 0, 1); mc.player.setYRot(mc.player.yRotO - speed * AnimationTickHolder.getPartialTicks()); mc.player.yBodyRot = mc.player.getYRot(); diff --git a/src/main/java/com/simibubi/create/content/legacy/ChromaticCompoundItem.java b/src/main/java/com/simibubi/create/content/legacy/ChromaticCompoundItem.java index 6a1f5f49dd..6a372ae9a0 100644 --- a/src/main/java/com/simibubi/create/content/legacy/ChromaticCompoundItem.java +++ b/src/main/java/com/simibubi/create/content/legacy/ChromaticCompoundItem.java @@ -135,11 +135,9 @@ public class ChromaticCompoundItem extends Item { if (state.getBlock() == Blocks.BEACON) { BlockEntity be = world.getBlockEntity(testPos); - if (!(be instanceof BeaconBlockEntity)) + if (!(be instanceof BeaconBlockEntity bte)) break; - BeaconBlockEntity bte = (BeaconBlockEntity) be; - if (!bte.beamSections.isEmpty()) isOverBeacon = true; @@ -180,10 +178,9 @@ public class ChromaticCompoundItem extends Item { behaviour.handleProcessingOnAllItems(ts -> { ItemStack heldStack = ts.stack; - if (!(heldStack.getItem() instanceof BlockItem)) + if (!(heldStack.getItem() instanceof BlockItem blockItem)) return TransportedResult.doNothing(); - BlockItem blockItem = (BlockItem) heldStack.getItem(); if (blockItem.getBlock() == null) return TransportedResult.doNothing(); @@ -207,7 +204,7 @@ public class ChromaticCompoundItem extends Item { } public boolean checkLight(ItemStack stack, ItemEntity entity, Level world, CompoundTag itemData, Vec3 positionVec, - BlockPos randomOffset, BlockState state) { + BlockPos randomOffset, BlockState state) { if (state.getLightEmission(world, randomOffset) == 0) return false; if (state.getDestroySpeed(world, randomOffset) == -1) diff --git a/src/main/java/com/simibubi/create/content/logistics/box/PackageEntity.java b/src/main/java/com/simibubi/create/content/logistics/box/PackageEntity.java index 46e33df1a7..e4701772f5 100644 --- a/src/main/java/com/simibubi/create/content/logistics/box/PackageEntity.java +++ b/src/main/java/com/simibubi/create/content/logistics/box/PackageEntity.java @@ -219,9 +219,8 @@ public class PackageEntity extends LivingEntity implements IEntityAdditionalSpaw } public static boolean centerPackage(Entity entity, Vec3 target) { - if (!(entity instanceof PackageEntity)) + if (!(entity instanceof PackageEntity packageEntity)) return true; - PackageEntity packageEntity = (PackageEntity) entity; return packageEntity.decreaseInsertionTimer(target); } @@ -278,7 +277,7 @@ public class PackageEntity extends LivingEntity implements IEntityAdditionalSpaw boolean isOtherPackage = entityIn instanceof PackageEntity; if (!isOtherPackage && tossedBy.get() != null) - tossedBy = new WeakReference(null); // no nudging + tossedBy = new WeakReference<>(null); // no nudging if (isOtherPackage) { if (entityIn.getBoundingBox().minY < this.getBoundingBox().maxY) diff --git a/src/main/java/com/simibubi/create/content/logistics/box/PackageItem.java b/src/main/java/com/simibubi/create/content/logistics/box/PackageItem.java index c217a7ed8c..462aebbfe7 100644 --- a/src/main/java/com/simibubi/create/content/logistics/box/PackageItem.java +++ b/src/main/java/com/simibubi/create/content/logistics/box/PackageItem.java @@ -41,6 +41,7 @@ import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.ItemStackHandler; @@ -107,7 +108,7 @@ public class PackageItem extends Item { } public static void setOrder(ItemStack box, int orderId, int linkIndex, boolean isFinalLink, int fragmentIndex, - boolean isFinal, @Nullable PackageOrder orderContext) { + boolean isFinal, @Nullable PackageOrder orderContext) { CompoundTag tag = new CompoundTag(); tag.putInt("OrderId", orderId); tag.putInt("LinkIndex", linkIndex); @@ -163,7 +164,7 @@ public class PackageItem extends Item { public static String getAddress(ItemStack box) { String boxAddress = !box.hasTag() ? "" : box.getTag() - .getString("Address"); + .getString("Address"); return boxAddress; } @@ -195,15 +196,15 @@ public class PackageItem extends Item { @Override public void appendHoverText(ItemStack pStack, Level pLevel, List pTooltipComponents, - TooltipFlag pIsAdvanced) { + TooltipFlag pIsAdvanced) { super.appendHoverText(pStack, pLevel, pTooltipComponents, pIsAdvanced); CompoundTag compoundnbt = pStack.getOrCreateTag(); if (compoundnbt.contains("Address", Tag.TAG_STRING) && !compoundnbt.getString("Address") .isBlank()) { - pTooltipComponents.add(Component.literal("\u2192 " + compoundnbt.getString("Address")) - .withStyle(ChatFormatting.GOLD)); - } + pTooltipComponents.add(Component.literal("\u2192 " + compoundnbt.getString("Address")) + .withStyle(ChatFormatting.GOLD)); + } /* * Debug Fragmentation Data if (compoundnbt.contains("Fragment")) { CompoundTag @@ -274,9 +275,9 @@ public class PackageItem extends Item { if (itemstack.getItem() instanceof SpawnEggItem sei && worldIn instanceof ServerLevel sl) { EntityType entitytype = sei.getType(itemstack.getTag()); Entity entity = entitytype.spawn(sl, itemstack, null, BlockPos.containing(playerIn.position() - .add(playerIn.getLookAngle() - .multiply(1, 0, 1) - .normalize())), + .add(playerIn.getLookAngle() + .multiply(1, 0, 1) + .normalize())), MobSpawnType.SPAWN_EGG, false, false); if (entity != null) itemstack.shrink(1); @@ -322,7 +323,7 @@ public class PackageItem extends Item { .getAxis() .isHorizontal()) point = point.add(Vec3.atLowerCornerOf(context.getClickedFace() - .getNormal()) + .getNormal()) .scale(r)); AABB scanBB = new AABB(point, point).inflate(r, 0, r) @@ -379,7 +380,7 @@ public class PackageItem extends Item { PackageEntity packageEntity = new PackageEntity(world, vec.x, vec.y, vec.z); packageEntity.setBox(copy); packageEntity.setDeltaMovement(motion); - packageEntity.tossedBy = new WeakReference(player); + packageEntity.tossedBy = new WeakReference<>(player); world.addFreshEntity(packageEntity); } diff --git a/src/main/java/com/simibubi/create/content/logistics/chute/ChuteBlockEntity.java b/src/main/java/com/simibubi/create/content/logistics/chute/ChuteBlockEntity.java index ccec04df05..ec02d51911 100644 --- a/src/main/java/com/simibubi/create/content/logistics/chute/ChuteBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/logistics/chute/ChuteBlockEntity.java @@ -632,8 +632,7 @@ public class ChuteBlockEntity extends SmartBlockEntity implements IHaveGoggleInf if (AllBlocks.ENCASED_FAN.has(blockStateAbove) && blockStateAbove.getValue(EncasedFanBlock.FACING) == Direction.DOWN) { BlockEntity be = level.getBlockEntity(worldPosition.above()); - if (be instanceof EncasedFanBlockEntity && !be.isRemoved()) { - EncasedFanBlockEntity fan = (EncasedFanBlockEntity) be; + if (be instanceof EncasedFanBlockEntity fan && !be.isRemoved()) { return fan.getSpeed(); } } @@ -655,8 +654,7 @@ public class ChuteBlockEntity extends SmartBlockEntity implements IHaveGoggleInf if (AllBlocks.ENCASED_FAN.has(blockStateBelow) && blockStateBelow.getValue(EncasedFanBlock.FACING) == Direction.UP) { BlockEntity be = level.getBlockEntity(worldPosition.below()); - if (be instanceof EncasedFanBlockEntity && !be.isRemoved()) { - EncasedFanBlockEntity fan = (EncasedFanBlockEntity) be; + if (be instanceof EncasedFanBlockEntity fan && !be.isRemoved()) { return fan.getSpeed(); } } diff --git a/src/main/java/com/simibubi/create/content/logistics/chute/ChuteItem.java b/src/main/java/com/simibubi/create/content/logistics/chute/ChuteItem.java index 9e3aa1b1e4..5eb7ded5c4 100644 --- a/src/main/java/com/simibubi/create/content/logistics/chute/ChuteItem.java +++ b/src/main/java/com/simibubi/create/content/logistics/chute/ChuteItem.java @@ -38,9 +38,8 @@ public class ChuteItem extends BlockItem { if (blockState.canBeReplaced()) context = BlockPlaceContext.at(context, correctPos, face); else { - if (!(blockState.getBlock() instanceof ChuteBlock) || world.isClientSide) + if (!(blockState.getBlock() instanceof ChuteBlock block) || world.isClientSide) return InteractionResult.FAIL; - AbstractChuteBlock block = (AbstractChuteBlock) blockState.getBlock(); if (block.getFacing(blockState) == Direction.DOWN) { world.setBlockAndUpdate(correctPos, ProperWaterloggedBlock.withWater(world, diff --git a/src/main/java/com/simibubi/create/content/logistics/depot/EjectorTargetHandler.java b/src/main/java/com/simibubi/create/content/logistics/depot/EjectorTargetHandler.java index 985bb6b4d4..61596eca2c 100644 --- a/src/main/java/com/simibubi/create/content/logistics/depot/EjectorTargetHandler.java +++ b/src/main/java/com/simibubi/create/content/logistics/depot/EjectorTargetHandler.java @@ -177,9 +177,8 @@ public class EjectorTargetHandler { return; HitResult objectMouseOver = mc.hitResult; - if (!(objectMouseOver instanceof BlockHitResult)) + if (!(objectMouseOver instanceof BlockHitResult blockRayTraceResult)) return; - BlockHitResult blockRayTraceResult = (BlockHitResult) objectMouseOver; if (blockRayTraceResult.getType() == Type.MISS) return; @@ -228,9 +227,8 @@ public class EjectorTargetHandler { if (!AllItems.WRENCH.isIn(heldItem)) return; HitResult objectMouseOver = Minecraft.getInstance().hitResult; - if (!(objectMouseOver instanceof BlockHitResult)) + if (!(objectMouseOver instanceof BlockHitResult result)) return; - BlockHitResult result = (BlockHitResult) objectMouseOver; BlockPos pos = result.getBlockPos(); BlockEntity be = Minecraft.getInstance().level.getBlockEntity(pos); diff --git a/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelBehaviour.java b/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelBehaviour.java index ca3be4db40..88a6d32bbe 100644 --- a/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelBehaviour.java +++ b/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelBehaviour.java @@ -71,6 +71,7 @@ import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.DistExecutor; @@ -147,7 +148,7 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro if (cached instanceof FactoryPanelBehaviour fbe && !fbe.blockEntity.isRemoved()) return fbe; FactoryPanelBehaviour result = at(world, connection.from); - connection.cachedSource = new WeakReference(result); + connection.cachedSource = new WeakReference<>(result); return result; } @@ -169,7 +170,7 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro if (cached instanceof FactoryPanelSupportBehaviour fpsb && !fpsb.blockEntity.isRemoved()) return fpsb; FactoryPanelSupportBehaviour result = linkAt(world, connection.from); - connection.cachedSource = new WeakReference(result); + connection.cachedSource = new WeakReference<>(result); return result; } @@ -268,7 +269,7 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro player.level() .playSound(null, newPos.pos(), SoundEvents.COPPER_BREAK, SoundSource.BLOCKS, 1.0f, 1.0f); } - + private void moveToSlot(PanelSlot slot) { this.slot = slot; if (this.getSlotPositioning() instanceof FactoryPanelSlotPositioning fpsp) @@ -545,7 +546,7 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro } boolean isClientSide = player.level().isClientSide; - + // Wrench cycles through arrow bending if (targeting.size() + targetedByLinks.size() > 0 && AllItemTags.WRENCH.matches(player.getItemInHand(hand))) { int sharedMode = -1; @@ -599,12 +600,12 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro NetworkHooks.openScreen(sp, this, buf -> getPanelPosition().send(buf)); return; } - + // Use regular filter interaction for setting the item super.onShortInteract(player, hand, side, hitResult); return; } - + // Bind logistics items to this panels' frequency if (heldItem.getItem() instanceof LogisticallyLinkedBlockItem) { if (!isClientSide) @@ -736,11 +737,11 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro return promises == null ? 0 : promises.getTotalPromisedAndRemoveExpired(item, getPromiseExpiryTimeInTicks()); } - + public void resetTimer() { timer = REQUEST_INTERVAL; } - + public void resetTimerSlightly() { timer = REQUEST_INTERVAL / 2; } @@ -893,7 +894,7 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro return new ValueSettingsBoard(CreateLang.translate("factory_panel.target_amount") .component(), maxAmount, 10, List.of(CreateLang.translate("schedule.condition.threshold.items") - .component(), + .component(), CreateLang.translate("schedule.condition.threshold.stacks") .component()), new ValueSettingsFormatter(this::formatValue)); @@ -955,7 +956,7 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro @Override public MutableComponent getCountLabelForValueBox() { if (filter.isEmpty()) - return Component.empty(); + return Component.empty(); if (waitingForNetwork) { return Component.literal("?"); } @@ -999,10 +1000,10 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro public static BehaviourType getTypeForSlot(PanelSlot slot) { return switch (slot) { - case BOTTOM_LEFT -> BOTTOM_LEFT; - case TOP_LEFT -> TOP_LEFT; - case TOP_RIGHT -> TOP_RIGHT; - case BOTTOM_RIGHT -> BOTTOM_RIGHT; + case BOTTOM_LEFT -> BOTTOM_LEFT; + case TOP_LEFT -> TOP_LEFT; + case TOP_RIGHT -> TOP_RIGHT; + case BOTTOM_RIGHT -> BOTTOM_RIGHT; }; } @@ -1037,7 +1038,7 @@ public class FactoryPanelBehaviour extends FilteringBehaviour implements MenuPro public boolean writeToClipboard(CompoundTag tag, Direction side) { return false; } - + private void tickOutline() { DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> LogisticallyLinkedClientHandler.tickPanel(this)); } diff --git a/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelConnection.java b/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelConnection.java index faf48616c9..d520936b38 100644 --- a/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelConnection.java +++ b/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelConnection.java @@ -34,7 +34,7 @@ public class FactoryPanelConnection { success = true; arrowBendMode = -1; arrowBendModeCurrentPathUses = 0; - cachedSource = new WeakReference(null); + cachedSource = new WeakReference<>(null); } public static FactoryPanelConnection read(CompoundTag nbt) { @@ -67,7 +67,8 @@ public class FactoryPanelConnection { final float yRot = Mth.RAD_TO_DEG * FactoryPanelBlock.getYRot(state); // When mode is not locked, find one that doesnt intersect with other gauges - ModeFinder: for (int actualMode = 0; actualMode <= 4; actualMode++) { + ModeFinder: + for (int actualMode = 0; actualMode <= 4; actualMode++) { path.clear(); if (!findSuitable && actualMode != arrowBendMode) continue; @@ -107,7 +108,7 @@ public class FactoryPanelConnection { continue; if (currentDirection == null || toTravel.relative(d) .distManhattan(BlockPos.ZERO) < toTravel.relative(currentDirection) - .distManhattan(BlockPos.ZERO)) + .distManhattan(BlockPos.ZERO)) currentDirection = d; } @@ -132,10 +133,10 @@ public class FactoryPanelConnection { continue ModeFinder; } } - + break; } - + return path; } diff --git a/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelSupportBehaviour.java b/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelSupportBehaviour.java index 71eed11bd2..40705fcd3d 100644 --- a/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelSupportBehaviour.java +++ b/src/main/java/com/simibubi/create/content/logistics/factoryBoard/FactoryPanelSupportBehaviour.java @@ -27,7 +27,7 @@ public class FactoryPanelSupportBehaviour extends BlockEntityBehaviour { private Runnable onNotify; public FactoryPanelSupportBehaviour(SmartBlockEntity be, Supplier isOutput, Supplier outputPower, - Runnable onNotify) { + Runnable onNotify) { super(be); this.isOutput = isOutput; this.outputPower = outputPower; @@ -49,8 +49,7 @@ public class FactoryPanelSupportBehaviour extends BlockEntityBehaviour { @Override public void destroy() { - for (Iterator iterator = linkedPanels.iterator(); iterator.hasNext();) { - FactoryPanelPosition panelPos = iterator.next(); + for (FactoryPanelPosition panelPos : linkedPanels) { if (!getWorld().isLoaded(panelPos.pos())) continue; FactoryPanelBehaviour behaviour = FactoryPanelBehaviour.at(getWorld(), panelPos); @@ -63,7 +62,7 @@ public class FactoryPanelSupportBehaviour extends BlockEntityBehaviour { public void notifyPanels() { if (getWorld().isClientSide()) return; - for (Iterator iterator = linkedPanels.iterator(); iterator.hasNext();) { + for (Iterator iterator = linkedPanels.iterator(); iterator.hasNext(); ) { FactoryPanelPosition panelPos = iterator.next(); if (!getWorld().isLoaded(panelPos.pos())) continue; @@ -79,7 +78,7 @@ public class FactoryPanelSupportBehaviour extends BlockEntityBehaviour { @Nullable public Boolean shouldBePoweredTristate() { - for (Iterator iterator = linkedPanels.iterator(); iterator.hasNext();) { + for (Iterator iterator = linkedPanels.iterator(); iterator.hasNext(); ) { FactoryPanelPosition panelPos = iterator.next(); if (!getWorld().isLoaded(panelPos.pos())) return null; diff --git a/src/main/java/com/simibubi/create/content/logistics/funnel/AbstractFunnelBlock.java b/src/main/java/com/simibubi/create/content/logistics/funnel/AbstractFunnelBlock.java index 2fe7a5ce46..6d91e6b035 100644 --- a/src/main/java/com/simibubi/create/content/logistics/funnel/AbstractFunnelBlock.java +++ b/src/main/java/com/simibubi/create/content/logistics/funnel/AbstractFunnelBlock.java @@ -32,6 +32,7 @@ import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.pathfinder.PathComputationType; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.extensions.common.IClientBlockExtensions; @@ -65,7 +66,7 @@ public abstract class AbstractFunnelBlock extends Block @Override public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState, - LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) { + LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) { updateWater(pLevel, pState, pCurrentPos); return pState; } @@ -82,7 +83,7 @@ public abstract class AbstractFunnelBlock extends Block @Override public void neighborChanged(BlockState state, Level level, BlockPos pos, Block block, BlockPos fromPos, - boolean isMoving) { + boolean isMoving) { if (level.isClientSide) return; InvManipulationBehaviour behaviour = BlockEntityBehaviour.get(level, pos, InvManipulationBehaviour.TYPE); @@ -113,8 +114,7 @@ public abstract class AbstractFunnelBlock extends Block if (!simulate && insert.getCount() != toInsert.getCount()) { BlockEntity blockEntity = worldIn.getBlockEntity(pos); - if (blockEntity instanceof FunnelBlockEntity) { - FunnelBlockEntity funnelBlockEntity = (FunnelBlockEntity) blockEntity; + if (blockEntity instanceof FunnelBlockEntity funnelBlockEntity) { funnelBlockEntity.onTransfer(toInsert); if (funnelBlockEntity.hasFlap()) funnelBlockEntity.flap(true); @@ -157,6 +157,8 @@ public abstract class AbstractFunnelBlock extends Block public BlockEntityType getBlockEntityType() { return AllBlockEntityTypes.FUNNEL.get(); - }; + } + + ; } diff --git a/src/main/java/com/simibubi/create/content/logistics/packagePort/postbox/PostboxBlockEntity.java b/src/main/java/com/simibubi/create/content/logistics/packagePort/postbox/PostboxBlockEntity.java index 48443aaf83..1e91d1a753 100644 --- a/src/main/java/com/simibubi/create/content/logistics/packagePort/postbox/PostboxBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/logistics/packagePort/postbox/PostboxBlockEntity.java @@ -8,9 +8,9 @@ import com.simibubi.create.content.logistics.packagePort.PackagePortBlockEntity; import com.simibubi.create.content.trains.station.GlobalStation; import com.simibubi.create.content.trains.station.GlobalStation.GlobalPackagePort; -import net.createmod.catnip.nbt.NBTHelper; import net.createmod.catnip.animation.LerpedFloat; import net.createmod.catnip.animation.LerpedFloat.Chaser; +import net.createmod.catnip.nbt.NBTHelper; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.sounds.SoundEvents; @@ -31,7 +31,7 @@ public class PostboxBlockEntity extends PackagePortBlockEntity { public PostboxBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { super(type, pos, state); - trackedGlobalStation = new WeakReference(null); + trackedGlobalStation = new WeakReference<>(null); flag = LerpedFloat.linear() .startWithValue(0); } diff --git a/src/main/java/com/simibubi/create/content/logistics/tableCloth/ShoppingListItem.java b/src/main/java/com/simibubi/create/content/logistics/tableCloth/ShoppingListItem.java index abd9aed287..c62fd3090b 100644 --- a/src/main/java/com/simibubi/create/content/logistics/tableCloth/ShoppingListItem.java +++ b/src/main/java/com/simibubi/create/content/logistics/tableCloth/ShoppingListItem.java @@ -114,7 +114,7 @@ public class ShoppingListItem extends Item { @Override public void appendHoverText(ItemStack pStack, Level pLevel, List pTooltipComponents, - TooltipFlag pIsAdvanced) { + TooltipFlag pIsAdvanced) { ShoppingList list = getList(pStack); if (list != null) { @@ -126,7 +126,7 @@ public class ShoppingListItem extends Item { boolean cost = items == lists.getSecond(); if (cost) - pTooltipComponents.add(Component.empty()); + pTooltipComponents.add(Component.empty()); if (entries.size() == 1) { BigItemStack entry = entries.get(0); @@ -169,12 +169,12 @@ public class ShoppingListItem extends Item { @Override public InteractionResultHolder use(Level pLevel, Player pPlayer, InteractionHand pUsedHand) { if (pUsedHand == InteractionHand.OFF_HAND || pPlayer == null || !pPlayer.isShiftKeyDown()) - return new InteractionResultHolder(InteractionResult.PASS, pPlayer.getItemInHand(pUsedHand)); + return new InteractionResultHolder<>(InteractionResult.PASS, pPlayer.getItemInHand(pUsedHand)); CreateLang.translate("table_cloth.shopping_list_discarded") .sendStatus(pPlayer); pPlayer.playSound(SoundEvents.BOOK_PAGE_TURN); - return new InteractionResultHolder(InteractionResult.SUCCESS, ItemStack.EMPTY); + return new InteractionResultHolder<>(InteractionResult.SUCCESS, ItemStack.EMPTY); } @Override diff --git a/src/main/java/com/simibubi/create/content/logistics/tunnel/BrassTunnelBlock.java b/src/main/java/com/simibubi/create/content/logistics/tunnel/BrassTunnelBlock.java index 5812add243..6147caa956 100644 --- a/src/main/java/com/simibubi/create/content/logistics/tunnel/BrassTunnelBlock.java +++ b/src/main/java/com/simibubi/create/content/logistics/tunnel/BrassTunnelBlock.java @@ -28,17 +28,16 @@ public class BrassTunnelBlock extends BeltTunnelBlock { @Override public InteractionResult use(BlockState p_225533_1_, Level world, BlockPos pos, Player player, - InteractionHand p_225533_5_, BlockHitResult p_225533_6_) { + InteractionHand p_225533_5_, BlockHitResult p_225533_6_) { return onBlockEntityUse(world, pos, be -> { - if (!(be instanceof BrassTunnelBlockEntity)) + if (!(be instanceof BrassTunnelBlockEntity bte)) return InteractionResult.PASS; - BrassTunnelBlockEntity bte = (BrassTunnelBlockEntity) be; List stacksOfGroup = bte.grabAllStacksOfGroup(world.isClientSide); if (stacksOfGroup.isEmpty()) return InteractionResult.PASS; if (world.isClientSide) return InteractionResult.SUCCESS; - for (ItemStack itemStack : stacksOfGroup) + for (ItemStack itemStack : stacksOfGroup) player.getInventory().placeItemBackInInventory(itemStack.copy()); world.playSound(null, pos, SoundEvents.ITEM_PICKUP, SoundSource.PLAYERS, .2f, 1f + world.random.nextFloat()); @@ -53,7 +52,7 @@ public class BrassTunnelBlock extends BeltTunnelBlock { @Override public BlockState updateShape(BlockState state, Direction facing, BlockState facingState, LevelAccessor worldIn, - BlockPos currentPos, BlockPos facingPos) { + BlockPos currentPos, BlockPos facingPos) { return super.updateShape(state, facing, facingState, worldIn, currentPos, facingPos); } diff --git a/src/main/java/com/simibubi/create/content/logistics/vault/ItemVaultBlock.java b/src/main/java/com/simibubi/create/content/logistics/vault/ItemVaultBlock.java index d874732a1a..9f84f30b9a 100644 --- a/src/main/java/com/simibubi/create/content/logistics/vault/ItemVaultBlock.java +++ b/src/main/java/com/simibubi/create/content/logistics/vault/ItemVaultBlock.java @@ -31,7 +31,7 @@ import net.minecraft.world.level.block.state.StateDefinition.Builder; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.block.state.properties.Property; -import net.minecraftforge.common.capabilities.ForgeCapabilities; + import net.minecraftforge.common.util.ForgeSoundType; public class ItemVaultBlock extends Block implements IWrenchable, IBE { @@ -84,8 +84,7 @@ public class ItemVaultBlock extends Block implements IWrenchable, IBE, IWrencha protected void createBlockStateDefinition(Builder p_206840_1_) { super.createBlockStateDefinition(p_206840_1_.add(FACING)); } - + public static boolean isBasin(LevelReader world, BlockPos pos) { return world.getBlockEntity(pos) instanceof BasinBlockEntity; } @@ -84,7 +85,7 @@ public class BasinBlock extends Block implements IBE, IWrencha @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, - BlockHitResult hit) { + BlockHitResult hit) { ItemStack heldItem = player.getItemInHand(handIn); return onBlockEntityUse(worldIn, pos, be -> { @@ -100,9 +101,9 @@ public class BasinBlock extends Block implements IBE, IWrencha if (heldItem.getItem() .equals(Items.SPONGE) && !be.getCapability(ForgeCapabilities.FLUID_HANDLER) - .map(iFluidHandler -> iFluidHandler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.EXECUTE)) - .orElse(FluidStack.EMPTY) - .isEmpty()) { + .map(iFluidHandler -> iFluidHandler.drain(Integer.MAX_VALUE, IFluidHandler.FluidAction.EXECUTE)) + .orElse(FluidStack.EMPTY) + .isEmpty()) { return InteractionResult.SUCCESS; } return InteractionResult.PASS; @@ -133,11 +134,10 @@ public class BasinBlock extends Block implements IBE, IWrencha if (!worldIn.getBlockState(entityIn.blockPosition()) .is(this)) return; - if (!(entityIn instanceof ItemEntity)) + if (!(entityIn instanceof ItemEntity itemEntity)) return; if (!entityIn.isAlive()) return; - ItemEntity itemEntity = (ItemEntity) entityIn; withBlockEntityDo(worldIn, entityIn.blockPosition(), be -> { ItemStack insertItem = ItemHandlerHelper.insertItem(be.inputInventory, itemEntity.getItem() .copy(), false); @@ -206,8 +206,7 @@ public class BasinBlock extends Block implements IBE, IWrencha return false; } else { BlockEntity blockEntity = world.getBlockEntity(output); - if (blockEntity instanceof BeltBlockEntity) { - BeltBlockEntity belt = (BeltBlockEntity) blockEntity; + if (blockEntity instanceof BeltBlockEntity belt) { return belt.getSpeed() == 0 || belt.getMovementFacing() != direction.getOpposite(); } } diff --git a/src/main/java/com/simibubi/create/content/processing/basin/BasinBlockEntity.java b/src/main/java/com/simibubi/create/content/processing/basin/BasinBlockEntity.java index 9ad388123d..b57e9ea75b 100644 --- a/src/main/java/com/simibubi/create/content/processing/basin/BasinBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/processing/basin/BasinBlockEntity.java @@ -256,12 +256,11 @@ public class BasinBlockEntity extends SmartBlockEntity implements IHaveGoggleInf } BlockEntity blockEntity = level.getBlockEntity(worldPosition.above(2)); - if (!(blockEntity instanceof MechanicalMixerBlockEntity)) { + if (!(blockEntity instanceof MechanicalMixerBlockEntity mixer)) { setAreFluidsMoving(false); return; } - MechanicalMixerBlockEntity mixer = (MechanicalMixerBlockEntity) blockEntity; setAreFluidsMoving(mixer.running && mixer.runningTicks <= 20); } diff --git a/src/main/java/com/simibubi/create/content/processing/basin/BasinRecipe.java b/src/main/java/com/simibubi/create/content/processing/basin/BasinRecipe.java index 765760fa4f..5dc29d45cc 100644 --- a/src/main/java/com/simibubi/create/content/processing/basin/BasinRecipe.java +++ b/src/main/java/com/simibubi/create/content/processing/basin/BasinRecipe.java @@ -27,6 +27,7 @@ import net.minecraft.world.item.crafting.CraftingRecipe; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.Level; + import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; @@ -41,12 +42,11 @@ public class BasinRecipe extends ProcessingRecipe { boolean filterTest = filter.test(recipe.getResultItem(basin.getLevel() .registryAccess())); - if (recipe instanceof BasinRecipe) { - BasinRecipe basinRecipe = (BasinRecipe) recipe; + if (recipe instanceof BasinRecipe basinRecipe) { if (basinRecipe.getRollableResults() .isEmpty() && !basinRecipe.getFluidResults() - .isEmpty()) + .isEmpty()) filterTest = filter.test(basinRecipe.getFluidResults() .get(0)); } @@ -93,9 +93,8 @@ public class BasinRecipe extends ProcessingRecipe { int[] extractedItemsFromSlot = new int[availableItems.getSlots()]; int[] extractedFluidsFromTank = new int[availableFluids.getTanks()]; - Ingredients: for (int i = 0; i < ingredients.size(); i++) { - Ingredient ingredient = ingredients.get(i); - + Ingredients: + for (Ingredient ingredient : ingredients) { for (int slot = 0; slot < availableItems.getSlots(); slot++) { if (simulate && availableItems.getStackInSlot(slot) .getCount() <= extractedItemsFromSlot[slot]) @@ -114,8 +113,8 @@ public class BasinRecipe extends ProcessingRecipe { } boolean fluidsAffected = false; - FluidIngredients: for (int i = 0; i < fluidIngredients.size(); i++) { - FluidIngredient fluidIngredient = fluidIngredients.get(i); + FluidIngredients: + for (FluidIngredient fluidIngredient : fluidIngredients) { int amountRequired = fluidIngredient.getRequiredAmount(); for (int tank = 0; tank < availableFluids.getTanks(); tank++) { diff --git a/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerBlock.java b/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerBlock.java index 5460ae4c3e..f04f03d9bb 100644 --- a/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerBlock.java +++ b/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerBlock.java @@ -51,6 +51,7 @@ import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.util.FakePlayer; @@ -77,9 +78,8 @@ public class BlazeBurnerBlock extends HorizontalDirectionalBlock implements IBE< if (world.isClientSide) return; BlockEntity blockEntity = world.getBlockEntity(pos.above()); - if (!(blockEntity instanceof BasinBlockEntity)) + if (!(blockEntity instanceof BasinBlockEntity basin)) return; - BasinBlockEntity basin = (BasinBlockEntity) blockEntity; basin.notifyChangeOfContents(); } @@ -103,7 +103,7 @@ public class BlazeBurnerBlock extends HorizontalDirectionalBlock implements IBE< @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult blockRayTraceResult) { + BlockHitResult blockRayTraceResult) { ItemStack heldItem = player.getItemInHand(hand); HeatLevel heat = state.getValue(HEAT_LEVEL); @@ -165,14 +165,13 @@ public class BlazeBurnerBlock extends HorizontalDirectionalBlock implements IBE< } public static InteractionResultHolder tryInsert(BlockState state, Level world, BlockPos pos, - ItemStack stack, boolean doNotConsume, boolean forceOverflow, boolean simulate) { + ItemStack stack, boolean doNotConsume, boolean forceOverflow, boolean simulate) { if (!state.hasBlockEntity()) return InteractionResultHolder.fail(ItemStack.EMPTY); BlockEntity be = world.getBlockEntity(pos); - if (!(be instanceof BlazeBurnerBlockEntity)) + if (!(be instanceof BlazeBurnerBlockEntity burnerBE)) return InteractionResultHolder.fail(ItemStack.EMPTY); - BlazeBurnerBlockEntity burnerBE = (BlazeBurnerBlockEntity) be; if (burnerBE.isCreativeFuel(stack)) { if (!simulate) @@ -213,7 +212,7 @@ public class BlazeBurnerBlock extends HorizontalDirectionalBlock implements IBE< @Override public VoxelShape getCollisionShape(BlockState p_220071_1_, BlockGetter p_220071_2_, BlockPos p_220071_3_, - CollisionContext p_220071_4_) { + CollisionContext p_220071_4_) { if (p_220071_4_ == CollisionContext.empty()) return AllShapes.HEATER_BLOCK_SPECIAL_COLLISION_SHAPE; return getShape(p_220071_1_, p_220071_2_, p_220071_3_, p_220071_4_); @@ -255,9 +254,9 @@ public class BlazeBurnerBlock extends HorizontalDirectionalBlock implements IBE< public static int getLight(BlockState state) { HeatLevel level = state.getValue(HEAT_LEVEL); return switch (level) { - case NONE -> 0; - case SMOULDERING -> 8; - default -> 15; + case NONE -> 0; + case SMOULDERING -> 8; + default -> 15; }; } @@ -279,7 +278,8 @@ public class BlazeBurnerBlock extends HorizontalDirectionalBlock implements IBE< } public enum HeatLevel implements StringRepresentable { - NONE, SMOULDERING, FADING, KINDLED, SEETHING,; + NONE, SMOULDERING, FADING, KINDLED, SEETHING, + ; public static HeatLevel byIndex(int index) { return values()[index]; diff --git a/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerHandler.java b/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerHandler.java index d491f20483..ad57746932 100644 --- a/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerHandler.java +++ b/src/main/java/com/simibubi/create/content/processing/burner/BlazeBurnerHandler.java @@ -22,6 +22,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.event.entity.ProjectileImpactEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @@ -47,7 +48,7 @@ public class BlazeBurnerHandler { BlockEntity blockEntity = projectile.level() .getBlockEntity(BlockPos.containing(event.getRayTraceResult() .getLocation())); - if (!(blockEntity instanceof BlazeBurnerBlockEntity)) { + if (!(blockEntity instanceof BlazeBurnerBlockEntity heater)) { return; } @@ -59,7 +60,6 @@ public class BlazeBurnerHandler { if (world.isClientSide) return; - BlazeBurnerBlockEntity heater = (BlazeBurnerBlockEntity) blockEntity; if (!heater.isCreative()) { if (heater.activeFuel != FuelType.SPECIAL) { heater.activeFuel = FuelType.NORMAL; @@ -77,9 +77,8 @@ public class BlazeBurnerHandler { Projectile projectile = event.getProjectile(); if (projectile.level().isClientSide) return; - if (!(projectile instanceof ThrownPotion)) + if (!(projectile instanceof ThrownPotion entity)) return; - ThrownPotion entity = (ThrownPotion) projectile; if (event.getRayTraceResult() .getType() != HitResult.Type.BLOCK) diff --git a/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedAssemblyRecipe.java b/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedAssemblyRecipe.java index e87268bdf9..dc1a5a6eeb 100644 --- a/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedAssemblyRecipe.java +++ b/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedAssemblyRecipe.java @@ -242,10 +242,9 @@ public class SequencedAssemblyRecipe implements Recipe { if (!optionalRecipe.isPresent()) return; Recipe recipe = optionalRecipe.get(); - if (!(recipe instanceof SequencedAssemblyRecipe)) + if (!(recipe instanceof SequencedAssemblyRecipe sequencedAssemblyRecipe)) return; - SequencedAssemblyRecipe sequencedAssemblyRecipe = (SequencedAssemblyRecipe) recipe; int length = sequencedAssemblyRecipe.sequence.size(); int step = sequencedAssemblyRecipe.getStep(stack); int total = length * sequencedAssemblyRecipe.loops; diff --git a/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedRecipe.java b/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedRecipe.java index 3105e477f8..a9bf8ebde7 100644 --- a/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedRecipe.java +++ b/src/main/java/com/simibubi/create/content/processing/sequenced/SequencedRecipe.java @@ -13,6 +13,7 @@ import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.RecipeSerializer; + import net.minecraftforge.common.crafting.conditions.ICondition.IContext; import net.minecraftforge.registries.ForgeRegistries; @@ -46,9 +47,7 @@ public class SequencedRecipe> { ResourceLocation parentId = parent.getId(); Recipe recipe = RecipeManager.fromJson( new ResourceLocation(parentId.getNamespace(), parentId.getPath() + "_step_" + index), json, IContext.EMPTY); - if (recipe instanceof ProcessingRecipe && recipe instanceof IAssemblyRecipe) { - ProcessingRecipe processingRecipe = (ProcessingRecipe) recipe; - IAssemblyRecipe assemblyRecipe = (IAssemblyRecipe) recipe; + if (recipe instanceof ProcessingRecipe processingRecipe && recipe instanceof IAssemblyRecipe assemblyRecipe) { if (assemblyRecipe.supportsAssembly()) { Ingredient transit = Ingredient.of(parent.getTransitionalItem()); processingRecipe.getIngredients() diff --git a/src/main/java/com/simibubi/create/content/redstone/link/LinkRenderer.java b/src/main/java/com/simibubi/create/content/redstone/link/LinkRenderer.java index e73b9ca959..280bdadb3a 100644 --- a/src/main/java/com/simibubi/create/content/redstone/link/LinkRenderer.java +++ b/src/main/java/com/simibubi/create/content/redstone/link/LinkRenderer.java @@ -35,10 +35,9 @@ public class LinkRenderer { public static void tick() { Minecraft mc = Minecraft.getInstance(); HitResult target = mc.hitResult; - if (target == null || !(target instanceof BlockHitResult)) + if (target == null || !(target instanceof BlockHitResult result)) return; - BlockHitResult result = (BlockHitResult) target; ClientLevel world = mc.level; BlockPos pos = result.getBlockPos(); @@ -79,7 +78,7 @@ public class LinkRenderer { } public static void renderOnBlockEntity(SmartBlockEntity be, float partialTicks, PoseStack ms, - MultiBufferSource buffer, int light, int overlay) { + MultiBufferSource buffer, int light, int overlay) { if (be == null || be.isRemoved()) return; diff --git a/src/main/java/com/simibubi/create/content/redstone/link/RedstoneLinkNetworkHandler.java b/src/main/java/com/simibubi/create/content/redstone/link/RedstoneLinkNetworkHandler.java index 73153bf16c..22f244fbbc 100644 --- a/src/main/java/com/simibubi/create/content/redstone/link/RedstoneLinkNetworkHandler.java +++ b/src/main/java/com/simibubi/create/content/redstone/link/RedstoneLinkNetworkHandler.java @@ -104,7 +104,7 @@ public class RedstoneLinkNetworkHandler { globalPowerVersion.incrementAndGet(); int power = 0; - for (Iterator iterator = network.iterator(); iterator.hasNext();) { + for (Iterator iterator = network.iterator(); iterator.hasNext(); ) { IRedstoneLinkable other = iterator.next(); if (!other.isAlive()) { iterator.remove(); @@ -118,8 +118,7 @@ public class RedstoneLinkNetworkHandler { power = Math.max(other.getTransmittedStrength(), power); } - if (actor instanceof LinkBehaviour) { - LinkBehaviour linkBehaviour = (LinkBehaviour) actor; + if (actor instanceof LinkBehaviour linkBehaviour) { // fix one-to-one loading order problem if (linkBehaviour.isListening()) { linkBehaviour.newPosition = true; diff --git a/src/main/java/com/simibubi/create/content/redstone/link/controller/LecternControllerBlockEntity.java b/src/main/java/com/simibubi/create/content/redstone/link/controller/LecternControllerBlockEntity.java index b52b5c7779..ff4549568f 100644 --- a/src/main/java/com/simibubi/create/content/redstone/link/controller/LecternControllerBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/redstone/link/controller/LecternControllerBlockEntity.java @@ -32,15 +32,16 @@ public class LecternControllerBlockEntity extends SmartBlockEntity { private CompoundTag controllerNbt = new CompoundTag(); private UUID user; - private UUID prevUser; // used only on client - private boolean deactivatedThisTick; // used only on server + private UUID prevUser; // used only on client + private boolean deactivatedThisTick; // used only on server public LecternControllerBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { super(type, pos, state); } @Override - public void addBehaviours(List behaviours) { } + public void addBehaviours(List behaviours) { + } @Override protected void write(CompoundTag compound, boolean clientPacket) { @@ -74,7 +75,9 @@ public class LecternControllerBlockEntity extends SmartBlockEntity { return createLinkedController(); } - public boolean hasUser() { return user != null; } + public boolean hasUser() { + return user != null; + } public boolean isUsedBy(Player player) { return hasUser() && user.equals(player.getUUID()); @@ -126,12 +129,11 @@ public class LecternControllerBlockEntity extends SmartBlockEntity { return; Entity entity = ((ServerLevel) level).getEntity(user); - if (!(entity instanceof Player)) { + if (!(entity instanceof Player player)) { stopUsing(null); return; } - Player player = (Player) entity; if (!playerInRange(player, level, worldPosition) || !playerIsUsingLectern(player)) stopUsing(player); } diff --git a/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerItemRenderer.java b/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerItemRenderer.java index 5e34a5be06..90e4de56d5 100644 --- a/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerItemRenderer.java +++ b/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerItemRenderer.java @@ -60,33 +60,33 @@ public class LinkedControllerItemRenderer extends CustomRenderedItemModelRendere } static void resetButtons() { - for (int i = 0; i < buttons.size(); i++) { - buttons.get(i).startWithValue(0); + for (LerpedFloat button : buttons) { + button.startWithValue(0); } } @Override protected void render(ItemStack stack, CustomRenderedItemModel model, PartialItemModelRenderer renderer, - ItemDisplayContext transformType, PoseStack ms, MultiBufferSource buffer, int light, - int overlay) { + ItemDisplayContext transformType, PoseStack ms, MultiBufferSource buffer, int light, + int overlay) { renderNormal(stack, model, renderer, transformType, ms, light); } protected static void renderNormal(ItemStack stack, CustomRenderedItemModel model, - PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, - int light) { + PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, + int light) { render(stack, model, renderer, transformType, ms, light, RenderType.NORMAL, false, false); } public static void renderInLectern(ItemStack stack, CustomRenderedItemModel model, - PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, - int light, boolean active, boolean renderDepression) { + PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, + int light, boolean active, boolean renderDepression) { render(stack, model, renderer, transformType, ms, light, RenderType.LECTERN, active, renderDepression); } protected static void render(ItemStack stack, CustomRenderedItemModel model, - PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, - int light, RenderType renderType, boolean active, boolean renderDepression) { + PartialItemModelRenderer renderer, ItemDisplayContext transformType, PoseStack ms, + int light, RenderType renderType, boolean active, boolean renderDepression) { float pt = AnimationTickHolder.getPartialTicks(); var msr = TransformStack.of(ms); @@ -96,9 +96,9 @@ public class LinkedControllerItemRenderer extends CustomRenderedItemModelRendere Minecraft mc = Minecraft.getInstance(); boolean rightHanded = mc.options.mainHand().get() == HumanoidArm.RIGHT; ItemDisplayContext mainHand = - rightHanded ? ItemDisplayContext.FIRST_PERSON_RIGHT_HAND : ItemDisplayContext.FIRST_PERSON_LEFT_HAND; + rightHanded ? ItemDisplayContext.FIRST_PERSON_RIGHT_HAND : ItemDisplayContext.FIRST_PERSON_LEFT_HAND; ItemDisplayContext offHand = - rightHanded ? ItemDisplayContext.FIRST_PERSON_LEFT_HAND : ItemDisplayContext.FIRST_PERSON_RIGHT_HAND; + rightHanded ? ItemDisplayContext.FIRST_PERSON_LEFT_HAND : ItemDisplayContext.FIRST_PERSON_RIGHT_HAND; active = false; boolean noControllerInMain = !AllItems.LINKED_CONTROLLER.isIn(mc.player.getMainHandItem()); @@ -163,7 +163,7 @@ public class LinkedControllerItemRenderer extends CustomRenderedItemModelRendere } protected static void renderButton(PartialItemModelRenderer renderer, PoseStack ms, int light, float pt, BakedModel button, - float b, int index, boolean renderDepression) { + float b, int index, boolean renderDepression) { ms.pushPose(); if (renderDepression) { float depression = b * buttons.get(index).getValue(pt); diff --git a/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerServerHandler.java b/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerServerHandler.java index 6729912cbd..e5e631a6f5 100644 --- a/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerServerHandler.java +++ b/src/main/java/com/simibubi/create/content/redstone/link/controller/LinkedControllerServerHandler.java @@ -30,12 +30,12 @@ public class LinkedControllerServerHandler { public static void tick(LevelAccessor world) { Map> map = receivedInputs.get(world); for (Iterator>> iterator = map.entrySet() - .iterator(); iterator.hasNext();) { + .iterator(); iterator.hasNext(); ) { Entry> entry = iterator.next(); Collection list = entry.getValue(); - for (Iterator entryIterator = list.iterator(); entryIterator.hasNext();) { + for (Iterator entryIterator = list.iterator(); entryIterator.hasNext(); ) { ManualFrequencyEntry manualFrequencyEntry = entryIterator.next(); manualFrequencyEntry.decrement(); if (!manualFrequencyEntry.isAlive()) { @@ -50,13 +50,13 @@ public class LinkedControllerServerHandler { } public static void receivePressed(LevelAccessor world, BlockPos pos, UUID uniqueID, List> collect, - boolean pressed) { + boolean pressed) { Map> map = receivedInputs.get(world); Collection list = map.computeIfAbsent(uniqueID, $ -> new ArrayList<>()); - WithNext: for (Couple activated : collect) { - for (Iterator iterator = list.iterator(); iterator.hasNext();) { - ManualFrequencyEntry entry = iterator.next(); + WithNext: + for (Couple activated : collect) { + for (ManualFrequencyEntry entry : list) { if (entry.getSecond() .equals(activated)) { if (!pressed) @@ -110,7 +110,8 @@ public class LinkedControllerServerHandler { } @Override - public void setReceivedStrength(int power) {} + public void setReceivedStrength(int power) { + } @Override public boolean isListening() { diff --git a/src/main/java/com/simibubi/create/content/redstone/rail/ControllerRailBlock.java b/src/main/java/com/simibubi/create/content/redstone/rail/ControllerRailBlock.java index 979ce222da..a921073e45 100644 --- a/src/main/java/com/simibubi/create/content/redstone/rail/ControllerRailBlock.java +++ b/src/main/java/com/simibubi/create/content/redstone/rail/ControllerRailBlock.java @@ -61,15 +61,15 @@ public class ControllerRailBlock extends BaseRailBlock implements IWrenchable { private static Direction getPointingTowards(BlockState state) { switch (state.getValue(SHAPE)) { - case ASCENDING_WEST: - case EAST_WEST: - return Direction.WEST; - case ASCENDING_EAST: - return Direction.EAST; - case ASCENDING_SOUTH: - return Direction.SOUTH; - default: - return Direction.NORTH; + case ASCENDING_WEST: + case EAST_WEST: + return Direction.WEST; + case ASCENDING_EAST: + return Direction.EAST; + case ASCENDING_SOUTH: + return Direction.SOUTH; + default: + return Direction.NORTH; } } @@ -109,8 +109,7 @@ public class ControllerRailBlock extends BaseRailBlock implements IWrenchable { .subtract(cart.position()); cart.setDeltaMovement(diff.x / 16f, 0, diff.z / 16f); - if (cart instanceof MinecartFurnace) { - MinecartFurnace fme = (MinecartFurnace) cart; + if (cart instanceof MinecartFurnace fme) { fme.xPush = fme.zPush = 0; } } @@ -145,8 +144,7 @@ public class ControllerRailBlock extends BaseRailBlock implements IWrenchable { Vec3 accelerationVec = Vec3.atLowerCornerOf(getAccelerationVector(state)); double targetSpeed = cart.getMaxSpeedWithRail() * state.getValue(POWER) / 15f; - if (cart instanceof MinecartFurnace) { - MinecartFurnace fme = (MinecartFurnace) cart; + if (cart instanceof MinecartFurnace fme) { fme.xPush = accelerationVec.x; fme.zPush = accelerationVec.z; } @@ -216,8 +214,8 @@ public class ControllerRailBlock extends BaseRailBlock implements IWrenchable { if (world.isClientSide) return InteractionResult.SUCCESS; BlockPos pos = context.getClickedPos(); - for (Rotation testRotation : new Rotation[] { Rotation.CLOCKWISE_90, Rotation.CLOCKWISE_180, - Rotation.COUNTERCLOCKWISE_90 }) { + for (Rotation testRotation : new Rotation[]{Rotation.CLOCKWISE_90, Rotation.CLOCKWISE_180, + Rotation.COUNTERCLOCKWISE_90}) { BlockState testState = rotate(state, testRotation); if (isStableWith(testState, world, pos)) { placeAndNotify(testState, pos, world); diff --git a/src/main/java/com/simibubi/create/content/schematics/cannon/SchematicannonScreen.java b/src/main/java/com/simibubi/create/content/schematics/cannon/SchematicannonScreen.java index 39de007c09..95dbf0d114 100644 --- a/src/main/java/com/simibubi/create/content/schematics/cannon/SchematicannonScreen.java +++ b/src/main/java/com/simibubi/create/content/schematics/cannon/SchematicannonScreen.java @@ -238,8 +238,7 @@ public class SchematicannonScreen extends AbstractSimiContainerScreen { - public static final Codec CODEC = RecordCodecBuilder.create(i -> + public static final Codec CODEC = RecordCodecBuilder.create(i -> i.group( - Codec.FLOAT.fieldOf("r").forGetter(p -> p.r), - Codec.FLOAT.fieldOf("g").forGetter(p -> p.g), - Codec.FLOAT.fieldOf("b").forGetter(p -> p.b), - Codec.FLOAT.fieldOf("scale").forGetter(p -> p.scale), - Codec.INT.fieldOf("avgAge").forGetter(p -> p.avgAge), - Codec.BOOL.fieldOf("hot").forGetter(p -> p.hot)) - .apply(i, CubeParticleData::new)); + Codec.FLOAT.fieldOf("r").forGetter(p -> p.r), + Codec.FLOAT.fieldOf("g").forGetter(p -> p.g), + Codec.FLOAT.fieldOf("b").forGetter(p -> p.b), + Codec.FLOAT.fieldOf("scale").forGetter(p -> p.scale), + Codec.INT.fieldOf("avgAge").forGetter(p -> p.avgAge), + Codec.BOOL.fieldOf("hot").forGetter(p -> p.hot)) + .apply(i, CubeParticleData::new)); - public static final ParticleOptions.Deserializer DESERIALIZER = new ParticleOptions.Deserializer() { + public static final ParticleOptions.Deserializer DESERIALIZER = new ParticleOptions.Deserializer<>() { @Override public CubeParticleData fromCommand(ParticleType type, StringReader reader) throws CommandSyntaxException { reader.expect(' '); diff --git a/src/main/java/com/simibubi/create/content/trains/display/FlapDisplayBlock.java b/src/main/java/com/simibubi/create/content/trains/display/FlapDisplayBlock.java index 2ff4413d94..6d062884c7 100644 --- a/src/main/java/com/simibubi/create/content/trains/display/FlapDisplayBlock.java +++ b/src/main/java/com/simibubi/create/content/trains/display/FlapDisplayBlock.java @@ -28,7 +28,6 @@ import net.minecraft.core.Direction.AxisDirection; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; @@ -118,7 +117,7 @@ public class FlapDisplayBlock extends HorizontalKineticBlock @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, - BlockHitResult ray) { + BlockHitResult ray) { if (player.isShiftKeyDown()) return InteractionResult.PASS; @@ -140,8 +139,8 @@ public class FlapDisplayBlock extends HorizontalKineticBlock double yCoord = ray.getLocation() .add(Vec3.atLowerCornerOf(ray.getDirection() - .getOpposite() - .getNormal()) + .getOpposite() + .getNormal()) .scale(.125f)).y; int lineIndex = flapBE.getLineIndexAt(yCoord); @@ -179,11 +178,11 @@ public class FlapDisplayBlock extends HorizontalKineticBlock if (AllBlocks.CLIPBOARD.isIn(heldItem)) { List entries = ClipboardEntry.getLastViewedEntries(heldItem); int line = lineIndex; - for (int i = 0; i < entries.size(); i++) { - for (String string : entries.get(i).text.getString() + for (ClipboardEntry entry : entries) { + for (String string : entry.text.getString() .split("\n")) { - flapBE.applyTextManually(line++, Component.Serializer.toJson(Component.literal(string))); - } + flapBE.applyTextManually(line++, Component.Serializer.toJson(Component.literal(string))); + } } return InteractionResult.SUCCESS; } @@ -230,7 +229,8 @@ public class FlapDisplayBlock extends HorizontalKineticBlock for (Direction connection : Iterate.directionsInAxis(Axis.Y)) { boolean connect = true; - Move: for (Direction movement : Iterate.directionsInAxis(axis)) { + Move: + for (Direction movement : Iterate.directionsInAxis(axis)) { currentPos.set(pos); for (int i = 0; i < 1000; i++) { if (!level.isLoaded(currentPos)) @@ -280,12 +280,12 @@ public class FlapDisplayBlock extends HorizontalKineticBlock @Override public BlockState updateShape(BlockState state, Direction pDirection, BlockState pNeighborState, - LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) { + LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) { return updatedShapeInner(state, pDirection, pNeighborState, pLevel, pCurrentPos); } private BlockState updatedShapeInner(BlockState state, Direction pDirection, BlockState pNeighborState, - LevelAccessor pLevel, BlockPos pCurrentPos) { + LevelAccessor pLevel, BlockPos pCurrentPos) { if (state.getValue(BlockStateProperties.WATERLOGGED)) pLevel.scheduleTick(pCurrentPos, Fluids.WATER, Fluids.WATER.getTickDelay(pLevel)); if (!canConnect(state, pNeighborState)) @@ -353,7 +353,7 @@ public class FlapDisplayBlock extends HorizontalKineticBlock @Override public PlacementOffset getOffset(Player player, Level world, BlockState state, BlockPos pos, - BlockHitResult ray) { + BlockHitResult ray) { List directions = IPlacementHelper.orderedByDistanceExceptAxis(pos, ray.getLocation(), state.getValue(FlapDisplayBlock.HORIZONTAL_FACING) .getAxis(), @@ -362,8 +362,8 @@ public class FlapDisplayBlock extends HorizontalKineticBlock return directions.isEmpty() ? PlacementOffset.fail() : PlacementOffset.success(pos.relative(directions.get(0)), s -> AllBlocks.DISPLAY_BOARD.get() - .updateColumn(world, pos.relative(directions.get(0)), - s.setValue(HORIZONTAL_FACING, state.getValue(FlapDisplayBlock.HORIZONTAL_FACING)), true)); + .updateColumn(world, pos.relative(directions.get(0)), + s.setValue(HORIZONTAL_FACING, state.getValue(FlapDisplayBlock.HORIZONTAL_FACING)), true)); } } diff --git a/src/main/java/com/simibubi/create/content/trains/graph/TrackGraph.java b/src/main/java/com/simibubi/create/content/trains/graph/TrackGraph.java index 53eb1572fc..2ac8ec3cb7 100644 --- a/src/main/java/com/simibubi/create/content/trains/graph/TrackGraph.java +++ b/src/main/java/com/simibubi/create/content/trains/graph/TrackGraph.java @@ -5,7 +5,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -27,9 +26,9 @@ import com.simibubi.create.content.trains.track.BezierConnection; import com.simibubi.create.content.trains.track.TrackMaterial; import net.createmod.catnip.data.Couple; -import net.createmod.catnip.nbt.NBTHelper; import net.createmod.catnip.data.Pair; import net.createmod.catnip.math.VecHelper; +import net.createmod.catnip.nbt.NBTHelper; import net.createmod.catnip.theme.Color; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -168,9 +167,7 @@ public class TrackGraph { return false; Map trains = Create.RAILWAYS.trains; - for (Iterator iterator = trains.keySet() - .iterator(); iterator.hasNext();) { - UUID uuid = iterator.next(); + for (UUID uuid : trains.keySet()) { Train train = trains.get(uuid); if (train.graph != this) continue; @@ -266,9 +263,7 @@ public class TrackGraph { toOther.invalidateBounds(); Map trains = Create.RAILWAYS.trains; - for (Iterator iterator = trains.keySet() - .iterator(); iterator.hasNext();) { - UUID uuid = iterator.next(); + for (UUID uuid : trains.keySet()) { Train train = trains.get(uuid); if (train.graph != this) continue; @@ -277,7 +272,7 @@ public class TrackGraph { } public Set findDisconnectedGraphs(@Nullable LevelAccessor level, - @Nullable Map> splitSubGraphs) { + @Nullable Map> splitSubGraphs) { Set dicovered = new HashSet<>(); Set vertices = new HashSet<>(nodes.keySet()); List frontier = new ArrayList<>(); @@ -356,9 +351,7 @@ public class TrackGraph { } if (level != null) - for (Iterator iterator = trains.keySet() - .iterator(); iterator.hasNext();) { - UUID uuid = iterator.next(); + for (UUID uuid : trains.keySet()) { Train train = trains.get(uuid); if (train.graph != this) continue; @@ -391,7 +384,7 @@ public class TrackGraph { } public void connectNodes(LevelAccessor reader, DiscoveredLocation location, DiscoveredLocation location2, - @Nullable BezierConnection turn) { + @Nullable BezierConnection turn) { TrackNode node1 = nodes.get(location); TrackNode node2 = nodes.get(location2); diff --git a/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItem.java b/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItem.java index 6eb4740bc3..7ee1313da6 100644 --- a/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItem.java +++ b/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItem.java @@ -33,6 +33,7 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.network.NetworkHooks; @@ -65,7 +66,7 @@ public class ScheduleItem extends Item implements MenuProvider, SupportsItemCopy } public InteractionResult handScheduleTo(ItemStack pStack, Player pPlayer, LivingEntity pInteractionTarget, - InteractionHand pUsedHand) { + InteractionHand pUsedHand) { InteractionResult pass = InteractionResult.PASS; Schedule schedule = getSchedule(pStack); @@ -74,12 +75,11 @@ public class ScheduleItem extends Item implements MenuProvider, SupportsItemCopy if (pInteractionTarget == null) return pass; Entity rootVehicle = pInteractionTarget.getRootVehicle(); - if (!(rootVehicle instanceof CarriageContraptionEntity)) + if (!(rootVehicle instanceof CarriageContraptionEntity entity)) return pass; if (pPlayer.level().isClientSide) return InteractionResult.SUCCESS; - CarriageContraptionEntity entity = (CarriageContraptionEntity) rootVehicle; Contraption contraption = entity.getContraption(); if (contraption instanceof CarriageContraption cc) { @@ -131,8 +131,8 @@ public class ScheduleItem extends Item implements MenuProvider, SupportsItemCopy if (schedule == null || schedule.entries.isEmpty()) return; - MutableComponent caret = Component.literal("> ").withStyle(ChatFormatting.GRAY); - MutableComponent arrow = Component.literal("-> ").withStyle(ChatFormatting.GRAY); + MutableComponent caret = Component.literal("> ").withStyle(ChatFormatting.GRAY); + MutableComponent arrow = Component.literal("-> ").withStyle(ChatFormatting.GRAY); List entries = schedule.entries; for (int i = 0; i < entries.size(); i++) { @@ -142,7 +142,7 @@ public class ScheduleItem extends Item implements MenuProvider, SupportsItemCopy continue; ChatFormatting format = current ? ChatFormatting.YELLOW : ChatFormatting.GOLD; MutableComponent prefix = current ? arrow : caret; - tooltip.add(prefix.copy() + tooltip.add(prefix.copy() .append(Component.literal(destination.getFilter()).withStyle(format))); } } diff --git a/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItemEntityInteraction.java b/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItemEntityInteraction.java index 9d90cd83ea..ab1ff200c0 100644 --- a/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItemEntityInteraction.java +++ b/src/main/java/com/simibubi/create/content/trains/schedule/ScheduleItemEntityInteraction.java @@ -16,6 +16,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; + import net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; @@ -33,7 +34,7 @@ public class ScheduleItemEntityInteraction { return; Entity rootVehicle = entity.getRootVehicle(); - if (!(rootVehicle instanceof CarriageContraptionEntity)) + if (!(rootVehicle instanceof CarriageContraptionEntity cce)) return; if (!(entity instanceof LivingEntity living)) return; @@ -42,7 +43,7 @@ public class ScheduleItemEntityInteraction { return; ItemStack itemStack = event.getItemStack(); - if (itemStack.getItem()instanceof ScheduleItem si) { + if (itemStack.getItem() instanceof ScheduleItem si) { InteractionResult result = si.handScheduleTo(itemStack, player, living, event.getHand()); if (result.consumesAction()) { player.getCooldowns() @@ -56,7 +57,6 @@ public class ScheduleItemEntityInteraction { if (event.getHand() == InteractionHand.OFF_HAND) return; - CarriageContraptionEntity cce = (CarriageContraptionEntity) rootVehicle; Contraption contraption = cce.getContraption(); if (!(contraption instanceof CarriageContraption cc)) return; diff --git a/src/main/java/com/simibubi/create/content/trains/signal/EdgeGroupColor.java b/src/main/java/com/simibubi/create/content/trains/signal/EdgeGroupColor.java index 845932b874..31671675c3 100644 --- a/src/main/java/com/simibubi/create/content/trains/signal/EdgeGroupColor.java +++ b/src/main/java/com/simibubi/create/content/trains/signal/EdgeGroupColor.java @@ -13,9 +13,7 @@ public enum EdgeGroupColor { CYAN(0x6EDAD9), BROWN(0xA17C58), - WHITE(0xE5E1DC) - - ; + WHITE(0xE5E1DC); private Color color; private int mask; @@ -41,9 +39,9 @@ public enum EdgeGroupColor { public static EdgeGroupColor findNextAvailable(int mask) { EdgeGroupColor[] values = values(); - for (int i = 0; i < values.length; i++) { + for (EdgeGroupColor value : values) { if ((mask & 1) == 0) - return values[i]; + return value; mask = mask >> 1; } return WHITE; diff --git a/src/main/java/com/simibubi/create/content/trains/station/GlobalStation.java b/src/main/java/com/simibubi/create/content/trains/station/GlobalStation.java index bcf7fe995f..edcbbf6c4a 100644 --- a/src/main/java/com/simibubi/create/content/trains/station/GlobalStation.java +++ b/src/main/java/com/simibubi/create/content/trains/station/GlobalStation.java @@ -29,6 +29,7 @@ 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.state.BlockState; + import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemHandlerHelper; @@ -44,7 +45,7 @@ public class GlobalStation extends SingleBlockEntityEdgePoint { public GlobalStation() { name = "Track Station"; - nearestTrain = new WeakReference(null); + nearestTrain = new WeakReference<>(null); connectedPorts = new HashMap<>(); } @@ -61,7 +62,7 @@ public class GlobalStation extends SingleBlockEntityEdgePoint { super.read(nbt, migration, dimensions); name = nbt.getString("Name"); assembling = nbt.getBoolean("Assembling"); - nearestTrain = new WeakReference(null); + nearestTrain = new WeakReference<>(null); connectedPorts.clear(); ListTag portList = nbt.getList("Ports", Tag.TAG_COMPOUND); diff --git a/src/main/java/com/simibubi/create/content/trains/station/StationBlockEntity.java b/src/main/java/com/simibubi/create/content/trains/station/StationBlockEntity.java index 8d9345fa71..eae80b1e4b 100644 --- a/src/main/java/com/simibubi/create/content/trains/station/StationBlockEntity.java +++ b/src/main/java/com/simibubi/create/content/trains/station/StationBlockEntity.java @@ -286,7 +286,7 @@ public class StationBlockEntity extends SmartBlockEntity implements Transformabl } public boolean trackClicked(Player player, InteractionHand hand, ITrackBlock track, BlockState state, - BlockPos pos) { + BlockPos pos) { refreshAssemblyInfo(); BoundingBox bb = assemblyAreas.get(level) .get(worldPosition); @@ -983,7 +983,7 @@ public class StationBlockEntity extends SmartBlockEntity implements Transformabl return; if (ppbe instanceof PostboxBlockEntity pbe) - pbe.trackedGlobalStation = new WeakReference(station); + pbe.trackedGlobalStation = new WeakReference<>(station); if (station.connectedPorts.containsKey(ppbe.getBlockPos())) restoreOfflineBuffer(ppbe, station.connectedPorts.get(ppbe.getBlockPos())); diff --git a/src/main/java/com/simibubi/create/content/trains/station/StationRenderer.java b/src/main/java/com/simibubi/create/content/trains/station/StationRenderer.java index a7516d3436..46f379add2 100644 --- a/src/main/java/com/simibubi/create/content/trains/station/StationRenderer.java +++ b/src/main/java/com/simibubi/create/content/trains/station/StationRenderer.java @@ -28,11 +28,12 @@ import net.minecraft.world.level.block.state.BlockState; public class StationRenderer extends SafeBlockEntityRenderer { - public StationRenderer(BlockEntityRendererProvider.Context context) {} + public StationRenderer(BlockEntityRendererProvider.Context context) { + } @Override protected void renderSafe(StationBlockEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer, - int light, int overlay) { + int light, int overlay) { BlockPos pos = be.getBlockPos(); TrackTargetingBehaviour target = be.edgePoint; @@ -43,7 +44,7 @@ public class StationRenderer extends SafeBlockEntityRenderer BlockState trackState = level.getBlockState(targetPosition); Block block = trackState.getBlock(); - if (!(block instanceof ITrackBlock)) + if (!(block instanceof ITrackBlock track)) return; GlobalStation station = be.getStation(); @@ -65,7 +66,6 @@ public class StationRenderer extends SafeBlockEntityRenderer renderFlag(AllPartialModels.STATION_ASSEMBLE, be, partialTicks, ms, buffer, light, overlay); - ITrackBlock track = (ITrackBlock) block; Direction direction = be.assemblyDirection; if (be.isVirtual() && be.bogeyLocations == null) @@ -112,7 +112,7 @@ public class StationRenderer extends SafeBlockEntityRenderer } public static void renderFlag(PartialModel flag, StationBlockEntity be, float partialTicks, PoseStack ms, - MultiBufferSource buffer, int light, int overlay) { + MultiBufferSource buffer, int light, int overlay) { if (!be.resolveFlagAngle()) return; SuperByteBuffer flagBB = CachedBuffers.partial(flag, be.getBlockState()); @@ -125,7 +125,7 @@ public class StationRenderer extends SafeBlockEntityRenderer } public static void transformFlag(Transform flag, StationBlockEntity be, float partialTicks, int yRot, - boolean flipped) { + boolean flipped) { float value = be.flag.getValue(partialTicks); float progress = (float) (Math.pow(Math.min(value * 5, 1), 2)); if (be.flag.getChaseTarget() > 0 && !be.flag.settled() && progress == 1) { diff --git a/src/main/java/com/simibubi/create/content/trains/track/TrackBlockItem.java b/src/main/java/com/simibubi/create/content/trains/track/TrackBlockItem.java index 48cd77d7fa..91a8bb0cb0 100644 --- a/src/main/java/com/simibubi/create/content/trains/track/TrackBlockItem.java +++ b/src/main/java/com/simibubi/create/content/trains/track/TrackBlockItem.java @@ -30,6 +30,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.event.entity.player.PlayerInteractEvent; @@ -137,10 +138,9 @@ public class TrackBlockItem extends BlockItem { public static boolean select(LevelAccessor world, BlockPos pos, Vec3 lookVec, ItemStack heldItem) { BlockState blockState = world.getBlockState(pos); Block block = blockState.getBlock(); - if (!(block instanceof ITrackBlock)) + if (!(block instanceof ITrackBlock track)) return false; - ITrackBlock track = (ITrackBlock) block; Pair nearestTrackAxis = track.getNearestTrackAxis(world, pos, blockState, lookVec); Vec3 axis = nearestTrackAxis.getFirst() .scale(nearestTrackAxis.getSecond() == AxisDirection.POSITIVE ? -1 : 1); diff --git a/src/main/java/com/simibubi/create/content/trains/track/TrackModel.java b/src/main/java/com/simibubi/create/content/trains/track/TrackModel.java index 9fc35e1e43..b8b4ee6af0 100644 --- a/src/main/java/com/simibubi/create/content/trains/track/TrackModel.java +++ b/src/main/java/com/simibubi/create/content/trains/track/TrackModel.java @@ -19,6 +19,7 @@ import net.minecraft.util.Mth; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.client.model.BakedModelWrapper; import net.minecraftforge.client.model.data.ModelData; @@ -30,7 +31,7 @@ public class TrackModel extends BakedModelWrapper { @Override public @NotNull List getQuads(@Nullable BlockState state, @Nullable Direction side, - @NotNull RandomSource rand, @NotNull ModelData extraData, @Nullable RenderType renderType) { + @NotNull RandomSource rand, @NotNull ModelData extraData, @Nullable RenderType renderType) { List templateQuads = super.getQuads(state, side, rand, extraData, renderType); if (templateQuads.isEmpty()) return templateQuads; @@ -43,11 +44,11 @@ public class TrackModel extends BakedModelWrapper { TrackShape trackShape = state.getValue(TrackBlock.SHAPE); double hAngle = switch (trackShape) { - case XO -> 0; - case PD -> 45; - case ZO -> 90; - case ND -> 135; - default -> 0; + case XO -> 0; + case PD -> 45; + case ZO -> 90; + case ND -> 135; + default -> 0; }; Vec3 verticalOffset = new Vec3(0, -0.25, 0); @@ -68,8 +69,8 @@ public class TrackModel extends BakedModelWrapper { int size = templateQuads.size(); List quads = new ArrayList<>(); - for (int i = 0; i < size; i++) { - BakedQuad quad = BakedQuadHelper.clone(templateQuads.get(i)); + for (BakedQuad templateQuad : templateQuads) { + BakedQuad quad = BakedQuadHelper.clone(templateQuad); int[] vertexData = quad.getVertices(); for (int j = 0; j < 4; j++) BakedQuadHelper.setXYZ(vertexData, j, transform.apply(BakedQuadHelper.getXYZ(vertexData, j))); diff --git a/src/main/java/com/simibubi/create/content/trains/track/TrackPlacement.java b/src/main/java/com/simibubi/create/content/trains/track/TrackPlacement.java index 65f9d11168..68091ff151 100644 --- a/src/main/java/com/simibubi/create/content/trains/track/TrackPlacement.java +++ b/src/main/java/com/simibubi/create/content/trains/track/TrackPlacement.java @@ -14,13 +14,13 @@ import com.simibubi.create.foundation.utility.BlockHelper; import com.simibubi.create.foundation.utility.CreateLang; import com.simibubi.create.infrastructure.config.AllConfigs; +import net.createmod.catnip.animation.LerpedFloat; +import net.createmod.catnip.animation.LerpedFloat.Chaser; import net.createmod.catnip.data.Couple; import net.createmod.catnip.data.Iterate; import net.createmod.catnip.data.Pair; -import net.createmod.catnip.math.VecHelper; -import net.createmod.catnip.animation.LerpedFloat; -import net.createmod.catnip.animation.LerpedFloat.Chaser; import net.createmod.catnip.math.AngleHelper; +import net.createmod.catnip.math.VecHelper; import net.createmod.catnip.outliner.Outliner; import net.createmod.catnip.theme.Color; import net.minecraft.ChatFormatting; @@ -107,7 +107,7 @@ public class TrackPlacement { static int extraTipWarmup; public static PlacementInfo tryConnect(Level level, Player player, BlockPos pos2, BlockState state2, - ItemStack stack, boolean girder, boolean maximiseTurn) { + ItemStack stack, boolean girder, boolean maximiseTurn) { Vec3 lookVec = player.getLookAngle(); int lookAngle = (int) (22.5 + AngleHelper.deg(Mth.atan2(lookVec.z, lookVec.x)) % 360) / 8; int maxLength = AllConfigs.server().trains.maxTrackPlacementLength.get(); @@ -361,8 +361,8 @@ public class TrackPlacement { info.curve = skipCurve ? null : new BezierConnection(Couple.create(targetPos1, targetPos2), - Couple.create(end1.add(offset1), end2.add(offset2)), Couple.create(normedAxis1, normedAxis2), - Couple.create(normal1, normal2), true, girder, TrackMaterial.fromItem(stack.getItem())); + Couple.create(end1.add(offset1), end2.add(offset2)), Couple.create(normedAxis1, normedAxis2), + Couple.create(normal1, normal2), true, girder, TrackMaterial.fromItem(stack.getItem())); info.valid = true; @@ -481,7 +481,7 @@ public class TrackPlacement { } private static PlacementInfo placeTracks(Level level, PlacementInfo info, BlockState state1, BlockState state2, - BlockPos targetPos1, BlockPos targetPos2, boolean simulate) { + BlockPos targetPos1, BlockPos targetPos2, boolean simulate) { info.requiredTracks = 0; for (boolean first : Iterate.trueAndFalse) { @@ -493,14 +493,14 @@ public class TrackPlacement { state = state.setValue(TrackBlock.HAS_BE, false); switch (state.getValue(TrackBlock.SHAPE)) { - case TE, TW: - state = state.setValue(TrackBlock.SHAPE, TrackShape.XO); - break; - case TN, TS: - state = state.setValue(TrackBlock.SHAPE, TrackShape.ZO); - break; - default: - break; + case TE, TW: + state = state.setValue(TrackBlock.SHAPE, TrackShape.XO); + break; + case TN, TS: + state = state.setValue(TrackBlock.SHAPE, TrackShape.ZO); + break; + default: + break; } for (int i = 0; i < (info.curve != null ? extent + 1 : extent); i++) { @@ -533,27 +533,24 @@ public class TrackPlacement { BlockState onto = info.trackMaterial.getBlock().defaultBlockState(); BlockState stateAtPos = level.getBlockState(targetPos1); level.setBlock(targetPos1, ProperWaterloggedBlock.withWater(level, - (AllTags.AllBlockTags.TRACKS.matches(stateAtPos) ? stateAtPos : BlockHelper.copyProperties(state1, onto)) - .setValue(TrackBlock.HAS_BE, true), targetPos1), 3); + (AllTags.AllBlockTags.TRACKS.matches(stateAtPos) ? stateAtPos : BlockHelper.copyProperties(state1, onto)) + .setValue(TrackBlock.HAS_BE, true), targetPos1), 3); stateAtPos = level.getBlockState(targetPos2); level.setBlock(targetPos2, ProperWaterloggedBlock.withWater(level, - (AllTags.AllBlockTags.TRACKS.matches(stateAtPos) ? stateAtPos : BlockHelper.copyProperties(state2, onto)) - .setValue(TrackBlock.HAS_BE, true), targetPos2), 3); + (AllTags.AllBlockTags.TRACKS.matches(stateAtPos) ? stateAtPos : BlockHelper.copyProperties(state2, onto)) + .setValue(TrackBlock.HAS_BE, true), targetPos2), 3); } BlockEntity te1 = level.getBlockEntity(targetPos1); BlockEntity te2 = level.getBlockEntity(targetPos2); int requiredTracksForTurn = (info.curve.getSegmentCount() + 1) / 2; - if (!(te1 instanceof TrackBlockEntity) || !(te2 instanceof TrackBlockEntity)) { + if (!(te1 instanceof TrackBlockEntity tte1) || !(te2 instanceof TrackBlockEntity tte2)) { info.requiredTracks += requiredTracksForTurn; return info; } - TrackBlockEntity tte1 = (TrackBlockEntity) te1; - TrackBlockEntity tte2 = (TrackBlockEntity) te2; - if (!tte1.getConnections() .containsKey(tte2.getBlockPos())) info.requiredTracks += requiredTracksForTurn; @@ -631,7 +628,7 @@ public class TrackPlacement { .withStyle(ChatFormatting.GREEN), true); else if (info.message != null) player.displayClientMessage(CreateLang.translateDirect(info.message) - .withStyle(info.message.equals("track.second_point") ? ChatFormatting.WHITE : ChatFormatting.RED), + .withStyle(info.message.equals("track.second_point") ? ChatFormatting.WHITE : ChatFormatting.RED), true); if (bhr.getDirection() == Direction.UP) { diff --git a/src/main/java/com/simibubi/create/content/trains/track/TrackTargetingBehaviour.java b/src/main/java/com/simibubi/create/content/trains/track/TrackTargetingBehaviour.java index 5bd2fa4f23..76997d1624 100644 --- a/src/main/java/com/simibubi/create/content/trains/track/TrackTargetingBehaviour.java +++ b/src/main/java/com/simibubi/create/content/trains/track/TrackTargetingBehaviour.java @@ -311,18 +311,17 @@ public class TrackTargetingBehaviour extends BlockEnti @OnlyIn(Dist.CLIENT) public static void render(LevelAccessor level, BlockPos pos, AxisDirection direction, - BezierTrackPointLocation bezier, PoseStack ms, MultiBufferSource buffer, int light, int overlay, - RenderedTrackOverlayType type, float scale) { + BezierTrackPointLocation bezier, PoseStack ms, MultiBufferSource buffer, int light, int overlay, + RenderedTrackOverlayType type, float scale) { if (level instanceof SchematicLevel && !(level instanceof PonderLevel)) return; BlockState trackState = level.getBlockState(pos); Block block = trackState.getBlock(); - if (!(block instanceof ITrackBlock)) + if (!(block instanceof ITrackBlock track)) return; ms.pushPose(); - ITrackBlock track = (ITrackBlock) block; PartialModel partial = track.prepareTrackOverlay(level, pos, trackState, bezier, direction, ms, type); if (partial != null) CachedBuffers.partial(partial, trackState) @@ -341,7 +340,7 @@ public class TrackTargetingBehaviour extends BlockEnti rotatedDirection = transform.applyWithoutOffsetUncentered(prevDirection); if (targetBezier != null) targetBezier = new BezierTrackPointLocation(transform.applyWithoutOffset(targetBezier.curveTarget() - .subtract(getPos())) + .subtract(getPos())) .offset(getPos()), targetBezier.segment()); blockEntity.notifyUpdate(); } diff --git a/src/main/java/com/simibubi/create/foundation/block/render/ReducedDestroyEffects.java b/src/main/java/com/simibubi/create/foundation/block/render/ReducedDestroyEffects.java index 534958cd5f..b66b63faed 100644 --- a/src/main/java/com/simibubi/create/foundation/block/render/ReducedDestroyEffects.java +++ b/src/main/java/com/simibubi/create/foundation/block/render/ReducedDestroyEffects.java @@ -10,15 +10,15 @@ import net.minecraft.util.Mth; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.VoxelShape; + import net.minecraftforge.client.extensions.common.IClientBlockExtensions; public class ReducedDestroyEffects implements IClientBlockExtensions { @Override public boolean addDestroyEffects(BlockState state, Level worldIn, BlockPos pos, ParticleEngine manager) { - if (!(worldIn instanceof ClientLevel)) + if (!(worldIn instanceof ClientLevel world)) return true; - ClientLevel world = (ClientLevel) worldIn; VoxelShape voxelshape = state.getShape(world, pos); MutableInt amtBoxes = new MutableInt(0); voxelshape.forAllBoxes((x1, y1, z1, x2, y2, z2) -> amtBoxes.increment()); diff --git a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/BlockEntityBehaviour.java b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/BlockEntityBehaviour.java index a15e57aef9..1935af6e62 100644 --- a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/BlockEntityBehaviour.java +++ b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/BlockEntityBehaviour.java @@ -44,7 +44,7 @@ public abstract class BlockEntityBehaviour { public void write(CompoundTag nbt, boolean clientPacket) { } - + /** * Called when isSafeNBT == true. Defaults to write() */ @@ -71,12 +71,14 @@ public abstract class BlockEntityBehaviour { /** * Block destroyed or Chunk unloaded. Usually invalidates capabilities */ - public void unload() {} + public void unload() { + } /** * Block destroyed or removed. Requires block to call ITE::onRemove */ - public void destroy() {} + public void destroy() { + } public void setLazyTickRate(int slowTickRate) { this.lazyTickRate = slowTickRate; @@ -108,9 +110,8 @@ public abstract class BlockEntityBehaviour { public static T get(BlockEntity be, BehaviourType type) { if (be == null) return null; - if (!(be instanceof SmartBlockEntity)) + if (!(be instanceof SmartBlockEntity ste)) return null; - SmartBlockEntity ste = (SmartBlockEntity) be; return ste.getBehaviour(type); } } diff --git a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/ValueBox.java b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/ValueBox.java index f69a909eaa..a7f6a31be0 100644 --- a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/ValueBox.java +++ b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/ValueBox.java @@ -54,7 +54,7 @@ public class ValueBox extends ChasingAABBOutline { this.label = label; this.pos = pos; this.blockState = state; - this.level = new WeakReference(Minecraft.getInstance().level); + this.level = new WeakReference<>(Minecraft.getInstance().level); } public ValueBox transform(ValueBoxTransform transform) { diff --git a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/edgeInteraction/EdgeInteractionRenderer.java b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/edgeInteraction/EdgeInteractionRenderer.java index a4872812eb..4c504547b9 100644 --- a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/edgeInteraction/EdgeInteractionRenderer.java +++ b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/edgeInteraction/EdgeInteractionRenderer.java @@ -33,10 +33,9 @@ public class EdgeInteractionRenderer { public static void tick() { Minecraft mc = Minecraft.getInstance(); HitResult target = mc.hitResult; - if (target == null || !(target instanceof BlockHitResult)) + if (target == null || !(target instanceof BlockHitResult result)) return; - BlockHitResult result = (BlockHitResult) target; ClientLevel world = mc.level; BlockPos pos = result.getBlockPos(); Player player = mc.player; diff --git a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/filtering/FilteringRenderer.java b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/filtering/FilteringRenderer.java index 074f931ced..f6bed852bd 100644 --- a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/filtering/FilteringRenderer.java +++ b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/filtering/FilteringRenderer.java @@ -42,10 +42,9 @@ public class FilteringRenderer { public static void tick() { Minecraft mc = Minecraft.getInstance(); HitResult target = mc.hitResult; - if (target == null || !(target instanceof BlockHitResult)) + if (target == null || !(target instanceof BlockHitResult result)) return; - BlockHitResult result = (BlockHitResult) target; ClientLevel world = mc.level; BlockPos pos = result.getBlockPos(); BlockState state = world.getBlockState(pos); @@ -109,7 +108,7 @@ public class FilteringRenderer { } public static void renderOnBlockEntity(SmartBlockEntity be, float partialTicks, PoseStack ms, - MultiBufferSource buffer, int light, int overlay) { + MultiBufferSource buffer, int light, int overlay) { if (be == null || be.isRemoved()) return; @@ -141,8 +140,7 @@ public class FilteringRenderer { ValueBoxTransform slotPositioning = behaviour.slotPositioning; BlockState blockState = be.getBlockState(); - if (slotPositioning instanceof ValueBoxTransform.Sided) { - ValueBoxTransform.Sided sided = (ValueBoxTransform.Sided) slotPositioning; + if (slotPositioning instanceof Sided sided) { Direction side = sided.getSide(); for (Direction d : Iterate.directions) { ItemStack filter = behaviour.getFilter(d); diff --git a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/scrollValue/ScrollValueRenderer.java b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/scrollValue/ScrollValueRenderer.java index ce38a9b641..77b33fa463 100644 --- a/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/scrollValue/ScrollValueRenderer.java +++ b/src/main/java/com/simibubi/create/foundation/blockEntity/behaviour/scrollValue/ScrollValueRenderer.java @@ -32,10 +32,9 @@ public class ScrollValueRenderer { public static void tick() { Minecraft mc = Minecraft.getInstance(); HitResult target = mc.hitResult; - if (target == null || !(target instanceof BlockHitResult)) + if (target == null || !(target instanceof BlockHitResult result)) return; - BlockHitResult result = (BlockHitResult) target; ClientLevel world = mc.level; BlockPos pos = result.getBlockPos(); Direction face = result.getDirection(); @@ -59,8 +58,7 @@ public class ScrollValueRenderer { continue; boolean highlight = behaviour.testHit(target.getLocation()) && !clipboard && !highlightFound; - if (behaviour instanceof BulkScrollValueBehaviour && AllKeys.ctrlDown()) { - BulkScrollValueBehaviour bulkScrolling = (BulkScrollValueBehaviour) behaviour; + if (behaviour instanceof BulkScrollValueBehaviour bulkScrolling && AllKeys.ctrlDown()) { for (SmartBlockEntity smartBlockEntity : bulkScrolling.getBulk()) { ScrollValueBehaviour other = smartBlockEntity.getBehaviour(ScrollValueBehaviour.TYPE); if (other != null) @@ -81,7 +79,7 @@ public class ScrollValueRenderer { } protected static void addBox(ClientLevel world, BlockPos pos, Direction face, ScrollValueBehaviour behaviour, - boolean highlight) { + boolean highlight) { AABB bb = new AABB(Vec3.ZERO, Vec3.ZERO).inflate(.5f) .contract(0, 0, -.5f) .move(0, 0, -.125f); @@ -91,7 +89,7 @@ public class ScrollValueRenderer { if (behaviour instanceof ScrollOptionBehaviour) { box = new IconValueBox(label, ((ScrollOptionBehaviour) behaviour).getIconForSelected(), bb, pos); } else { - box = new TextValueBox(label, bb, pos, Component.literal(behaviour.formatValue())); + box = new TextValueBox(label, bb, pos, Component.literal(behaviour.formatValue())); } box.passive(!highlight) diff --git a/src/main/java/com/simibubi/create/foundation/data/CreateRegistrate.java b/src/main/java/com/simibubi/create/foundation/data/CreateRegistrate.java index 74ea306475..61a1ce459e 100644 --- a/src/main/java/com/simibubi/create/foundation/data/CreateRegistrate.java +++ b/src/main/java/com/simibubi/create/foundation/data/CreateRegistrate.java @@ -47,6 +47,7 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockBehaviour.Properties; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; @@ -103,8 +104,8 @@ public class CreateRegistrate extends AbstractRegistrate { @Override protected RegistryEntry accept(String name, ResourceKey> type, - Builder builder, NonNullSupplier creator, - NonNullFunction, ? extends RegistryEntry> entryFactory) { + Builder builder, NonNullSupplier creator, + NonNullFunction, ? extends RegistryEntry> entryFactory) { RegistryEntry entry = super.accept(name, type, builder, creator, entryFactory); if (type.equals(Registries.ITEM)) { if (currentTooltipModifierFactory != null) { @@ -119,26 +120,26 @@ public class CreateRegistrate extends AbstractRegistrate { @Override public CreateBlockEntityBuilder blockEntity(String name, - BlockEntityFactory factory) { + BlockEntityFactory factory) { return blockEntity(self(), name, factory); } @Override public CreateBlockEntityBuilder blockEntity(P parent, String name, - BlockEntityFactory factory) { + BlockEntityFactory factory) { return (CreateBlockEntityBuilder) entry(name, (callback) -> CreateBlockEntityBuilder.create(this, parent, name, callback, factory)); } @Override public CreateEntityBuilder entity(String name, - EntityType.EntityFactory factory, MobCategory classification) { + EntityType.EntityFactory factory, MobCategory classification) { return this.entity(self(), name, factory, classification); } @Override public CreateEntityBuilder entity(P parent, String name, - EntityType.EntityFactory factory, MobCategory classification) { + EntityType.EntityFactory factory, MobCategory classification) { return (CreateEntityBuilder) this.entry(name, (callback) -> { return CreateEntityBuilder.create(this, parent, name, callback, factory, classification); }); @@ -155,8 +156,8 @@ public class CreateRegistrate extends AbstractRegistrate { /* Palettes */ public BlockBuilder paletteStoneBlock(String name, - NonNullFunction factory, NonNullSupplier propertiesFrom, boolean worldGenStone, - boolean hasNaturalVariants) { + NonNullFunction factory, NonNullSupplier propertiesFrom, boolean worldGenStone, + boolean hasNaturalVariants) { BlockBuilder builder = super.block(name, factory).initialProperties(propertiesFrom) .transform(pickaxeOnly()) .blockstate(hasNaturalVariants ? BlockStateGen.naturalStoneTypeBlock(name) : (c, p) -> { @@ -177,35 +178,35 @@ public class CreateRegistrate extends AbstractRegistrate { } public BlockBuilder paletteStoneBlock(String name, NonNullSupplier propertiesFrom, - boolean worldGenStone, boolean hasNaturalVariants) { + boolean worldGenStone, boolean hasNaturalVariants) { return paletteStoneBlock(name, Block::new, propertiesFrom, worldGenStone, hasNaturalVariants); } /* Fluids */ public FluidBuilder virtualFluid(String name, - FluidBuilder.FluidTypeFactory typeFactory, NonNullFunction sourceFactory, - NonNullFunction flowingFactory) { + FluidBuilder.FluidTypeFactory typeFactory, NonNullFunction sourceFactory, + NonNullFunction flowingFactory) { return entry(name, c -> new VirtualFluidBuilder<>(self(), self(), name, c, new ResourceLocation(getModid(), "fluid/" + name + "_still"), new ResourceLocation(getModid(), "fluid/" + name + "_flow"), typeFactory, sourceFactory, flowingFactory)); } public FluidBuilder virtualFluid(String name, - ResourceLocation still, ResourceLocation flow, FluidBuilder.FluidTypeFactory typeFactory, - NonNullFunction sourceFactory, NonNullFunction flowingFactory) { + ResourceLocation still, ResourceLocation flow, FluidBuilder.FluidTypeFactory typeFactory, + NonNullFunction sourceFactory, NonNullFunction flowingFactory) { return entry(name, c -> new VirtualFluidBuilder<>(self(), self(), name, c, still, flow, typeFactory, sourceFactory, flowingFactory)); } public FluidBuilder virtualFluid(String name) { return entry(name, - c -> new VirtualFluidBuilder(self(), self(), name, c, + c -> new VirtualFluidBuilder<>(self(), self(), name, c, new ResourceLocation(getModid(), "fluid/" + name + "_still"), new ResourceLocation(getModid(), "fluid/" + name + "_flow"), CreateRegistrate::defaultFluidType, VirtualFluid::createSource, VirtualFluid::createFlowing)); } public FluidBuilder virtualFluid(String name, ResourceLocation still, - ResourceLocation flow) { + ResourceLocation flow) { return entry(name, c -> new VirtualFluidBuilder<>(self(), self(), name, c, still, flow, CreateRegistrate::defaultFluidType, VirtualFluid::createSource, VirtualFluid::createFlowing)); } @@ -215,13 +216,13 @@ public class CreateRegistrate extends AbstractRegistrate { } public FluidBuilder standardFluid(String name, - FluidBuilder.FluidTypeFactory typeFactory) { + FluidBuilder.FluidTypeFactory typeFactory) { return fluid(name, new ResourceLocation(getModid(), "fluid/" + name + "_still"), new ResourceLocation(getModid(), "fluid/" + name + "_flow"), typeFactory); } public static FluidType defaultFluidType(FluidType.Properties properties, ResourceLocation stillTexture, - ResourceLocation flowingTexture) { + ResourceLocation flowingTexture) { return new FluidType(properties) { @Override public void initializeClient(Consumer consumer) { @@ -268,20 +269,20 @@ public class CreateRegistrate extends AbstractRegistrate { @OnlyIn(Dist.CLIENT) private static void registerCasingConnectivity(T entry, - BiConsumer consumer) { + BiConsumer consumer) { consumer.accept(entry, CreateClient.CASING_CONNECTIVITY); } @OnlyIn(Dist.CLIENT) private static void registerBlockModel(Block entry, - Supplier> func) { + Supplier> func) { CreateClient.MODEL_SWAPPER.getCustomBlockModels() .register(CatnipServices.REGISTRIES.getKeyOrThrow(entry), func.get()); } @OnlyIn(Dist.CLIENT) private static void registerItemModel(Item entry, - Supplier> func) { + Supplier> func) { CreateClient.MODEL_SWAPPER.getCustomItemModels() .register(CatnipServices.REGISTRIES.getKeyOrThrow(entry), func.get()); } diff --git a/src/main/java/com/simibubi/create/foundation/item/ItemHelper.java b/src/main/java/com/simibubi/create/foundation/item/ItemHelper.java index e567cc2239..4c89e97028 100644 --- a/src/main/java/com/simibubi/create/foundation/item/ItemHelper.java +++ b/src/main/java/com/simibubi/create/foundation/item/ItemHelper.java @@ -7,16 +7,10 @@ import java.util.function.Predicate; import javax.annotation.Nullable; -import com.simibubi.create.foundation.block.IBE; - -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.ForgeCapabilities; - -import net.minecraftforge.items.IItemHandlerModifiable; - import org.apache.commons.lang3.mutable.MutableInt; import com.simibubi.create.content.logistics.box.PackageEntity; +import com.simibubi.create.foundation.block.IBE; import net.createmod.catnip.data.Pair; import net.minecraft.core.BlockPos; @@ -28,7 +22,11 @@ import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; + +import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.IItemHandler; +import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemHandlerHelper; public class ItemHelper { @@ -85,9 +83,9 @@ public class ItemHelper { public static > int calcRedstoneFromBlockEntity(T ibe, Level level, BlockPos pos) { return ibe.getBlockEntityOptional(level, pos) - .map(be -> be.getCapability(ForgeCapabilities.ITEM_HANDLER)) - .map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory).orElse(0)) - .orElse(0); + .map(be -> be.getCapability(ForgeCapabilities.ITEM_HANDLER)) + .map(lo -> lo.map(ItemHelper::calcRedstoneFromInventory).orElse(0)) + .orElse(0); } public static int calcRedstoneFromInventory(@Nullable IItemHandler inv) { @@ -119,7 +117,8 @@ public class ItemHelper { public static List> condenseIngredients(NonNullList recipeIngredients) { List> actualIngredients = new ArrayList<>(); - Ingredients: for (Ingredient igd : recipeIngredients) { + Ingredients: + for (Ingredient igd : recipeIngredients) { for (Pair pair : actualIngredients) { ItemStack[] stacks1 = pair.getFirst() .getItems(); @@ -180,7 +179,7 @@ public class ItemHelper { } public static ItemStack extract(IItemHandler inv, Predicate test, ExtractionCountMode mode, int amount, - boolean simulate) { + boolean simulate) { ItemStack extracting = ItemStack.EMPTY; boolean amountRequired = mode == ExtractionCountMode.EXACTLY; boolean checkHasEnoughItems = amountRequired; @@ -188,7 +187,8 @@ public class ItemHelper { boolean potentialOtherMatch = false; int maxExtractionCount = amount; - Extraction: do { + Extraction: + do { extracting = ItemStack.EMPTY; for (int slot = 0; slot < inv.getSlots(); slot++) { @@ -245,7 +245,7 @@ public class ItemHelper { } public static ItemStack extract(IItemHandler inv, Predicate test, - Function amountFunction, boolean simulate) { + Function amountFunction, boolean simulate) { ItemStack extracting = ItemStack.EMPTY; int maxExtractionCount = 64; @@ -305,8 +305,7 @@ public class ItemHelper { public static ItemStack fromItemEntity(Entity entityIn) { if (!entityIn.isAlive()) return ItemStack.EMPTY; - if (entityIn instanceof PackageEntity) { - PackageEntity packageEntity = (PackageEntity) entityIn; + if (entityIn instanceof PackageEntity packageEntity) { return packageEntity.getBox(); } return entityIn instanceof ItemEntity ? ((ItemEntity) entityIn).getItem() : ItemStack.EMPTY; diff --git a/src/main/java/com/simibubi/create/foundation/particle/AirParticleData.java b/src/main/java/com/simibubi/create/foundation/particle/AirParticleData.java index 011c00177c..16b427fd7c 100644 --- a/src/main/java/com/simibubi/create/foundation/particle/AirParticleData.java +++ b/src/main/java/com/simibubi/create/foundation/particle/AirParticleData.java @@ -12,19 +12,20 @@ import net.minecraft.client.particle.ParticleEngine.SpriteParticleRegistration; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; import net.minecraft.network.FriendlyByteBuf; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public class AirParticleData implements ParticleOptions, ICustomParticleDataWithSprite { - public static final Codec CODEC = RecordCodecBuilder.create(i -> + public static final Codec CODEC = RecordCodecBuilder.create(i -> i.group( - Codec.FLOAT.fieldOf("drag").forGetter(p -> p.drag), - Codec.FLOAT.fieldOf("speed").forGetter(p -> p.speed)) - .apply(i, AirParticleData::new)); - + Codec.FLOAT.fieldOf("drag").forGetter(p -> p.drag), + Codec.FLOAT.fieldOf("speed").forGetter(p -> p.speed)) + .apply(i, AirParticleData::new)); + public static final ParticleOptions.Deserializer DESERIALIZER = - new ParticleOptions.Deserializer() { + new ParticleOptions.Deserializer<>() { public AirParticleData fromCommand(ParticleType particleTypeIn, StringReader reader) throws CommandSyntaxException { reader.expect(' '); @@ -39,7 +40,7 @@ public class AirParticleData implements ParticleOptions, ICustomParticleDataWith } }; - float drag; + float drag; float speed; public AirParticleData(float drag, float speed) { @@ -83,4 +84,4 @@ public class AirParticleData implements ParticleOptions, ICustomParticleDataWith return AirParticle.Factory::new; } -} \ No newline at end of file +} diff --git a/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleData.java b/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleData.java index fce8b6a62f..64a00bb344 100644 --- a/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleData.java +++ b/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleData.java @@ -6,6 +6,7 @@ import net.minecraft.client.particle.ParticleProvider; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleOptions.Deserializer; import net.minecraft.core.particles.ParticleType; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.RegisterParticleProvidersEvent; @@ -14,10 +15,10 @@ public interface ICustomParticleData { Deserializer getDeserializer(); - Codec getCodec(ParticleType type); - + Codec getCodec(ParticleType type); + public default ParticleType createType() { - return new ParticleType(false, getDeserializer()) { + return new ParticleType<>(false, getDeserializer()) { @Override public Codec codec() { @@ -25,13 +26,13 @@ public interface ICustomParticleData { } }; } - + @OnlyIn(Dist.CLIENT) public ParticleProvider getFactory(); - + @OnlyIn(Dist.CLIENT) public default void register(ParticleType type, RegisterParticleProvidersEvent event) { event.registerSpecial(type, getFactory()); } - + } diff --git a/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleDataWithSprite.java b/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleDataWithSprite.java index 75d9121f00..b504bc8a20 100644 --- a/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleDataWithSprite.java +++ b/src/main/java/com/simibubi/create/foundation/particle/ICustomParticleDataWithSprite.java @@ -7,6 +7,7 @@ import net.minecraft.client.particle.ParticleProvider; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleOptions.Deserializer; import net.minecraft.core.particles.ParticleType; + import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.RegisterParticleProvidersEvent; @@ -14,9 +15,9 @@ import net.minecraftforge.client.event.RegisterParticleProvidersEvent; public interface ICustomParticleDataWithSprite extends ICustomParticleData { Deserializer getDeserializer(); - + public default ParticleType createType() { - return new ParticleType(false, getDeserializer()) { + return new ParticleType<>(false, getDeserializer()) { @Override public Codec codec() { @@ -24,20 +25,20 @@ public interface ICustomParticleDataWithSprite extend } }; } - + @Override @OnlyIn(Dist.CLIENT) default ParticleProvider getFactory() { throw new IllegalAccessError("This particle type uses a metaFactory!"); } - + @OnlyIn(Dist.CLIENT) public SpriteParticleRegistration getMetaFactory(); - + @Override @OnlyIn(Dist.CLIENT) public default void register(ParticleType type, RegisterParticleProvidersEvent event) { event.registerSpriteSet(type, getMetaFactory()); } - + } diff --git a/src/main/java/com/simibubi/create/infrastructure/command/HighlightCommand.java b/src/main/java/com/simibubi/create/infrastructure/command/HighlightCommand.java index e4c9126114..4cd66f0a43 100644 --- a/src/main/java/com/simibubi/create/infrastructure/command/HighlightCommand.java +++ b/src/main/java/com/simibubi/create/infrastructure/command/HighlightCommand.java @@ -21,6 +21,7 @@ import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; + import net.minecraftforge.common.ForgeMod; import net.minecraftforge.network.PacketDistributor; @@ -60,9 +61,9 @@ public class HighlightCommand { private static void sendMissMessage(CommandSourceStack source) { source.sendSuccess(() -> - { - return Component.literal("Try looking at a Block that has failed to assemble a Contraption and try again."); - }, + { + return Component.literal("Try looking at a Block that has failed to assemble a Contraption and try again."); + }, true); } @@ -83,12 +84,11 @@ public class HighlightCommand { BlockPos pos = ray.getBlockPos(); BlockEntity be = world.getBlockEntity(pos); - if (!(be instanceof IDisplayAssemblyExceptions)) { + if (!(be instanceof IDisplayAssemblyExceptions display)) { sendMissMessage(source); return 0; } - IDisplayAssemblyExceptions display = (IDisplayAssemblyExceptions) be; AssemblyException exception = display.getLastAssemblyException(); if (exception == null) { sendMissMessage(source); @@ -97,8 +97,8 @@ public class HighlightCommand { if (!exception.hasPosition()) { source.sendSuccess(() -> { - return Component.literal("Can't highlight a specific position for this issue"); - }, true); + return Component.literal("Can't highlight a specific position for this issue"); + }, true); return Command.SINGLE_SUCCESS; } diff --git a/src/main/java/com/simibubi/create/infrastructure/command/ReplaceInCommandBlocksCommand.java b/src/main/java/com/simibubi/create/infrastructure/command/ReplaceInCommandBlocksCommand.java index 65ba7a099a..3470a7009c 100644 --- a/src/main/java/com/simibubi/create/infrastructure/command/ReplaceInCommandBlocksCommand.java +++ b/src/main/java/com/simibubi/create/infrastructure/command/ReplaceInCommandBlocksCommand.java @@ -1,7 +1,5 @@ package com.simibubi.create.infrastructure.command; -import net.minecraft.network.chat.Component; - import org.apache.commons.lang3.mutable.MutableInt; import com.mojang.brigadier.arguments.StringArgumentType; @@ -11,6 +9,7 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.coordinates.BlockPosArgument; import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.BaseCommandBlock; import net.minecraft.world.level.block.CommandBlock; @@ -38,7 +37,7 @@ public class ReplaceInCommandBlocksCommand { } private static void doReplace(CommandSourceStack source, BlockPos from, BlockPos to, String toReplace, - String replaceWith) { + String replaceWith) { ServerLevel world = source.getLevel(); MutableInt blocks = new MutableInt(0); BlockPos.betweenClosedStream(from, to) @@ -47,9 +46,8 @@ public class ReplaceInCommandBlocksCommand { if (!(blockState.getBlock() instanceof CommandBlock)) return; BlockEntity blockEntity = world.getBlockEntity(pos); - if (!(blockEntity instanceof CommandBlockEntity)) + if (!(blockEntity instanceof CommandBlockEntity cb)) return; - CommandBlockEntity cb = (CommandBlockEntity) blockEntity; BaseCommandBlock commandBlockLogic = cb.getCommandBlock(); String command = commandBlockLogic.getCommand(); if (command.indexOf(toReplace) != -1) @@ -61,13 +59,13 @@ public class ReplaceInCommandBlocksCommand { int intValue = blocks.intValue(); if (intValue == 0) { source.sendSuccess(() -> { - return Component.literal("Couldn't find \"" + toReplace + "\" anywhere."); - }, true); + return Component.literal("Couldn't find \"" + toReplace + "\" anywhere."); + }, true); return; } source.sendSuccess(() -> { - return Component.literal("Replaced occurrences in " + intValue + " blocks."); - }, true); + return Component.literal("Replaced occurrences in " + intValue + " blocks."); + }, true); } } diff --git a/src/main/java/com/simibubi/create/infrastructure/ponder/scenes/ItemVaultScenes.java b/src/main/java/com/simibubi/create/infrastructure/ponder/scenes/ItemVaultScenes.java index 7e459f60ba..6610d21f28 100644 --- a/src/main/java/com/simibubi/create/infrastructure/ponder/scenes/ItemVaultScenes.java +++ b/src/main/java/com/simibubi/create/infrastructure/ponder/scenes/ItemVaultScenes.java @@ -60,8 +60,8 @@ public class ItemVaultScenes { ItemStack hand = AllItems.BRASS_HAND.asStack(); scene.overlay().showControls(util.vector().blockSurface(frontVault, Direction.NORTH), Pointing.RIGHT, 40) - .showing(AllIcons.I_MTD_CLOSE) - .withItem(hand); + .showing(AllIcons.I_MTD_CLOSE) + .withItem(hand); scene.idle(7); scene.overlay().showText(60) @@ -85,7 +85,7 @@ public class ItemVaultScenes { .pointAt(util.vector().topOf(2, 2, 3)); ItemStack[] junk = - { new ItemStack(Items.APPLE), new ItemStack(Items.GOLD_INGOT, 8), new ItemStack(Items.TUFF, 32) }; + {new ItemStack(Items.APPLE), new ItemStack(Items.GOLD_INGOT, 8), new ItemStack(Items.TUFF, 32)}; for (int i = 0; i < junk.length + 2; i++) { scene.idle(4); @@ -111,8 +111,8 @@ public class ItemVaultScenes { .placeNearTarget() .pointAt(util.vector().topOf(2, 1, 1)); - for (int i = 0; i < junk.length; i++) { - scene.world().createItemOnBeltLike(util.grid().at(2, 1, 1), Direction.EAST, junk[i]); + for (ItemStack stack : junk) { + scene.world().createItemOnBeltLike(util.grid().at(2, 1, 1), Direction.EAST, stack); scene.idle(18); }